<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Batch Schedule Controller
 *
 * Handles public batch schedule display and seat booking.
 */
class BatchController extends Controller
{
    /**
     * Display batch schedule with filters.
     *
     * @return void
     */
    public function index(): void
    {
        $courseModel = $this->model('Course');
        $batchModel  = $this->model('Batch');

        $courses = [];
        $batches = [];

        try {
            $courses = $courseModel->where('active', 1);
        } catch (\Throwable $e) {
            error_log('Batch schedule courses error: ' . $e->getMessage());
        }

        try {
            $courseFilter = (int) ($_GET['course_id'] ?? 0);
            $shiftFilter  = sanitize($_GET['shift'] ?? '');

            if ($courseFilter > 0 || $shiftFilter !== '') {
                $batches = $batchModel->getFiltered($courseFilter > 0 ? $courseFilter : null, $shiftFilter !== '' ? $shiftFilter : null);
            } else {
                $batches = $batchModel->getActive();
            }
        } catch (\Throwable $e) {
            error_log('Batch schedule error: ' . $e->getMessage());
        }

        $this->view('batch-schedule/index', [
            'title'      => 'Batch Schedule - Gmind Institute',
            'courses'    => $courses,
            'batches'    => $batches,
            'currentPage' => 'batch-schedule',
        ]);
    }

    /**
     * Book a seat in a batch (AJAX POST).
     *
     * @return void
     */
    public function bookSeat(): void
    {
        $batchId     = (int) ($_POST['batch_id'] ?? 0);
        $studentName = sanitize($_POST['student_name'] ?? '');
        $contact     = sanitize($_POST['contact'] ?? '');
        $email       = sanitize($_POST['email'] ?? '');

        if ($batchId <= 0 || empty($studentName) || empty($contact)) {
            if ($this->isAjax()) {
                $this->json(['success' => false, 'message' => 'All required fields must be filled.'], 422);
            }
            flash('error', 'All required fields must be filled.');
            redirect(BASE_PATH . '/batch-schedule');
            return;
        }

        if (!preg_match('/^[0-9]{10}$/', $contact)) {
            if ($this->isAjax()) {
                $this->json(['success' => false, 'message' => 'Please enter a valid 10-digit contact number.'], 422);
            }
            flash('error', 'Please enter a valid 10-digit contact number.');
            redirect(BASE_PATH . '/batch-schedule');
            return;
        }

        try {
            $bookingModel = $this->model('SeatBooking');

            // Check duplicate
            if ($bookingModel->hasBooking($batchId, $contact)) {
                if ($this->isAjax()) {
                    $this->json(['success' => false, 'message' => 'You have already booked a seat in this batch.']);
                }
                flash('warning', 'You have already booked a seat in this batch.');
                redirect(BASE_PATH . '/batch-schedule');
                return;
            }

            // Create booking
            $bookingModel->create([
                'batch_id'     => $batchId,
                'student_name' => $studentName,
                'contact'      => $contact,
                'email'        => $email ?: null,
                'status'       => 'booked',
            ]);

            // Decrease available seats
            $batchModel = $this->model('Batch');
            $batchModel->decrementSeats($batchId);

            if ($this->isAjax()) {
                $this->json(['success' => true, 'message' => 'Seat booked successfully! We will contact you with details.']);
            }

            flash('success', 'Seat booked successfully! We will contact you with details.');
            redirect(BASE_PATH . '/batch-schedule');
        } catch (\Throwable $e) {
            error_log('Seat booking error: ' . $e->getMessage());

            if ($this->isAjax()) {
                $this->json(['success' => false, 'message' => 'Something went wrong. Please try again.'], 500);
            }

            flash('error', 'Something went wrong. Please try again.');
            redirect(BASE_PATH . '/batch-schedule');
        }
    }

    /**
     * Check if request is AJAX.
     *
     * @return bool
     */
    private function isAjax(): bool
    {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}
