<?php
require_once "config.php";
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$agent_id = $_SESSION['user_id'];

// Ensure reference is passed
if (!isset($_GET['reference'])) {
    die("No reference supplied");
}

$reference = $_GET['reference'];

// Paystack secret key
$secret_key = "sk_test_241adee0b21e498272b5f9c48e31024416d2a034";

// Verify transaction from Paystack
$url = "https://api.paystack.co/transaction/verify/" . urlencode($reference);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . $secret_key
]);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if ($result && isset($result['status']) && $result['status'] == true && $result['data']['status'] == 'success') {
    $amount   = $result['data']['amount'] / 100; // convert kobo to naira
    $currency = $result['data']['currency'];
    $txn_ref  = $result['data']['reference'];

    // ✅ Update wallet balance
    $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
    $stmt->bind_param("di", $amount, $agent_id);
    $stmt->execute();
    $stmt->close();

    // ✅ Log into transactions
    $type = "credit";
    $description = "Deposit";
    $status = "completed";

    $stmt2 = $conn->prepare("
        INSERT INTO transactions (user_id, type, amount, currency, description, reference, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt2->bind_param("isdssss", $agent_id, $type, $amount, $currency, $description, $txn_ref, $status);
    $stmt2->execute();
    $stmt2->close();

    // Redirect back to dashboard
    header("Location: agent_dash.php?deposit=success");
    exit();

} else {
    // ❌ Failed verification
    header("Location: agent_dash.php?deposit=failed");
    exit();
}
?>
