<?php
declare(strict_types=1);

namespace App\Modules\ActivitySubscriptions\Controllers;

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

class PlayerSearchController extends Controller
{
    public function search(Request $request): Response
    {
        $q = trim((string) ($_GET['q'] ?? ''));
        if (mb_strlen($q) < 2) {
            return $this->json(['success' => true, 'players' => []]);
        }

        $db = App::getInstance()->db();
        $players = $db->select(
            "SELECT p.id, p.full_name_ar, p.national_id, p.player_type, p.phone
             FROM players p
             WHERE (p.full_name_ar LIKE ? OR p.national_id LIKE ? OR p.phone LIKE ?)
             AND p.is_archived = 0
             ORDER BY p.full_name_ar ASC
             LIMIT 15",
            ["%{$q}%", "%{$q}%", "%{$q}%"]
        );

        $results = [];
        foreach ($players as $p) {
            $results[] = [
                'id'          => (int) $p['id'],
                'name'        => $p['full_name_ar'],
                'national_id' => $p['national_id'] ?? '',
                'phone'       => $p['phone'] ?? '',
                'player_type' => $p['player_type'] ?? 'non_member',
            ];
        }

        return $this->json(['success' => true, 'players' => $results]);
    }
}
