<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

/**
 * Batch Model
 *
 * Handles batch schedule and timetable data.
 */
class Batch extends Model
{
    protected string $table = 'batches';

    /**
     * Get all active/upcoming batches with course and branch info.
     *
     * @return array<int, array<string, mixed>>
     */
    public function getActive(): array
    {
        $sql = "SELECT b.*, c.name AS course_name, c.category AS course_category,
                       br.name AS branch_name, br.city AS branch_city
                FROM `{$this->table}` b
                INNER JOIN `courses` c ON b.course_id = c.id
                LEFT JOIN `branches` br ON b.branch_id = br.id
                WHERE b.is_active = 1 AND b.status IN ('upcoming', 'ongoing')
                ORDER BY b.start_date ASC, b.shift ASC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();

        return $stmt->fetchAll();
    }

    /**
     * Get batches filtered by course and/or shift.
     *
     * @param int|null $courseId Filter by course ID
     * @param string|null $shift Filter by shift
     * @return array<int, array<string, mixed>>
     */
    public function getFiltered(?int $courseId = null, ?string $shift = null): array
    {
        $sql = "SELECT b.*, c.name AS course_name, c.category AS course_category,
                       br.name AS branch_name, br.city AS branch_city
                FROM `{$this->table}` b
                INNER JOIN `courses` c ON b.course_id = c.id
                LEFT JOIN `branches` br ON b.branch_id = br.id
                WHERE b.is_active = 1 AND b.status IN ('upcoming', 'ongoing')";

        $params = [];

        if ($courseId !== null && $courseId > 0) {
            $sql .= " AND b.course_id = :course_id";
            $params[':course_id'] = $courseId;
        }

        if ($shift !== null && $shift !== '') {
            $sql .= " AND b.shift = :shift";
            $params[':shift'] = $shift;
        }

        $sql .= " ORDER BY b.start_date ASC, b.shift ASC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);

        return $stmt->fetchAll();
    }

    /**
     * Decrease available seats when a booking is made.
     *
     * @param int $batchId The batch ID
     * @return bool True if seats were decremented
     */
    public function decrementSeats(int $batchId): bool
    {
        $sql = "UPDATE `{$this->table}` SET available_seats = available_seats - 1
                WHERE id = :id AND available_seats > 0";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':id' => $batchId]);
        return $stmt->rowCount() > 0;
    }
}
