<?php
// Start session securely
session_start([
    'cookie_secure' => true, // Ensure cookies are only sent over HTTPS
    'cookie_httponly' => true, // Prevent JavaScript access to session cookies
    'use_strict_mode' => true, // Prevent session fixation
    'cookie_samesite' => 'Strict', // Prevent CSRF attacks
]);

// Regenerate session ID to prevent session fixation
session_regenerate_id(true);

// Session expiration (30 min timeout)
if (!isset($_SESSION['LAST_ACTIVITY'])) {
    $_SESSION['LAST_ACTIVITY'] = time();
} elseif (time() - $_SESSION['LAST_ACTIVITY'] > 1800) { // 30 min timeout
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}
$_SESSION['LAST_ACTIVITY'] = time();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Include database connection
require 'require/conn.php';

// Process form data only if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get user input from the form and sanitize
    $mobile_no = filter_input(INPUT_POST, 'mobile_no', FILTER_SANITIZE_NUMBER_INT);
    $amount = filter_input(INPUT_POST, 'amount', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $airtime_name = filter_input(INPUT_POST, 'airtime_name', FILTER_SANITIZE_STRING);
    $transaction_pin = filter_input(INPUT_POST, 'transaction_pin', FILTER_SANITIZE_STRING);

    // Validate inputs
    if (empty($mobile_no) || empty($amount) || empty($airtime_name) || empty($transaction_pin)) {
        die(json_encode(['status' => 'error', 'message' => 'All fields are required.']));
    }

    if ($amount <= 0) {
        die(json_encode(['status' => 'error', 'message' => 'Amount must be a positive number.']));
    }

    // Fetch user details from the database
    $userId = $_SESSION['user_id']; // Use session user ID
    $userSql = "SELECT wallet_balance, transaction_pin, type FROM jamaa WHERE id = ?";
    $stmt = $conn->prepare($userSql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $userResult = $stmt->get_result();
    $userRow = $userResult->fetch_assoc();

    if (!$userRow) {
        $conn->close();
        die(json_encode(['status' => 'error', 'message' => 'User not found.']));
    }

    $wallet_balance = $userRow['wallet_balance'];
    $hashed_pin = $userRow['transaction_pin'];
    $user_type = $userRow['type'];

    // Verify the transaction pin
    if (!password_verify($transaction_pin, $hashed_pin)) {
        die(json_encode(['status' => 'error', 'message' => 'Invalid transaction pin.']));
    }

    // Fetch airtime details from the database
    $airtimeSql = "SELECT api_price, user_price FROM airtime_status WHERE airtime_name = ?";
    $stmt = $conn->prepare($airtimeSql);
    $stmt->bind_param("s", $airtime_name);
    $stmt->execute();
    $airtimeResult = $stmt->get_result();
    $airtimeRow = $airtimeResult->fetch_assoc();

    if (!$airtimeRow) {
        die(json_encode(['status' => 'error', 'message' => 'Airtime details not found.']));
    }

    $price_percentage = ($user_type === 'api') ? $airtimeRow['api_price'] : $airtimeRow['user_price'];
    $deduction_amount = ($amount * $price_percentage) / 100; // Calculate deduction amount
    $total_deduction = $deduction_amount; // No transaction fee in this example

    // Check if the user has sufficient balance
    if ($wallet_balance < $total_deduction) {
        die(json_encode(['status' => 'error', 'message' => 'Insufficient wallet balance.']));
    }

    // Start a transaction
    $conn->begin_transaction();

    try {
        // Deduct from wallet balance
        $new_balance = $wallet_balance - $total_deduction;
        $updateBalanceSql = "UPDATE jamaa SET wallet_balance = ? WHERE id = ?";
        $stmt = $conn->prepare($updateBalanceSql);
        $stmt->bind_param("di", $new_balance, $userId);
        $stmt->execute();

        // Fetch API settings from the database
        $apiSettingsSql = "SELECT * FROM api_settings LIMIT 1";
        $apiSettingsResult = $conn->query($apiSettingsSql);
        $apiSettings = $apiSettingsResult->fetch_assoc();

        if (!$apiSettings) {
            throw new Exception("API settings not found.");
        }

        // Prepare the payload
        $payload = array(
            'network' => $airtime_name,
            'amount' => $amount,
            'mobile_no' => $mobile_no,
            'reference' => 'REF-UNIQUE' . uniqid(),
        );

        // Set the URL for the VTU API
        $url = $apiSettings['vtu_url'];

        // Initialize cURL
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $headers = [
            'Authorization: Basic ' . $apiSettings['api_key'],
            'Content-Type: application/json',
        ];

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL request
        $response = curl_exec($ch);

        // Check for CURL errors
        if (curl_errno($ch)) {
            throw new Exception('CURL Error: ' . curl_error($ch));
        } else {
            // Decode and display response
            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($http_status != 200) {
                throw new Exception("HTTP Status for $airtime_name: $http_status\nResponse: $response");
            }
        }

        // Close cURL session
        curl_close($ch);

        // Record the transaction in the database
        $insertTransactionSql = "INSERT INTO airtime_purchases (user_id, mobile_no, amount, airtime_name, deduction_amount, old_balance, current_balance, status, created_at) 
                                  VALUES (?, ?, ?, ?, ?, ?, ?, 'successful', NOW())";
        $stmt = $conn->prepare($insertTransactionSql);
        $stmt->bind_param("isisddd", $userId, $mobile_no, $amount, $airtime_name, $total_deduction, $wallet_balance, $new_balance);
        $stmt->execute();

        // Commit the transaction
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Airtime purchased successfully.']);
    } catch (Exception $e) {
        // Rollback the transaction in case of errors
        $conn->rollback();
        error_log($e->getMessage()); // Log the error
        echo json_encode(['status' => 'error', 'message' => 'An error occurred. Please try again later.']);
    } finally {
        // Close the database connection
        $conn->close();
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Airtime Purchase</title>
</head>
<body>
    <h1>Purchase Airtime</h1>
    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
        <label for="mobile_no">Mobile Number:</label>
        <input type="text" id="mobile_no" name="mobile_no" required>
        <br><br>

        <label for="amount">Amount:</label>
        <input type="number" id="amount" name="amount" required>
        <br><br>

        <label for="airtime_name">Select Network:</label>
        <select id="airtime_name" name="airtime_name" required>
            <?php
            // Include database connection
            require 'require/conn.php';

            // Fetch airtime options from the database
            $sql = "SELECT airtime_name FROM airtime_status WHERE status = 'On'";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    echo "<option value='" . $row['airtime_name'] . "'>" . $row['airtime_name'] . "</option>";
                }
            } else {
                echo "<option value=''>No networks available</option>";
            }

            // Close the database connection
            $conn->close();
            ?>
        </select>
        <br><br>

        <label for="transaction_pin">Transaction PIN:</label>
        <input type="password" id="transaction_pin" name="transaction_pin" required>
        <br><br>

        <button type="submit">Purchase Airtime</button>
    </form>
</body>
</html>