<?php
class WaitingListController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $membershipTypes = $db->fetchAll("SELECT id, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('waiting-list/index', [
            'title' => lang('applications.waiting_list'),
            'breadcrumbs' => [
                ['label' => lang('applications.title'), 'url' => '/applications'],
                ['label' => lang('applications.waiting_list')]
            ],
            'membershipTypes' => $membershipTypes,
        ]);
    }

    public function createEntry(Request $request): void
    {
        $db = $this->db();
        $waitingLists = $db->fetchAll(
            "SELECT wl.*, mt.name_en as type_name_en, mt.name_ar as type_name_ar
             FROM waiting_lists wl
             JOIN membership_types mt ON wl.membership_type_id = mt.id
             WHERE wl.is_open = 1 ORDER BY mt.sort_order"
        );

        $this->view('waiting-list/create-entry', [
            'title' => lang('applications.add_to_waitlist'),
            'breadcrumbs' => [
                ['label' => lang('applications.title'), 'url' => '/applications'],
                ['label' => lang('applications.waiting_list'), 'url' => '/waiting-list'],
                ['label' => lang('applications.add_to_waitlist')]
            ],
            'waitingLists' => $waitingLists,
        ]);
    }

    public function storeEntry(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
            return;
        }

        $validator = new Validator($request->all(), [
            'waiting_list_id' => 'required|integer|exists:waiting_lists,id',
            'applicant_name'  => 'required|string|max:300',
            'applicant_phone' => 'required|string|max:20',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $db = $this->db();
        $listId = (int) $request->post('waiting_list_id');

        $list = $db->fetchOne("SELECT * FROM waiting_lists WHERE id = ? AND is_open = 1", [$listId]);
        if (!$list) {
            $this->json(['success' => false, 'message' => 'Waiting list is not open'], 422);
            return;
        }

        if ($list['max_entries'] && $list['current_entries'] >= $list['max_entries']) {
            $this->json(['success' => false, 'message' => 'Waiting list is full'], 422);
            return;
        }

        $maxQueue = (int) $db->fetchColumn(
            "SELECT COALESCE(MAX(queue_number), 0) FROM waiting_list_entries WHERE waiting_list_id = ?",
            [$listId]
        );

        $entryId = $db->insert('waiting_list_entries', [
            'waiting_list_id'        => $listId,
            'queue_number'           => $maxQueue + 1,
            'applicant_name'         => $request->post('applicant_name'),
            'applicant_phone'        => $request->post('applicant_phone'),
            'applicant_email'        => $request->post('applicant_email') ?: null,
            'applicant_national_id'  => $request->post('applicant_national_id') ?: null,
            'registration_date'      => date('Y-m-d'),
            'priority'               => $request->post('priority', 'normal'),
            'status'                 => 'waiting',
            'notes'                  => $request->post('notes') ?: null,
        ]);

        $this->audit('create', 'waiting_list_entries', $entryId, "Added to waiting list #{$listId}");
        $this->json(['success' => true, 'message' => lang('applications.added_to_waitlist'), 'redirect' => '/waiting-list']);
    }
}