<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Members\Services\MembershipValidationService;
use App\Modules\Carnets\Models\CarnetGuestEntry;
use App\Modules\Carnets\Services\GuestEntryService;

class ServiceDeskController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('sa.registration.manage');

        $activityTypes = CarnetGuestEntry::getActivityTypes();

        $db = App::getInstance()->db();
        $facilities = $db->select(
            "SELECT id, name_ar FROM sa_facilities WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC",
            []
        );

        return $this->view('SportsActivity.Views.service-desk.index', [
            'activityTypes' => $activityTypes,
            'facilities'    => $facilities,
        ]);
    }

    public function lookup(Request $request): Response
    {
        $this->authorize('sa.registration.manage');

        $nationalId = trim((string) $request->post('national_id', ''));
        if ($nationalId === '') {
            return $this->json(['success' => false, 'error' => 'الرقم القومي مطلوب']);
        }

        $result = MembershipValidationService::checkByNationalId($nationalId);
        $db = App::getInstance()->db();

        $player = $db->selectOne(
            "SELECT id, full_name_ar, registration_serial, player_type FROM sa_players WHERE national_id = ? LIMIT 1",
            [$nationalId]
        );

        $carnet = null;
        if (!empty($result['member_id'])) {
            $carnet = $db->selectOne(
                "SELECT c.id, c.max_invitations,
                        (SELECT COUNT(*) FROM carnet_guest_entries cge WHERE cge.carnet_id = c.id AND cge.status != 'cancelled') as used_count
                 FROM carnets c
                 WHERE c.member_id = ? AND c.status = 'active'
                 ORDER BY c.created_at DESC LIMIT 1",
                [(int) $result['member_id']]
            );
        }

        return $this->json([
            'success'    => true,
            'membership' => $result,
            'player'     => $player,
            'carnet'     => $carnet,
        ]);
    }

    public function issueTicket(Request $request): Response
    {
        $this->authorize('sa.registration.manage');

        $activityType = trim((string) $request->post('activity_type', ''));
        $guestName = trim((string) $request->post('guest_name', ''));
        $guestCount = max(1, (int) $request->post('guest_count', 1));
        $amountPaid = (float) $request->post('amount_paid', 0);
        $facilityId = $request->post('facility_id', '') !== '' ? (int) $request->post('facility_id') : null;
        $carnetId = $request->post('carnet_id', '') !== '' ? (int) $request->post('carnet_id') : null;
        $memberId = $request->post('member_id', '') !== '' ? (int) $request->post('member_id') : null;
        $notes = trim((string) $request->post('notes', ''));

        if ($activityType === '' || !array_key_exists($activityType, CarnetGuestEntry::getActivityTypes())) {
            return $this->json(['success' => false, 'error' => 'نوع النشاط غير صالح']);
        }
        if ($guestName === '') {
            return $this->json(['success' => false, 'error' => 'اسم الضيف مطلوب']);
        }

        $employee = App::getInstance()->currentEmployee();

        if ($carnetId) {
            $eligibilityErrors = GuestEntryService::checkEligibility($carnetId);
            if (!empty($eligibilityErrors)) {
                return $this->json(['success' => false, 'error' => implode(' | ', $eligibilityErrors)]);
            }
        }

        try {
            $entry = GuestEntryService::recordEntry([
                'carnet_id'         => $carnetId,
                'member_id'         => $memberId,
                'guest_name'        => $guestName,
                'guest_phone'       => trim((string) $request->post('guest_phone', '')),
                'guest_national_id' => '',
                'guest_count'       => $guestCount,
                'entry_date'        => date('Y-m-d'),
                'entry_time'        => date('H:i:s'),
                'facility_id'       => $facilityId,
                'activity_type'     => $activityType,
                'amount_paid'       => $amountPaid,
                'notes'             => $notes,
                'recorded_by'       => $employee ? (int) $employee->id : null,
                'status'            => 'active',
            ]);
        } catch (\Throwable $e) {
            return $this->json(['success' => false, 'error' => 'فشل الإصدار: ' . $e->getMessage()]);
        }

        return $this->json([
            'success' => true,
            'entry_id' => (int) $entry->id,
            'message' => 'تم إصدار التذكرة بنجاح',
        ]);
    }
}
