<?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();
}
$manager_id = $_SESSION['user_id'];

// --- Input Validation ---
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['fine_ids']) || !is_array($_POST['fine_ids'])) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'No fines were selected for payment.'];
    header('Location: my_club.php');
    exit();
}

$fine_ids = filter_var_array($_POST['fine_ids'], FILTER_VALIDATE_INT);

// --- Instantiate Models ---
$fineModel = new Fine();
$userModel = new User();
$clubManagerModel = new ClubManager();
$settingModel = new Setting();

// --- Get User and Club Info for Payment ---
$manager = $userModel->getFullUserDetailsById($manager_id);
$club = $clubManagerModel->getClubByManagerId($manager_id);

if (!$club || !$manager) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Could not identify your club or user profile.'];
    header('Location: my_club.php');
    exit();
}

// --- Fetch Data and Calculate Total ---
$total_amount = 0;
$line_items_description = [];
$fines_to_pay = [];

foreach ($fine_ids as $fine_id) {
    // Security check: Ensure the fine exists, is unpaid, and belongs to the manager's club.
    $fine = $fineModel->getFineDetailsByIdAndClubId($fine_id, $club->id);
    if ($fine) {
        $total_amount += $fine->amount;
        $fines_to_pay[] = $fine;
        $line_items_description[] = $fine->reason;
    }
}

if (empty($fines_to_pay)) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Selected fines could not be processed.'];
    header('Location: my_club.php');
    exit();
}

// --- Prepare Flutterwave Payment ---
$settings = $settingModel->getAll();
$flutterwave_secret_key = $settings['flutterwave_secret_key'] ?? '';

if (empty($flutterwave_secret_key)) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Payment gateway is not configured.'];
    header('Location: my_club.php');
    exit();
}
$tx_ref = 'SF-FINES-' . uniqid();
$redirect_url = URL_ROOT . '/app/flutterwave_verify.php?payment_context=club_manager';

$payload = [
    'tx_ref' => $tx_ref,
    'amount' => $total_amount,
    'currency' => $settings['system_currency'] ?? 'USD',
    'redirect_url' => $redirect_url,
    'payment_options' => 'card, banktransfer, ussd',
    'customer' => [
        'email' => $manager->email,
        'name' => $manager->first_name . ' ' . $manager->last_name,
    ],
    'meta' => [
        'fine_ids' => implode(',', $fine_ids),
        'user_id' => $manager_id,
    ],
    'customizations' => [
        'title' => $club->name . ' - Fine Payment',
        'description' => 'Payment for: ' . implode(', ', $line_items_description),
        'logo' => $club->logo ?? (URL_ROOT . '/public/assets/images/default-logo.png'),
    ],
];

// --- cURL Request to Flutterwave ---
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.flutterwave.com/v3/payments');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $flutterwave_secret_key]);

$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

$result = json_decode($response);

if ($result && $result->status === 'success' && !empty($result->data->link)) {
    header('Location: ' . $result->data->link);
} else {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Could not initiate payment: ' . ($result->message ?? 'Unknown error')];
    header('Location: my_club.php');
}
exit();