<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

$method  = $_SERVER['REQUEST_METHOD'];
$db      = db();

if ($method === 'GET') {
    $payload = require_auth();
    if (isset($_GET['team_id'])) {
        // Manager or admin fetching a team's requests
        $stmt = $db->prepare(
            'SELECT * FROM join_requests WHERE team_id = ? ORDER BY requested_at DESC'
        );
        $stmt->execute([$_GET['team_id']]);
    } elseif (isset($_GET['player_id'])) {
        $stmt = $db->prepare(
            'SELECT * FROM join_requests WHERE player_id = ? ORDER BY requested_at DESC'
        );
        $stmt->execute([$_GET['player_id']]);
    } else {
        json_err('Provide team_id or player_id');
    }
    json_ok(['requests' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $payload     = require_auth();
    $b           = body();
    $team_id     = $b['team_id']     ?? '';
    $player_id   = $payload['uid'];
    $player_name = $b['player_name'] ?? '';
    $player_email= $b['player_email']?? $payload['email'];
    $team_name   = $b['team_name']   ?? '';

    if ($team_id === '') json_err('team_id required');

    // Idempotent: return existing pending request if one exists
    $stmt = $db->prepare(
        "SELECT id FROM join_requests WHERE team_id=? AND player_id=? AND status='pending'"
    );
    $stmt->execute([$team_id, $player_id]);
    $existing = $stmt->fetch();
    if ($existing) json_ok(['id' => $existing['id']]);

    $id = uuid();
    $db->prepare(
        'INSERT INTO join_requests (id, team_id, team_name, player_id, player_name, player_email)
         VALUES (?, ?, ?, ?, ?, ?)'
    )->execute([$id, $team_id, $team_name, $player_id, $player_name, $player_email]);
    json_ok(['id' => $id], 201);
}

if ($method === 'PUT') {
    $payload   = require_auth();
    $b         = body();
    $request_id= $_GET['id'] ?? ($b['id'] ?? '');
    $status    = $b['status'] ?? '';

    if ($request_id === '' || $status === '') json_err('id and status required');
    if (!in_array($status, ['approved','rejected'])) json_err('Invalid status');

    $db->prepare('UPDATE join_requests SET status = ? WHERE id = ?')
       ->execute([$status, $request_id]);

    if ($status === 'approved') {
        // Stamp team_id on the player's profile
        $stmt = $db->prepare('SELECT * FROM join_requests WHERE id = ?');
        $stmt->execute([$request_id]);
        $req = $stmt->fetch();
        if ($req) {
            $db->prepare('UPDATE users SET team_id = ? WHERE id = ?')
               ->execute([$req['team_id'], $req['player_id']]);
            // Add player to players table
            $exists = $db->prepare('SELECT id FROM players WHERE team_id=? AND user_id=?');
            $exists->execute([$req['team_id'], $req['player_id']]);
            if (!$exists->fetch()) {
                $db->prepare(
                    'INSERT INTO players (id, team_id, user_id, name) VALUES (?, ?, ?, ?)'
                )->execute([uuid(), $req['team_id'], $req['player_id'], $req['player_name']]);
            }
        }
    }

    json_ok(['updated' => true]);
}

json_err('Method not allowed', 405);
