<?php

declare(strict_types=1);

namespace Admin\Controllers;

use App\Core\Controller;

/**
 * AdminBatchScheduleController — Admin management of batch schedules
 */
class AdminBatchScheduleController extends AdminController
{
    /**
     * List all batch schedules.
     */
    public function index(): never
    {
        $model = $this->model('BatchSchedule');

        // Auto-update statuses
        try { $model->autoUpdateStatuses(); } catch (\Throwable $e) { }

        $batches = $model->getAllWithCourse();

        $this->adminView('batch_schedules', [
            'title'       => 'Batch Schedules',
            'currentPage' => 'batch-schedules',
            'batches'     => $batches,
        ]);
    }

    /**
     * Show create form.
     */
    public function create(): never
    {
        $courses = [];
        try {
            $courseModel = $this->model('Course');
            $courses = $courseModel->where('active', 1);
        } catch (\Throwable $e) { }

        $this->adminView('batch_schedule_form', [
            'title'       => 'Add New Batch',
            'currentPage' => 'batch-schedules',
            'batch'       => null,
            'courses'     => $courses,
        ]);
    }

    /**
     * Store a new batch schedule.
     */
    public function store(): never
    {
        $this->validateCsrf();

        $batchName      = trim($_POST['batch_name'] ?? '');
        $courseId       = (int) ($_POST['course_id'] ?? 0) ?: null;
        $startDate      = trim($_POST['start_date'] ?? '');
        $endDate        = trim($_POST['end_date'] ?? '') ?: null;
        $timing         = trim($_POST['timing'] ?? '');
        $days           = trim($_POST['days'] ?? '');
        $seatsTotal     = (int) ($_POST['seats_total'] ?? 0);
        $seatsAvailable = (int) ($_POST['seats_available'] ?? 0);
        $fee            = trim($_POST['fee'] ?? '') ?: null;
        $description    = trim($_POST['description'] ?? '') ?: null;
        $status         = trim($_POST['status'] ?? 'upcoming');
        $isFeatured     = (int) ($_POST['is_featured'] ?? 0);
        $showCountdown  = (int) ($_POST['show_countdown'] ?? 0);
        $sortOrder      = (int) ($_POST['sort_order'] ?? 0);

        if (empty($batchName) || empty($startDate)) {
            flash('error', 'Batch name and start date are required.');
            redirect(BASE_PATH . '/admin/batch-schedules/create');
        }

        $model = $this->model('BatchSchedule');
        $model->create([
            'batch_name'      => $batchName,
            'course_id'       => $courseId,
            'start_date'      => $startDate,
            'end_date'        => $endDate,
            'timing'          => $timing ?: null,
            'days'            => $days ?: null,
            'seats_total'     => $seatsTotal,
            'seats_available' => $seatsAvailable,
            'fee'             => $fee,
            'description'     => $description,
            'status'          => $status,
            'is_featured'     => $isFeatured,
            'show_countdown'  => $showCountdown,
            'sort_order'      => $sortOrder,
        ]);

        flash('success', 'Batch schedule added successfully.');
        redirect(BASE_PATH . '/admin/batch-schedules');
    }

    /**
     * Show edit form.
     */
    public function edit(int $id): never
    {
        $model = $this->model('BatchSchedule');
        $batch = $model->find($id);

        if (!$batch) {
            flash('error', 'Batch not found.');
            redirect(BASE_PATH . '/admin/batch-schedules');
        }

        $courses = [];
        try {
            $courseModel = $this->model('Course');
            $courses = $courseModel->where('active', 1);
        } catch (\Throwable $e) { }

        $this->adminView('batch_schedule_form', [
            'title'       => 'Edit Batch Schedule',
            'currentPage' => 'batch-schedules',
            'batch'       => $batch,
            'courses'     => $courses,
        ]);
    }

    /**
     * Update a batch schedule.
     */
    public function update(int $id): never
    {
        $this->validateCsrf();

        $model = $this->model('BatchSchedule');
        $batch = $model->find($id);

        if (!$batch) {
            flash('error', 'Batch not found.');
            redirect(BASE_PATH . '/admin/batch-schedules');
        }

        $batchName      = trim($_POST['batch_name'] ?? '');
        $courseId       = (int) ($_POST['course_id'] ?? 0) ?: null;
        $startDate      = trim($_POST['start_date'] ?? '');
        $endDate        = trim($_POST['end_date'] ?? '') ?: null;
        $timing         = trim($_POST['timing'] ?? '');
        $days           = trim($_POST['days'] ?? '');
        $seatsTotal     = (int) ($_POST['seats_total'] ?? 0);
        $seatsAvailable = (int) ($_POST['seats_available'] ?? 0);
        $fee            = trim($_POST['fee'] ?? '') ?: null;
        $description    = trim($_POST['description'] ?? '') ?: null;
        $status         = trim($_POST['status'] ?? 'upcoming');
        $isFeatured     = (int) ($_POST['is_featured'] ?? 0);
        $showCountdown  = (int) ($_POST['show_countdown'] ?? 0);
        $sortOrder      = (int) ($_POST['sort_order'] ?? 0);

        if (empty($batchName) || empty($startDate)) {
            flash('error', 'Batch name and start date are required.');
            redirect(BASE_PATH . "/admin/batch-schedules/{$id}/edit");
        }

        $model->update($id, [
            'batch_name'      => $batchName,
            'course_id'       => $courseId,
            'start_date'      => $startDate,
            'end_date'        => $endDate,
            'timing'          => $timing ?: null,
            'days'            => $days ?: null,
            'seats_total'     => $seatsTotal,
            'seats_available' => $seatsAvailable,
            'fee'             => $fee,
            'description'     => $description,
            'status'          => $status,
            'is_featured'     => $isFeatured,
            'show_countdown'  => $showCountdown,
            'sort_order'      => $sortOrder,
        ]);

        flash('success', 'Batch schedule updated successfully.');
        redirect(BASE_PATH . '/admin/batch-schedules');
    }

    /**
     * Delete a batch schedule.
     */
    public function delete(int $id): never
    {
        $this->validateCsrf();

        $model = $this->model('BatchSchedule');
        $model->delete($id);

        flash('success', 'Batch schedule deleted.');
        redirect(BASE_PATH . '/admin/batch-schedules');
    }
}
