<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Api;

use App\Core\App;
use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;

class PlayerSearchApiController extends Controller
{
    public function search(Request $request): Response
    {
        $q = trim((string) $request->get('q', ''));
        if (strlen($q) < 2) {
            return $this->json(['results' => []]);
        }

        $db = App::getInstance()->db();
        $like = '%' . $q . '%';

        $disciplineId = (int) $request->get('discipline_id', 0);
        $groupId = (int) $request->get('group_id', 0);
        $excludeGroup = (int) $request->get('exclude_group', 0);

        $joins = '';
        $where = 'p.is_archived = 0 AND (p.full_name_ar LIKE ? OR p.registration_serial LIKE ? OR p.national_id LIKE ? OR p.phone LIKE ?)';
        $params = [$like, $like, $like, $like];

        if ($disciplineId > 0) {
            $joins .= ' INNER JOIN sa_group_players gp_d ON gp_d.player_id = p.id AND gp_d.status = "active"';
            $joins .= ' INNER JOIN sa_groups g_d ON g_d.id = gp_d.group_id AND g_d.is_archived = 0';
            $joins .= ' INNER JOIN sa_programs pr_d ON pr_d.id = g_d.program_id AND pr_d.discipline_id = ?';
            $params[] = $disciplineId;
        }

        if ($groupId > 0) {
            $joins .= ' INNER JOIN sa_group_players gp_g ON gp_g.player_id = p.id AND gp_g.group_id = ? AND gp_g.status = "active"';
            $params[] = $groupId;
        }

        if ($excludeGroup > 0) {
            $where .= ' AND p.id NOT IN (SELECT player_id FROM sa_group_players WHERE group_id = ? AND status IN ("active","pending_payment"))';
            $params[] = $excludeGroup;
        }

        $results = $db->select(
            "SELECT DISTINCT p.id, p.full_name_ar, p.registration_serial, p.national_id,
                    p.player_type, p.medical_status, p.phone, p.date_of_birth
             FROM sa_players p
             {$joins}
             WHERE {$where}
             ORDER BY p.full_name_ar
             LIMIT 20",
            $params
        );

        $medicalLabels = [
            'fit' => 'لائق',
            'conditional' => 'لائق مشروط',
            'pending' => 'في الانتظار',
            'unfit' => 'غير لائق',
        ];

        foreach ($results as &$row) {
            $type = $row['player_type'] === 'member' ? 'عضو' : 'غير عضو';
            $medical = $medicalLabels[$row['medical_status'] ?? ''] ?? 'بدون شهادة';
            $serial = $row['registration_serial'] ?? '';

            $label = $row['full_name_ar'];
            $parts = [];
            if ($serial) {
                $parts[] = $serial;
            }
            $parts[] = $type;
            $parts[] = $medical;
            $label .= ' (' . implode(' • ', $parts) . ')';

            $row['label'] = $label;
        }
        unset($row);

        return $this->json(['results' => $results]);
    }
}
