<?php
declare(strict_types=1);

namespace App\Modules\Carnets\Controllers;

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

class GuestEntryController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('carnet.view_guests');

        $filters = [
            'search'        => trim((string) $request->get('q', '')),
            'member_id'     => $request->get('member_id', ''),
            'facility_id'   => $request->get('facility_id', ''),
            'activity_type' => $request->get('activity_type', ''),
            'date_from'     => $request->get('date_from', ''),
            'date_to'       => $request->get('date_to', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));

        $result = CarnetGuestEntry::search($filters, 25, $page);

        $db = App::getInstance()->db();
        $facilities = $db->select("SELECT id, name_ar FROM facilities WHERE is_archived = 0 ORDER BY name_ar");

        return $this->view('Carnets.Views.guest_entries', [
            'rows'           => $result['data'],
            'pagination'     => $result['pagination'],
            'filters'        => $filters,
            'facilities'     => $facilities,
            'activityTypes'  => CarnetGuestEntry::getActivityTypes(),
        ]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('carnet.record_guest');

        $db = App::getInstance()->db();
        $facilities = $db->select("SELECT id, name_ar FROM facilities WHERE is_archived = 0 ORDER BY name_ar");

        $memberId = $request->get('member_id');
        $carnet = null;
        $member = null;

        if ($memberId) {
            $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
            if ($member) {
                $carnet = $db->selectOne("SELECT * FROM carnets WHERE member_id = ? AND is_active = 1 ORDER BY id DESC LIMIT 1", [(int) $memberId]);
            }
        }

        return $this->view('Carnets.Views.guest_entry_create', [
            'facilities'    => $facilities,
            'activityTypes' => CarnetGuestEntry::getActivityTypes(),
            'member'        => $member,
            'carnet'        => $carnet,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('carnet.record_guest');

        $rules = [
            'carnet_id'     => 'required|numeric',
            'guest_name'    => 'required|string|max:200',
            'activity_type' => 'required|string',
        ];

        $errors = $this->validate($request->all(), $rules);
        if ($errors) {
            return $this->redirect('/carnets/guest-entries/create?member_id=' . $request->post('member_id', ''))
                ->withError('يرجى تصحيح الأخطاء');
        }

        $carnetId = (int) $request->post('carnet_id');
        $eligibilityErrors = GuestEntryService::checkEligibility($carnetId);
        if (!empty($eligibilityErrors)) {
            return $this->redirect('/carnets/guest-entries/create?member_id=' . $request->post('member_id', ''))
                ->withError(implode(' | ', $eligibilityErrors));
        }

        $db = App::getInstance()->db();
        $carnet = $db->selectOne("SELECT * FROM carnets WHERE id = ?", [$carnetId]);
        $employee = App::getInstance()->currentEmployee();

        $entry = GuestEntryService::recordEntry([
            'carnet_id'        => $carnetId,
            'member_id'        => (int) $carnet['member_id'],
            'guest_name'       => trim((string) $request->post('guest_name')),
            'guest_phone'      => trim((string) $request->post('guest_phone', '')),
            'guest_national_id'=> trim((string) $request->post('guest_national_id', '')),
            'guest_count'      => max(1, (int) $request->post('guest_count', 1)),
            'entry_date'       => date('Y-m-d'),
            'entry_time'       => date('H:i:s'),
            'facility_id'      => $request->post('facility_id') ? (int) $request->post('facility_id') : null,
            'activity_type'    => $request->post('activity_type'),
            'amount_paid'      => (float) $request->post('amount_paid', 0),
            'notes'            => trim((string) $request->post('notes', '')),
            'recorded_by'      => $employee ? (int) $employee->id : null,
            'status'           => 'active',
        ]);

        $remaining = GuestEntryService::getRemainingInvitations($carnetId);
        return $this->redirect('/carnets/guest-entries')
            ->withSuccess("تم تسجيل دخول الضيف: {$request->post('guest_name')} — متبقي {$remaining} دعوة");
    }

    public function checkout(Request $request, string $id): Response
    {
        $this->authorize('carnet.record_guest');

        $success = GuestEntryService::checkOut((int) $id);
        if (!$success) {
            return $this->redirect('/carnets/guest-entries')->withError('لم يتم العثور على سجل دخول نشط');
        }

        return $this->redirect('/carnets/guest-entries')->withSuccess('تم تسجيل خروج الضيف');
    }

    public function cancel(Request $request, string $id): Response
    {
        $this->authorize('carnet.record_guest');

        $reason = trim((string) $request->post('reason', ''));
        $success = GuestEntryService::cancelEntry((int) $id, $reason);
        if (!$success) {
            return $this->redirect('/carnets/guest-entries')->withError('لم يتم العثور على سجل دخول نشط');
        }

        return $this->redirect('/carnets/guest-entries')->withSuccess('تم إلغاء دخول الضيف وإرجاع الدعوة');
    }

    public function memberSummary(Request $request, string $memberId): Response
    {
        $this->authorize('carnet.view_guests');

        $summary = GuestEntryService::getSummaryForMember((int) $memberId);

        return $this->json($summary);
    }
}
