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

// --- Authentication and Role Check ---
// Get Parameters from AJAX Request (JSON) to determine context first
$input_json = json_decode(file_get_contents('php://input'), true);
$is_ajax = !empty($input_json);

if ($is_ajax) {
    $input = $input_json;
} else {
    $input = $_GET;
}

$context = $input['payment_context'] ?? 'team_manager';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

// Only restrict roles for management-related payments (fines)
if (in_array($context, ['team_manager', 'club_manager']) && !in_array($_SESSION['user_role'], ['team_manager', 'club_manager'])) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Access Denied']);
    exit();
}

$transaction_id = $input['transaction_id'] ?? null;
$tx_ref = $input['tx_ref'] ?? null;

if ($is_ajax) {
    // Set JSON response header only for AJAX
    header('Content-Type: application/json');
}

if (!$transaction_id) {
    echo json_encode(['status' => 'error', 'message' => 'Transaction ID is missing.']);
    exit();
}

// --- Verification with Flutterwave API ---
$settingModel = new Setting();
$settings = $settingModel->getAll();
$flutterwave_secret_key = $settings['flutterwave_secret_key'] ?? '';

if (empty($flutterwave_secret_key)) {
    echo json_encode(['status' => 'error', 'message' => 'Payment configuration error: Secret Key not found.']);
    exit();
}

// Sanitize transaction ID to ensure it is an integer before using it in the API URL
$transaction_id = intval($transaction_id);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.flutterwave.com/v3/transactions/{$transaction_id}/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Fix for XAMPP SSL issues
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);

if ($err) {
    echo json_encode(['status' => 'error', 'message' => 'Could not verify the transaction. Please contact support.']);
    exit();
}

$result = json_decode($response);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid response received from payment gateway.']);
    exit();
}

