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

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'team_manager') {
    header('HTTP/1.1 403 Forbidden');
    exit();
}
$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$teamModel = new Team();
$fineModel = new Fine();

// --- Get Team and Fines ---
$team = $teamModel->getTeamByManagerId($manager_id);
if (!$team) {
    die('No team found for manager.');
}

$outstanding_fines = $fineModel->getUnpaidFinesForTeam($team->club_id);
if (empty($outstanding_fines)) {
    die('No outstanding fines to pay.');
}

// --- Stripe Integration ---
\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$line_items = [];
$fine_ids = [];
foreach ($outstanding_fines as $fine) {
    $line_items[] = [
        'price_data' => [
            'currency' => 'usd', // Change currency as needed
            'product_data' => [
                'name' => 'Fine: ' . htmlspecialchars($fine->reason),
                'description' => 'For: ' . htmlspecialchars($fine->entity_name),
            ],
            'unit_amount' => $fine->amount * 100, // Amount in cents
        ],
        'quantity' => 1,
    ];
    $fine_ids[] = $fine->id;
}

$checkout_session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => $line_items,
    'mode' => 'payment',
    'success_url' => URL_ROOT . '/app/payment_success.php?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => URL_ROOT . '/app/my_team.php?payment=cancelled',
    'metadata' => [
        'fine_ids' => implode(',', $fine_ids),
        'team_id' => $team->id
    ]
]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);
exit();
?>