<?php
declare(strict_types=1);

namespace App\Modules\Reservations\Models;

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

class PrivateMatchBooking extends Model
{
    protected static string $table = 'private_match_bookings';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    protected static array $fillable = [
        'facility_id', 'booked_by_member_id', 'booked_by_name', 'booked_by_phone',
        'booking_date', 'start_time', 'end_time', 'match_type',
        'team_a_name', 'team_b_name', 'players_count',
        'has_referee', 'referee_cost', 'facility_cost', 'total_cost',
        'deposit_paid', 'status', 'payment_status', 'notes', 'cancelled_reason',
    ];

    public static function getMatchTypes(): array
    {
        return [
            'friendly'   => 'ودية',
            'training'   => 'تدريبية',
            'tournament' => 'بطولة',
            'other'      => 'أخرى',
        ];
    }

    public static function search(array $filters = [], int $limit = 30): array
    {
        $db = App::getInstance()->db();
        $sql = "SELECT pmb.*, f.name_ar AS facility_name
                FROM private_match_bookings pmb
                LEFT JOIN facilities f ON f.id = pmb.facility_id
                WHERE 1=1";
        $params = [];

        if (!empty($filters['status'])) {
            $sql .= " AND pmb.status = ?";
            $params[] = $filters['status'];
        }
        if (!empty($filters['date_from'])) {
            $sql .= " AND pmb.booking_date >= ?";
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $sql .= " AND pmb.booking_date <= ?";
            $params[] = $filters['date_to'];
        }
        if (!empty($filters['facility_id'])) {
            $sql .= " AND pmb.facility_id = ?";
            $params[] = (int) $filters['facility_id'];
        }

        $sql .= " ORDER BY pmb.booking_date DESC, pmb.start_time ASC LIMIT ?";
        $params[] = $limit;

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

    public static function getUpcoming(int $limit = 10): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pmb.*, f.name_ar AS facility_name
             FROM private_match_bookings pmb
             LEFT JOIN facilities f ON f.id = pmb.facility_id
             WHERE pmb.booking_date >= CURDATE() AND pmb.status IN ('pending','confirmed')
             ORDER BY pmb.booking_date ASC, pmb.start_time ASC
             LIMIT ?",
            [$limit]
        );
    }
}
