<?php
declare(strict_types=1);

namespace App\Modules\TrainingGroups\Models;

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

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

    protected static array $fillable = [
        'player_id', 'from_group_id', 'to_group_id', 'reason_ar',
        'status', 'reviewed_by', 'reviewed_at', 'review_notes',
    ];

    public static function getPending(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT gtr.*,
                    p.full_name_ar AS player_name,
                    fg.name_ar AS from_group_name,
                    tg.name_ar AS to_group_name
             FROM group_transfer_requests gtr
             LEFT JOIN players p ON p.id = gtr.player_id
             LEFT JOIN training_groups fg ON fg.id = gtr.from_group_id
             LEFT JOIN training_groups tg ON tg.id = gtr.to_group_id
             WHERE gtr.status = 'pending'
             ORDER BY gtr.created_at ASC"
        );
    }

    public static function getForPlayer(int $playerId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT gtr.*,
                    fg.name_ar AS from_group_name,
                    tg.name_ar AS to_group_name
             FROM group_transfer_requests gtr
             LEFT JOIN training_groups fg ON fg.id = gtr.from_group_id
             LEFT JOIN training_groups tg ON tg.id = gtr.to_group_id
             WHERE gtr.player_id = ?
             ORDER BY gtr.created_at DESC",
            [$playerId]
        );
    }

    public static function search(array $filters = [], int $limit = 30): array
    {
        $db = App::getInstance()->db();
        $sql = "SELECT gtr.*,
                    p.full_name_ar AS player_name,
                    fg.name_ar AS from_group_name,
                    tg.name_ar AS to_group_name
                FROM group_transfer_requests gtr
                LEFT JOIN players p ON p.id = gtr.player_id
                LEFT JOIN training_groups fg ON fg.id = gtr.from_group_id
                LEFT JOIN training_groups tg ON tg.id = gtr.to_group_id
                WHERE 1=1";
        $params = [];

        if (!empty($filters['status'])) {
            $sql .= " AND gtr.status = ?";
            $params[] = $filters['status'];
        }
        if (!empty($filters['from_group_id'])) {
            $sql .= " AND gtr.from_group_id = ?";
            $params[] = (int) $filters['from_group_id'];
        }

        $sql .= " ORDER BY gtr.created_at DESC LIMIT ?";
        $params[] = $limit;

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