<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class ConferenceRoomModel extends Model
{
    public function byConference(int $conferenceId): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM conference_rooms
            WHERE conference_id = :conference_id
            ORDER BY 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_rooms 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_rooms (
                conference_id, room_name_en, room_name_ar, location_en, location_ar, capacity, sort_order, is_active
            ) VALUES (
                :conference_id, :room_name_en, :room_name_ar, :location_en, :location_ar, :capacity, :sort_order, :is_active
            )
        ");
        $stmt->execute([
            ':conference_id' => $data['conference_id'],
            ':room_name_en' => $data['room_name_en'],
            ':room_name_ar' => $data['room_name_ar'] ?: null,
            ':location_en' => $data['location_en'] ?: null,
            ':location_ar' => $data['location_ar'] ?: null,
            ':capacity' => (int) ($data['capacity'] ?? 0),
            ':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_rooms
            SET conference_id = :conference_id,
                room_name_en = :room_name_en,
                room_name_ar = :room_name_ar,
                location_en = :location_en,
                location_ar = :location_ar,
                capacity = :capacity,
                sort_order = :sort_order,
                is_active = :is_active
            WHERE id = :id
        ");
        $stmt->execute([
            ':id' => $id,
            ':conference_id' => $data['conference_id'],
            ':room_name_en' => $data['room_name_en'],
            ':room_name_ar' => $data['room_name_ar'] ?: null,
            ':location_en' => $data['location_en'] ?: null,
            ':location_ar' => $data['location_ar'] ?: null,
            ':capacity' => (int) ($data['capacity'] ?? 0),
            ':sort_order' => $data['sort_order'] ?? 0,
            ':is_active' => !empty($data['is_active']) ? 1 : 0,
        ]);
    }
}
