<?php
declare(strict_types=1);

namespace App\Modules\MatchCenter\Models;

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

class LiveMatch extends Model
{
    protected static string $table = 'live_matches';
    protected static bool $softDelete = false;
    protected static array $fillable = [
        'facility_id',
        'discipline_id',
        'tournament_match_id',
        'match_title_ar',
        'team_a_name',
        'team_b_name',
        'team_a_logo_path',
        'team_b_logo_path',
        'score_a',
        'score_b',
        'match_date',
        'start_time',
        'status',
        'started_at',
        'finished_at',
        'referee_name',
        'entry_employee_id',
        'notes',
    ];

    /**
     * Search matches with optional status and date filters.
     */
    public static function search(array $filters = [], int $perPage = 20, int $page = 1): array
    {
        $qb = static::query();

        if (!empty($filters['status'])) {
            $qb->where('status', '=', $filters['status']);
        }

        if (!empty($filters['date_from'])) {
            $qb->where('match_date', '>=', $filters['date_from']);
        }

        if (!empty($filters['date_to'])) {
            $qb->where('match_date', '<=', $filters['date_to']);
        }

        if (!empty($filters['q'])) {
            $qb->where('match_title_ar', 'LIKE', '%' . $filters['q'] . '%');
        }

        $qb->orderBy('match_date', 'DESC')->orderBy('start_time', 'DESC');

        return $qb->paginate($perPage, $page);
    }

    /**
     * Get matches grouped by status for the dashboard.
     */
    public static function getDashboardMatches(): array
    {
        $db = App::getInstance()->db();

        $live = $db->select(
            "SELECT * FROM live_matches WHERE status = 'live' ORDER BY started_at DESC"
        );

        $scheduled = $db->select(
            "SELECT * FROM live_matches WHERE status = 'scheduled' ORDER BY match_date ASC, start_time ASC LIMIT 20"
        );

        $finished = $db->select(
            "SELECT * FROM live_matches WHERE status = 'finished' ORDER BY finished_at DESC LIMIT 20"
        );

        return [
            'live'      => $live,
            'scheduled' => $scheduled,
            'finished'  => $finished,
        ];
    }
}
