<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\EmployeeCard;
use App\Models\User;
use App\Services\CardPdfService;
use App\Services\QrCardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class EmployeeCardController extends Controller
{
    public function __construct(
        protected QrCardService $qrCardService,
        protected CardPdfService $cardPdfService
    ) {}

    /**
     * Get current user's active card.
     */
    public function myCard(Request $request): JsonResponse
    {
        $user = $request->user();

        // Check if QR card feature is enabled
        if (!$user->company->qr_card_enabled) {
            return response()->json([
                'success' => false,
                'message' => 'Fitur kartu karyawan tidak diaktifkan',
            ], 403);
        }

        $card = $user->activeEmployeeCard;

        if (!$card) {
            return response()->json([
                'success' => false,
                'message' => 'Anda belum memiliki kartu karyawan. Silakan hubungi admin.',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'card' => [
                    'id' => $card->id,
                    'card_number' => $card->card_number,
                    'qr_data' => $card->qr_data,
                    'status' => $card->card_status,
                    'issued_at' => $card->issued_at?->toIso8601String(),
                    'expires_at' => $card->expires_at?->toIso8601String(),
                ],
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'employee_id' => $user->employee_id,
                    'nip' => $user->nip,
                    'position' => $user->position,
                    'department' => $user->department,
                    'avatar' => $user->avatar ? asset($user->avatar) : null,
                ],
                'company' => [
                    'id' => $user->company->id,
                    'name' => $user->company->name,
                    'logo' => $user->company->logo ? asset($user->company->logo) : null,
                ],
            ],
        ]);
    }

    /**
     * Get specific employee's card (admin only).
     */
    public function show(Request $request, string $id): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $card = EmployeeCard::with(['user', 'company'])->find($id);

        if (!$card) {
            return response()->json([
                'success' => false,
                'message' => 'Kartu tidak ditemukan',
            ], 404);
        }

        // Verify same company for non-super admin
        if (!$user->hasRole('super_admin') && $card->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'card' => $card,
                'user' => $card->user,
                'company' => $card->company,
            ],
        ]);
    }

    /**
     * Generate card for a user (admin only).
     */
    public function generate(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);

        $targetUser = User::find($request->user_id);

        // Verify same company for non-super admin
        if (!$user->hasRole('super_admin') && $targetUser->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        if (!$targetUser->is_active) {
            return response()->json([
                'success' => false,
                'message' => 'User tidak aktif',
            ], 400);
        }

        try {
            $card = $this->qrCardService->createCard($targetUser);

            return response()->json([
                'success' => true,
                'message' => 'Kartu berhasil dibuat',
                'data' => [
                    'card' => $card,
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal membuat kartu: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Generate cards for multiple users (admin only).
     */
    public function batchGenerate(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'user_ids' => 'required|array',
            'user_ids.*' => 'exists:users,id',
        ]);

        // Filter to same company for non-super admin
        $userIds = $request->user_ids;
        if (!$user->hasRole('super_admin')) {
            $userIds = User::whereIn('id', $userIds)
                ->where('company_id', $user->company_id)
                ->pluck('id')
                ->toArray();
        }

        $result = $this->qrCardService->batchCreateCards($userIds);

        return response()->json([
            'success' => true,
            'message' => "{$result['created']} kartu berhasil dibuat",
            'data' => $result,
        ]);
    }

    /**
     * Download card as PDF.
     */
    public function downloadPdf(Request $request, string $id): Response|JsonResponse
    {
        $user = $request->user();
        $card = EmployeeCard::find($id);

        if (!$card) {
            return response()->json([
                'success' => false,
                'message' => 'Kartu tidak ditemukan',
            ], 404);
        }

        // User can only download own card, admin can download any card in company
        $canDownload = $card->user_id === $user->id;
        if (!$canDownload && $user->hasRole(['admin', 'super_admin'])) {
            $canDownload = $user->hasRole('super_admin') || $card->company_id === $user->company_id;
        }

        if (!$canDownload) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        try {
            $pdf = $this->cardPdfService->generateCardPdf($card);

            return response($pdf, 200, [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => 'attachment; filename="kartu-' . $card->card_number . '.pdf"',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal generate PDF: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Revoke a card (admin only).
     */
    public function revoke(Request $request, string $id): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'reason' => 'nullable|string|max:255',
        ]);

        $card = EmployeeCard::find($id);

        if (!$card) {
            return response()->json([
                'success' => false,
                'message' => 'Kartu tidak ditemukan',
            ], 404);
        }

        // Verify same company for non-super admin
        if (!$user->hasRole('super_admin') && $card->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        if ($card->card_status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => 'Kartu sudah tidak aktif',
            ], 400);
        }

        $card->revoke($request->reason);

        return response()->json([
            'success' => true,
            'message' => 'Kartu berhasil dicabut',
        ]);
    }

    /**
     * List all cards (admin only).
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $query = EmployeeCard::with(['user'])
            ->orderBy('created_at', 'desc');

        // Filter by company for non-super admin
        if (!$user->hasRole('super_admin')) {
            $query->where('company_id', $user->company_id);
        }

        // Apply filters
        if ($request->has('status')) {
            $query->where('card_status', $request->status);
        }

        if ($request->has('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        $cards = $query->paginate($request->get('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $cards,
        ]);
    }
}
