<?php

class EventController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $planned  = (int) $db->fetchColumn("SELECT COUNT(*) FROM club_events WHERE status IN ('planned','registration_open')");
        $ongoing  = (int) $db->fetchColumn("SELECT COUNT(*) FROM club_events WHERE status = 'ongoing'");
        $completed = (int) $db->fetchColumn("SELECT COUNT(*) FROM club_events WHERE status = 'completed'");

        $this->view('events/index', [
            'title'       => lang('facilities.events'),
            'breadcrumbs' => [
                ['label' => lang('facilities.title'), 'url' => '/facilities'],
                ['label' => lang('facilities.events')],
            ],
            'planned'   => $planned,
            'ongoing'   => $ongoing,
            'completed' => $completed,
        ]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $facilities = $db->fetchAll("SELECT id, name_en, name_ar FROM facilities WHERE is_active = 1 ORDER BY name_en");

        $this->view('events/create', [
            'title'       => lang('facilities.create_event'),
            'breadcrumbs' => [
                ['label' => lang('facilities.title'), 'url' => '/facilities'],
                ['label' => lang('facilities.events'), 'url' => '/events'],
                ['label' => lang('facilities.create_event')],
            ],
            'facilities' => $facilities,
        ]);
    }

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

        $validator = new Validator($request->all(), [
            'title_en'           => 'required|string|max:500',
            'title_ar'           => 'nullable|string|max:500',
            'description_en'     => 'nullable|string',
            'description_ar'     => 'nullable|string',
            'event_type'         => 'required|in:social,sport,cultural,charity,celebration,workshop,competition,other',
            'facility_id'        => 'nullable|integer',
            'location'           => 'nullable|string|max:300',
            'start_datetime'     => 'required|string',
            'end_datetime'       => 'nullable|string',
            'registration_start' => 'nullable|string',
            'registration_end'   => 'nullable|string',
            'max_attendees'      => 'nullable|integer',
            'member_fee'         => 'nullable|decimal',
            'guest_fee'          => 'nullable|decimal',
            'allow_guests'       => 'nullable|boolean',
            'max_guests_per_member' => 'nullable|integer',
        ]);

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

        $data = $validator->validated();
        $data['event_code']    = SequenceGenerator::next('event_code');
        $data['allow_guests']  = isset($data['allow_guests']) ? 1 : 0;
        $data['fee']           = $data['member_fee'] ?? 0;
        $data['status']        = 'planned';
        $data['created_at']    = date('Y-m-d H:i:s');
        $data['created_by']    = Auth::id();

        $db = $this->db();
        $id = $db->insert('club_events', $data);
        $this->audit('create', 'club_events', $id, "Created event: {$data['title_en']}");

        $this->json(['success' => true, 'message' => lang('facilities.event_created'), 'redirect' => "/events/{$id}"]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();

        $event = $db->fetchOne(
            "SELECT e.*, f.name_en AS facility_name_en, f.name_ar AS facility_name_ar
             FROM club_events e
             LEFT JOIN facilities f ON e.facility_id = f.id
             WHERE e.id = ?",
            [$id]
        );
        if (!$event) {
            $this->abort(404, 'Event not found');
        }

        $registrations = $db->fetchAll(
            "SELECT r.*, m.full_name_en AS member_name, m.membership_number
             FROM club_event_registrations r
             LEFT JOIN members m ON r.member_id = m.id
             WHERE r.event_id = ?
             ORDER BY r.registration_date DESC",
            [$id]
        );

        $this->view('events/show', [
            'title'       => $event['title_en'],
            'breadcrumbs' => [
                ['label' => lang('facilities.title'), 'url' => '/facilities'],
                ['label' => lang('facilities.events'), 'url' => '/events'],
                ['label' => $event['title_en']],
            ],
            'event'         => $event,
            'registrations' => $registrations,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $event = $db->fetchOne("SELECT * FROM club_events WHERE id = ?", [$id]);
        if (!$event) {
            $this->abort(404);
        }
        $facilities = $db->fetchAll("SELECT id, name_en, name_ar FROM facilities WHERE is_active = 1 ORDER BY name_en");

        $this->view('events/edit', [
            'title'       => lang('common.edit') . ': ' . $event['title_en'],
            'breadcrumbs' => [
                ['label' => lang('facilities.title'), 'url' => '/facilities'],
                ['label' => lang('facilities.events'), 'url' => '/events'],
                ['label' => $event['title_en'], 'url' => "/events/{$id}"],
                ['label' => lang('common.edit')],
            ],
            'event'      => $event,
            'facilities' => $facilities,
        ]);
    }

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

        $db  = $this->db();
        $old = $db->fetchOne("SELECT * FROM club_events WHERE id = ?", [$id]);
        if (!$old) {
            $this->json(['success' => false, 'message' => 'Event not found'], 404);
            return;
        }

        $validator = new Validator($request->all(), [
            'title_en'           => 'required|string|max:500',
            'title_ar'           => 'nullable|string|max:500',
            'description_en'     => 'nullable|string',
            'description_ar'     => 'nullable|string',
            'event_type'         => 'required|in:social,sport,cultural,charity,celebration,workshop,competition,other',
            'facility_id'        => 'nullable|integer',
            'location'           => 'nullable|string|max:300',
            'start_datetime'     => 'required|string',
            'end_datetime'       => 'nullable|string',
            'max_attendees'      => 'nullable|integer',
            'member_fee'         => 'nullable|decimal',
            'guest_fee'          => 'nullable|decimal',
            'allow_guests'       => 'nullable|boolean',
            'status'             => 'nullable|in:planned,registration_open,registration_closed,ongoing,completed,cancelled,postponed',
        ]);

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

        $data = $validator->validated();
        $data['allow_guests'] = isset($data['allow_guests']) ? 1 : 0;
        $data['fee']          = $data['member_fee'] ?? $old['fee'];
        $data['updated_at']   = date('Y-m-d H:i:s');

        $db->update('club_events', $data, 'id = ?', [$id]);
        $this->audit('update', 'club_events', $id, "Updated event: {$data['title_en']}", $old, $data);

        $this->json(['success' => true, 'message' => lang('facilities.event_updated'), 'redirect' => "/events/{$id}"]);
    }

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

        $memberId = (int) $request->post('member_id');
        if (!$memberId) {
            $this->json(['success' => false, 'message' => 'Member is required'], 422);
            return;
        }

        $db    = $this->db();
        $event = $db->fetchOne("SELECT * FROM club_events WHERE id = ?", [$eventId]);
        if (!$event) {
            $this->json(['success' => false, 'message' => 'Event not found'], 404);
            return;
        }

        if ($event['max_attendees'] && $event['current_attendees'] >= $event['max_attendees']) {
            $this->json(['success' => false, 'message' => lang('facilities.event_full')], 422);
            return;
        }

        $existing = $db->fetchColumn(
            "SELECT COUNT(*) FROM club_event_registrations WHERE event_id = ? AND member_id = ? AND status NOT IN ('cancelled')",
            [$eventId, $memberId]
        );
        if ($existing > 0) {
            $this->json(['success' => false, 'message' => lang('facilities.already_registered')], 422);
            return;
        }

        $totalGuests = (int) $request->post('guest_count', 0);
        $totalAttendees = 1 + $totalGuests;
        $totalFee = (float) $event['member_fee'] + ($totalGuests * (float) $event['guest_fee']);

        $regData = [
            'event_id'          => $eventId,
            'member_id'         => $memberId,
            'total_attendees'   => $totalAttendees,
            'total_fee'         => $totalFee,
            'registration_date' => date('Y-m-d H:i:s'),
            'status'            => 'registered',
            'notes'             => $request->post('notes', ''),
        ];

        $regId = $db->insert('club_event_registrations', $regData);

        $db->execute("UPDATE club_events SET current_attendees = current_attendees + ? WHERE id = ?", [$totalAttendees, $eventId]);

        $this->audit('create', 'club_event_registrations', $regId, "Registered member #{$memberId} for event #{$eventId}");

        $this->json(['success' => true, 'message' => lang('facilities.registration_success')]);
    }

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

        $registrationId = (int) $request->post('registration_id');
        $db = $this->db();

        $reg = $db->fetchOne("SELECT * FROM club_event_registrations WHERE id = ? AND event_id = ?", [$registrationId, $eventId]);
        if (!$reg) {
            $this->json(['success' => false, 'message' => 'Registration not found'], 404);
            return;
        }

        $db->update('club_event_registrations', [
            'status'      => 'attended',
            'check_in_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$registrationId]);

        $this->audit('update', 'club_event_registrations', $registrationId, "Checked in registration #{$registrationId}");
        $this->json(['success' => true, 'message' => lang('facilities.checkin_success')]);
    }
}