<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class ProgramDayModel extends Model
{
    public function byConference(int $conferenceId): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM conference_program_days
            WHERE conference_id = :conference_id
            ORDER BY program_date ASC, sort_order ASC, id ASC
        ");
        $stmt->execute([':conference_id' => $conferenceId]);
        return $stmt->fetchAll();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM conference_program_days WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO conference_program_days (conference_id, program_date, title_en, title_ar, sort_order, is_active)
            VALUES (:conference_id, :program_date, :title_en, :title_ar, :sort_order, :is_active)
        ");
        $stmt->execute([
            ':conference_id' => $data['conference_id'],
            ':program_date' => $data['program_date'],
            ':title_en' => $data['title_en'] ?: null,
            ':title_ar' => $data['title_ar'] ?: null,
            ':sort_order' => $data['sort_order'] ?? 0,
            ':is_active' => !empty($data['is_active']) ? 1 : 0,
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        $stmt = $this->db->prepare("
            UPDATE conference_program_days
            SET conference_id = :conference_id,
                program_date = :program_date,
                title_en = :title_en,
                title_ar = :title_ar,
                sort_order = :sort_order,
                is_active = :is_active
            WHERE id = :id
        ");
        $stmt->execute([
            ':id' => $id,
            ':conference_id' => $data['conference_id'],
            ':program_date' => $data['program_date'],
            ':title_en' => $data['title_en'] ?: null,
            ':title_ar' => $data['title_ar'] ?: null,
            ':sort_order' => $data['sort_order'] ?? 0,
            ':is_active' => !empty($data['is_active']) ? 1 : 0,
        ]);
    }
}
