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

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

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

$team_id = filter_input(INPUT_POST, 'team_id', FILTER_VALIDATE_INT);
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$description = trim($_POST['description'] ?? '');

if (!$team_id || !$amount || $amount <= 0) {
    header('Location: club_finances.php?error=' . urlencode('Invalid team or amount.'));
    exit();
}

$clubManagerModel = new ClubManager();
$walletModel = new Wallet();
$teamModel = new Team();

$club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
if (!$club) {
    header('Location: my_club.php?error=no_club');
    exit();
}

// Verify team belongs to club
$team = $teamModel->findById($team_id);
if (!$team || $team->club_id != $club->id) {
    header('Location: club_finances.php?error=' . urlencode('Invalid team selected.'));
    exit();
}

$club_wallet = $walletModel->getOrCreateWallet('club', $club->id);
$team_wallet = $walletModel->getOrCreateWallet('team', $team->id);

$desc = "Transfer to Team ({$team->name})" . ($description ? ": $description" : "");

if ($walletModel->transfer($club_wallet->id, $team_wallet->id, $amount, $desc)) {
    header('Location: club_finances.php?status=success&msg=' . urlencode('Funds transferred successfully.'));
} else {
    header('Location: club_finances.php?error=' . urlencode('Insufficient funds or transfer failed.'));
}
exit();