<?php
$pageTitle = 'Payment Successful';
include 'includes/header.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$session_id = $_GET['session_id'] ?? null;

if (!$session_id) {
    header('Location: my_team.php');
    exit();
}

try {
    $session = \Stripe\Checkout\Session::retrieve($session_id);

    if ($session->payment_status === 'paid') {
        $fine_ids_string = $session->metadata->fine_ids;
        $fine_ids = explode(',', $fine_ids_string);

        $fineModel = new Fine();
        $fineModel->markAsPaid($fine_ids);

        // Redirect to the receipt page instead of the dashboard
        header('Location: receipt.php?ids=' . $fine_ids_string);
        exit();
    } else {
        $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Payment was not successful. Please try again.'];
    }
} catch (Exception $e) {
    // Handle invalid session ID or other Stripe errors
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'An error occurred while verifying your payment. Please contact support.'];
}

header('Location: my_team.php');
exit();