<?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();
}

$action = $_POST['action'] ?? '';
$initiating_manager_id = $_SESSION['user_id'];

if ($action === 'initiate') {
    $data = [
        'player_id' => filter_input(INPUT_POST, 'player_id', FILTER_VALIDATE_INT),
        'from_club_id' => filter_input(INPUT_POST, 'from_club_id', FILTER_VALIDATE_INT),
        'to_club_id' => filter_input(INPUT_POST, 'to_club_id', FILTER_VALIDATE_INT),
        'offer_amount' => filter_input(INPUT_POST, 'offer_amount', FILTER_VALIDATE_FLOAT),
        'initiating_manager_id' => $initiating_manager_id
    ];

    if (!$data['player_id'] || !$data['from_club_id'] || !$data['to_club_id']) {
        header('Location: club_transfers.php?error=invalid_data');
        exit();
    }

    // In a real app, you'd have a Transfer model. For now, we can use the DB directly.
    $db = new Database();
    $db->query('INSERT INTO transfers (player_id, from_club_id, to_club_id, offer_amount, initiating_manager_id) VALUES (:player_id, :from_club_id, :to_club_id, :offer_amount, :initiating_manager_id)');
    foreach ($data as $key => $value) {
        $db->bind(':' . $key, $value);
    }

    if ($db->execute()) {
        header('Location: club_transfers.php?status=offer_submitted');
    } else {
        header('Location: club_transfers.php?error=submit_failed');
    }
} else {
    header('Location: club_transfers.php');
}
exit();
?>