<?php
declare(strict_types=1);

namespace App\Modules\Sessions\Models;

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

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

    protected static array $fillable = [
        'group_id',
        'academy_id',
        'coach_id',
        'facility_id',
        'session_date',
        'start_time',
        'end_time',
        'session_type',
        'status',
        'cancellation_reason',
        'cancelled_by',
        'players_expected',
        'players_attended',
        'notes',
    ];

    public static function getSessionTypes(): array
    {
        return [
            'regular'    => 'عادية',
            'makeup'     => 'تعويضية',
            'extra'      => 'إضافية',
            'assessment' => 'تقييم',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'scheduled'   => 'مجدولة',
            'in_progress' => 'جارية',
            'completed'   => 'مكتملة',
            'cancelled'   => 'ملغاة',
        ];
    }

    public static function getStatusColor(string $status): string
    {
        return match ($status) {
            'scheduled'   => '#3B82F6',
            'in_progress' => '#F59E0B',
            'completed'   => '#10B981',
            'cancelled'   => '#EF4444',
            default       => '#6B7280',
        };
    }

    public static function getSessionTypeColor(string $type): string
    {
        return match ($type) {
            'regular'    => '#6B7280',
            'makeup'     => '#7C3AED',
            'extra'      => '#D97706',
            'assessment' => '#2563EB',
            default      => '#6B7280',
        };
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();

        $where = ['1=1'];
        $params = [];

        if (!empty($filters['date_from'])) {
            $where[] = 'ts.session_date >= ?';
            $params[] = $filters['date_from'];
        }

        if (!empty($filters['date_to'])) {
            $where[] = 'ts.session_date <= ?';
            $params[] = $filters['date_to'];
        }

        if (!empty($filters['group_id'])) {
            $where[] = 'ts.group_id = ?';
            $params[] = (int) $filters['group_id'];
        }

        if (!empty($filters['academy_id'])) {
            $where[] = 'ts.academy_id = ?';
            $params[] = (int) $filters['academy_id'];
        }

        if (!empty($filters['coach_id'])) {
            $where[] = 'ts.coach_id = ?';
            $params[] = (int) $filters['coach_id'];
        }

        if (!empty($filters['status'])) {
            $where[] = 'ts.status = ?';
            $params[] = $filters['status'];
        }

        if (!empty($filters['session_type'])) {
            $where[] = 'ts.session_type = ?';
            $params[] = $filters['session_type'];
        }

        $whereClause = implode(' AND ', $where);

        $countSql = "SELECT COUNT(*) AS total FROM training_sessions ts WHERE {$whereClause}";
        $countResult = $db->selectOne($countSql, $params);
        $total = (int) ($countResult['total'] ?? 0);

        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        $sql = "SELECT ts.*,
                    tg.name_ar AS group_name,
                    a.name_ar AS academy_name,
                    c.full_name_ar AS coach_name,
                    f.name_ar AS facility_name
                FROM training_sessions ts
                LEFT JOIN training_groups tg ON tg.id = ts.group_id
                LEFT JOIN academies a ON a.id = ts.academy_id
                LEFT JOIN coaches c ON c.id = ts.coach_id
                LEFT JOIN facilities f ON f.id = ts.facility_id
                WHERE {$whereClause}
                ORDER BY ts.session_date DESC, ts.start_time ASC
                LIMIT {$perPage} OFFSET {$offset}";

        $data = $db->select($sql, $params);

        return [
            'data' => $data,
            'pagination' => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => $lastPage,
            ],
        ];
    }

    public static function getForCalendar(int $year, int $month, ?int $academyId = null): array
    {
        $db = App::getInstance()->db();

        $startDate = sprintf('%04d-%02d-01', $year, $month);
        $endDate = date('Y-m-t', strtotime($startDate));

        $params = [$startDate, $endDate];
        $extraWhere = '';

        if ($academyId) {
            $extraWhere = ' AND ts.academy_id = ?';
            $params[] = $academyId;
        }

        $sql = "SELECT ts.*, tg.name_ar AS group_name
                FROM training_sessions ts
                LEFT JOIN training_groups tg ON tg.id = ts.group_id
                WHERE ts.session_date >= ? AND ts.session_date <= ?{$extraWhere}
                ORDER BY ts.session_date ASC, ts.start_time ASC";

        return $db->select($sql, $params);
    }
}