// --- Process Verification Result ---
if ($result && $result->status === 'success') {
    $data = $result->data;
    $meta = $data->meta ?? null;

    // Security checks
    if ($data->status === 'successful' && $data->tx_ref === $tx_ref) {
        
        // --- DUPLICATE TRANSACTION CHECK ---
        // This is the most important check to prevent re-processing the same payment.
        $paymentModel = new Payment();
        if ($paymentModel->findByRef($data->tx_ref)) {
            // This transaction has already been logged and processed.
            // We can inform the user and stop execution.
            echo json_encode(['status' => 'info', 'message' => 'This transaction has already been processed.']);
            exit();
        }

        // --- CURRENCY VERIFICATION ---
        $expected_currency = $settings['system_currency'] ?? 'USD';
        if ($data->currency !== $expected_currency) {
            echo json_encode(['status' => 'error', 'message' => "Currency mismatch. Expected $expected_currency but received {$data->currency}."]);
            exit();
        }

        // --- Handle Membership Purchase ---
        if ($context === 'membership_purchase') {
            $package_id = $meta->package_id ?? null;
            
            if (!$package_id) {
                echo json_encode(['status' => 'error', 'message' => 'Transaction verified, but package data was missing.']);
                exit();
            }

            $clubModel = new Club();
            $package = $clubModel->getMembershipPackageById($package_id);

            if (!$package) {
                echo json_encode(['status' => 'error', 'message' => 'Membership package not found.']);
                exit();
            }

            // Verify Amount
            if (abs($data->amount - $package->price) > 0.01) {
                echo json_encode(['status' => 'error', 'message' => 'Payment amount mismatch.']);
                exit();
            }

            // Calculate Expiry Date
            $expiry_date = date('Y-m-d');
            if ($package->duration_type === 'monthly') {
                $expiry_date = date('Y-m-d', strtotime('+1 month'));
            } elseif ($package->duration_type === 'termly') {
                $expiry_date = date('Y-m-d', strtotime('+3 months'));
            } elseif ($package->duration_type === 'yearly') {
                $expiry_date = date('Y-m-d', strtotime('+1 year'));
            }

            // Create Membership
            $membershipData = [
                'user_id' => $_SESSION['user_id'],
                'club_id' => $package->club_id,
                'membership_type' => $package->name,
                'start_date' => date('Y-m-d'),
                'expiry_date' => $expiry_date
            ];
            $clubModel->createMembership($membershipData);

            // Log Payment
            $paymentModel = new Payment();
            $paymentData = [
                'user_id' => $_SESSION['user_id'],
                'amount' => $data->amount,
                'currency' => $data->currency,
                'transaction_ref' => $data->tx_ref,
                'payment_gateway' => 'flutterwave',
                'status' => 'successful',
                'metadata' => json_encode($meta)
            ];
            $paymentModel->create($paymentData);

            // Distribute Revenue (Club gets net, Board & Site get commissions)
            $walletModel = new Wallet();
            // Ensure Board/System wallet exists for commission
            $walletModel->getOrCreateWallet('board', 0);
            $walletModel->getOrCreateWallet('site', 0);
            
            $walletModel->distributePaymentWithCommission(
                $data->amount, 
                'membership', 
                'club', 
                $package->club_id, 
                "Membership: " . $package->name, 
                $data->tx_ref
            );

            if ($is_ajax) {
                echo json_encode(['status' => 'success', 'message' => 'Membership purchased successfully.', 'redirect_url' => 'memberships.php?status=success']);
            } else {
                header('Location: memberships.php?status=success');
            }
            exit();
        }

        // --- Handle Wallet Deposit ---
        if ($context === 'wallet_deposit' || $context === 'user_wallet_deposit' || $context === 'club_wallet_deposit') {
            $wallet = null;
            
            if ($context === 'club_wallet_deposit') {
                $clubManagerModel = new ClubManager();
                $club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']); // Assuming club manager is making the deposit
                if ($club) $wallet = $walletModel->getOrCreateWallet('club', $club->id); else { echo json_encode(['status' => 'error', 'message' => 'Club wallet not found or accessible.']); exit(); }
            } else { // wallet_deposit
                $wallet = $walletModel->getOrCreateWallet('user', $_SESSION['user_id']);
            }

            if (!$wallet) {
                echo json_encode(['status' => 'error', 'message' => 'Wallet not found or accessible.']);
                exit();
            }

            if ($walletModel->deposit($wallet->id, $data->amount, 'Flutterwave Deposit', $data->tx_ref)) {
                $paymentModel = new Payment();
                $paymentData = [
                    'user_id' => $_SESSION['user_id'],
                    'amount' => $data->amount,
                    'currency' => $data->currency,
                    'transaction_ref' => $data->tx_ref,
                    'payment_gateway' => 'flutterwave',
                    'status' => 'successful',
                    'metadata' => json_encode($meta)
                ];
                $paymentModel->create($paymentData);
                
                $redirect = 'wallet.php?status=success';
                if ($context === 'club_wallet_deposit') {
                    $redirect = 'my_club.php?tab=finances&status=success';
                }

                if ($is_ajax) {
                    echo json_encode(['status' => 'success', 'message' => 'Wallet topped up successfully.', 'redirect_url' => $redirect]);
                } else {
                    header('Location: ' . $redirect);
                }
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to update wallet balance.']);
                exit();
            }
        }

        // --- Handle Referee Fee ---
        if ($context === 'referee_fee') {
            $fixture_id = $meta->fixture_id;
            $team_id = $meta->team_id;
            
            // --- FIX: Add amount verification for referee fee ---
            $expected_amount = (float)($settings['referee_fee'] ?? 50);
            if ($expected_amount <= 0) {
                echo json_encode(['status' => 'error', 'message' => 'Referee fee is not configured correctly in system settings.']);
                exit();
            }

            if (abs($data->amount - $expected_amount) > 0.01) {
                echo json_encode(['status' => 'error', 'message' => 'Payment amount mismatch. Paid amount does not match the required referee fee.']);
                exit();
            }

            $fixtureModel = new Fixture();
            $fixture = $fixtureModel->findById($fixture_id);

            if (!$fixture || !$fixture->referee_id) {
                echo json_encode(['status' => 'error', 'message' => 'Referee not assigned to this match. Cannot process fee.']);
                exit();
            }
            
            $column = ($fixture->home_team_id == $team_id) ? 'home_team_paid_referee' : 'away_team_paid_referee';
            
            $db = new Database();
            $db->query("UPDATE fixtures SET $column = 1 WHERE id = :id");
            $db->bind(':id', $fixture_id);
            $db->execute();

            // Distribute Referee Fee (To Board, with Site Commission)
            $walletModel = new Wallet();
            
            // Get Team Wallet and Deposit the Gateway Amount first to ensure funds exist for distribution
            $team_wallet = $walletModel->getOrCreateWallet('team', $team_id);
            $walletModel->deposit($team_wallet->id, $data->amount, "Deposit for Referee Fee (Online)", $data->tx_ref);

            // Ensure Board/System wallet exists for commission
            $walletModel->getOrCreateWallet('board', 0);
            $walletModel->getOrCreateWallet('site', 0);

            $walletModel->distributePaymentWithCommission(
                $data->amount,
                'referee_fee',
                'user',
                $fixture->referee_id,
                "Referee Fee: Match #$fixture_id",
                $data->tx_ref,
                $team_wallet->id
            );

            // Log Payment
            $paymentModel = new Payment();
            $paymentData = [
                'user_id' => $_SESSION['user_id'],
                'amount' => $data->amount,
                'currency' => $data->currency,
                'transaction_ref' => $data->tx_ref,
                'payment_gateway' => 'flutterwave',
                'status' => 'successful',
                'metadata' => json_encode($meta)
            ];
            $paymentModel->create($paymentData);
            
            if ($is_ajax) {
                echo json_encode(['status' => 'success', 'message' => 'Referee fee paid successfully.', 'redirect_url' => 'my_team.php?status=success&msg=Referee fee paid']);
            } else {
                header('Location: my_team.php?status=success&msg=Referee fee paid');
            }
            exit();
        }

        // --- Payment is successful and verified ---
        $fine_ids_string = $meta->fine_ids ?? null;

        if (!$fine_ids_string) {
            echo json_encode(['status' => 'error', 'message' => 'Transaction verified, but fine data was missing. Please contact support.']);
            exit();
        }

        $fine_ids = explode(',', $fine_ids_string);

        // Instantiate models
        $fineModel = new Fine();
        $paymentModel = new Payment();

        // --- Amount Verification ---
        // Fetch the fines to verify the total amount matches what was paid
        $fines = $fineModel->getFinesByIds($fine_ids);
        $expected_amount = 0;
        foreach ($fines as $fine) {
            if ($fine->status === 'paid') {
                 echo json_encode(['status' => 'info', 'message' => 'These fines have already been paid.']);
                 exit();
            }
            $expected_amount += $fine->amount;
        }

        // Allow for small floating point differences
        if (abs($data->amount - $expected_amount) > 0.01) {
             echo json_encode(['status' => 'error', 'message' => 'Payment amount mismatch. Please contact support.']);
             exit();
        }

        // Update fines to 'paid' status
        $fineModel->markAsPaid($fine_ids);

        // --- Determine Source Wallet for Ledger ---
        // We deposit the online payment into the entity's wallet first, then distribute it out.
        // This ensures the entity's transaction history reflects the payment.
        $walletModel = new Wallet();
        $source_wallet_id = null;
        $deposit_desc = "Deposit for Fine Payment (Online)";
        $manager_id = $meta->user_id ?? $_SESSION['user_id'];

        if ($context === 'club_manager') {
            $clubManagerModel = new ClubManager();
            $club = $clubManagerModel->getClubByManagerId($manager_id);
            if ($club) {
                $wallet = $walletModel->getOrCreateWallet('club', $club->id);
                $source_wallet_id = $wallet->id;
                $walletModel->deposit($source_wallet_id, $data->amount, $deposit_desc, $data->tx_ref);
            }
        } elseif ($context === 'team_manager') {
            $teamModel = new Team();
            $team = $teamModel->getTeamByManagerId($manager_id);
            if ($team) {
                $wallet = $walletModel->getOrCreateWallet('team', $team->id);
                $source_wallet_id = $wallet->id;
                $walletModel->deposit($source_wallet_id, $data->amount, $deposit_desc, $data->tx_ref);
            }
        }

        // Ensure Board/System wallet exists for commission
        $walletModel->getOrCreateWallet('board', 0);
        $walletModel->getOrCreateWallet('site', 0);

        // Distribute Fine Payment (To Board, with Site Commission)
        $walletModel->distributePaymentWithCommission(
            $data->amount,
            'fine',
            'board',
            0, // Board ID
            "Fine Payment (" . count($fines) . " items)",
            $data->tx_ref,
            $source_wallet_id
        );

        // --- Notify Players ---
        $notificationModel = new Notification();
        foreach ($fines as $fine) {
            if ($fine->entity_type === 'player' && !empty($fine->player_id)) {
                $msg = "Your fine of {$data->currency} " . number_format($fine->amount, 2) . " for '{$fine->reason}' has been paid.";
                $notificationModel->create($fine->player_id, 'fine_paid', $msg);
            }
        }

        // Log the payment for record-keeping
        $paymentData = [
            'user_id' => $_SESSION['user_id'],
            'amount' => $data->amount,
            'currency' => $data->currency,
            'transaction_ref' => $data->tx_ref,
            'payment_gateway' => 'flutterwave',
            'status' => 'successful',
            'metadata' => json_encode(['fine_ids' => $fine_ids_string])
        ];
        $paymentModel->create($paymentData);

        // Return success JSON with redirect URL
        $redirect_url = 'receipt.php?ids=' . urlencode($fine_ids_string) . '&context=' . urlencode($context);
        if ($is_ajax) {
            echo json_encode([
                'status' => 'success',
                'message' => 'Payment verified successfully.',
                'redirect_url' => $redirect_url
            ]);
        } else {
            header('Location: ' . $redirect_url);
        }
        exit();
    } else {
        // Verification failed (e.g., amount mismatch, status not successful)
        echo json_encode(['status' => 'error', 'message' => 'Payment verification failed. Please try again.']);
        exit();
    }
} else {
    // API call to Flutterwave failed
    $error_message = $result->message ?? 'An unknown error occurred while verifying the payment.';
    echo json_encode(['status' => 'error', 'message' => 'Verification Error: ' . $error_message]);
    exit();
}