<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: club_transfers.php');
    exit();
}

$transfer_id = filter_input(INPUT_POST, 'transfer_id', FILTER_VALIDATE_INT);
$action = $_POST['action'] ?? '';
$manager_id = $_SESSION['user_id'];

if (!$transfer_id || !in_array($action, ['accept', 'reject'])) {
    header('Location: club_transfers.php?error=invalid_request');
    exit();
}

$clubManagerModel = new ClubManager();
$club = $clubManagerModel->getClubByManagerId($manager_id);

if (!$club) {
    header('Location: club_transfers.php?error=no_club');
    exit();
}

$db = new Database();

// Verify transfer exists and is pending for THIS club (incoming transfer)
$db->query("SELECT * FROM transfers WHERE id = :id AND to_club_id = :club_id AND status = 'pending'");
$db->bind(':id', $transfer_id);
$db->bind(':club_id', $club->id);
$transfer = $db->single();

if (!$transfer) {
    header('Location: club_transfers.php?error=transfer_not_found');
    exit();
}

$new_status = ($action === 'accept') ? 'accepted' : 'rejected';

$db->beginTransaction();
try {
    // Update transfer status
    $db->query("UPDATE transfers SET status = :status WHERE id = :id");
    $db->bind(':status', $new_status);
    $db->bind(':id', $transfer_id);
    $db->execute();

    if ($new_status === 'accepted') {
        // If accepted, update the player's team/club association
        // Note: This assumes players table has team_id. We need to find a team in the new club or set to NULL/unassigned within club.
        // For simplicity, we might just update the team_id to NULL (free agent within club) or assign to a default team if logic exists.
        // Here we assume the player moves to the new club but needs team assignment later, or we just update the team_id if we knew it.
        // Since we don't know the specific team ID in the new club, we might need to handle this.
        // For now, let's just mark the transfer as 'completed' immediately for simplicity in this flow.
        $db->query("UPDATE transfers SET status = 'completed' WHERE id = :id");
        $db->bind(':id', $transfer_id);
        $db->execute();
        
        // Update player record to reflect new club ownership (this depends on your schema, usually via team_id)
        // Since players are linked to teams, and teams to clubs, we'd need to assign them to a team in the new club.
        // Let's assume we unassign them from the old team for now, effectively making them a free agent but "owned" by the new club conceptually.
        // Or better, we require the buying manager to assign them to a team later.
        // For this implementation, let's just clear the team_id so they show up as available to be added to a team in the new club.
        $db->query("UPDATE players SET team_id = NULL WHERE user_id = :player_id");
        $db->bind(':player_id', $transfer->player_id);
        $db->execute();
    }

    $db->commit();
    header('Location: club_transfers.php?status=' . $new_status);
} catch (Exception $e) {
    $db->rollBack();
    header('Location: club_transfers.php?error=db_error');
}
exit();
?>