<?php
declare(strict_types=1);

namespace App\Modules\PoolManagement\Models;

use App\Core\Model;
use App\Core\App;

class PoolSchedule extends Model
{
    protected static string $table = 'pool_schedules';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'pool_config_id',
        'schedule_name',
        'day_of_week',
        'start_time',
        'end_time',
        'lanes_json',
        'booking_type',
        'coach_id',
        'coach_name',
        'academy_id',
        'academy_name',
        'age_group',
        'gender',
        'max_swimmers',
        'color',
        'effective_from',
        'effective_to',
        'is_active',
        'notes',
    ];

    public function getLanes(): array
    {
        $decoded = json_decode($this->lanes_json ?? '[]', true);
        return is_array($decoded) ? $decoded : [];
    }

    public static function getActiveForPool(int $poolConfigId, ?string $date = null): array
    {
        $db = App::getInstance()->db();
        $date = $date ?: date('Y-m-d');
        $dayOfWeek = (int) date('w', strtotime($date));

        return $db->select(
            "SELECT * FROM pool_schedules
             WHERE pool_config_id = ? AND day_of_week = ? AND is_active = 1
             AND effective_from <= ? AND (effective_to IS NULL OR effective_to >= ?)
             ORDER BY start_time ASC",
            [$poolConfigId, $dayOfWeek, $date, $date]
        );
    }

    public static function getAllForPool(int $poolConfigId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT ps.*, c.full_name_ar AS coach_full_name, a.name_ar AS acad_name
             FROM pool_schedules ps
             LEFT JOIN coaches c ON c.id = ps.coach_id
             LEFT JOIN academies a ON a.id = ps.academy_id
             WHERE ps.pool_config_id = ? AND ps.is_active = 1
             ORDER BY ps.day_of_week ASC, ps.start_time ASC",
            [$poolConfigId]
        );
    }

    public static function getDayNames(): array
    {
        return [
            0 => 'الأحد',
            1 => 'الإثنين',
            2 => 'الثلاثاء',
            3 => 'الأربعاء',
            4 => 'الخميس',
            5 => 'الجمعة',
            6 => 'السبت',
        ];
    }
}
