<?php
// /payment/verify.php
require_once __DIR__ . '/../includes/db.php'; // Includes session_start()
require_once __DIR__ . '/../config.php';

if (!isset($_GET['reference'])) {
    die("No payment reference supplied.");
}

$reference = $_GET['reference'];

// --- Verify Transaction with Paystack ---
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array(
        "accept: application/json",
        "authorization: Bearer " . PAYSTACK_SECRET_KEY, // Use the constant from config.php
        "cache-control: no-cache"
    ),
));

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

if ($err) {
    // cURL error
    die("cURL Error: " . $err);
}

$tranx = json_decode($response);

if (!$tranx->status) {
    // API call failed
    die("API returned error: " . $tranx->message);
}

// --- Process Payment Status ---
$page_title = "Payment Status";
require_once __DIR__ . '/../includes/header.php';

echo '<div class="container mx-auto px-4 py-12 text-center">';

if ('success' == $tranx->data->status) {
    // Payment was successful
    $status = $tranx->data->status;
    $amount = $tranx->data->amount / 100; // Convert from kobo
    $metadata = $tranx->data->metadata;
    $user_id = $metadata->user_id;
    $plan_id = $metadata->plan_id;
    $ad_ids_to_promote = json_decode($metadata->ad_ids, true);

    // Check if transaction is already processed
    $stmt_check = $conn->prepare("SELECT id FROM user_subscriptions WHERE payment_reference = ?");
    $stmt_check->bind_param("s", $reference);
    $stmt_check->execute();
    if ($stmt_check->get_result()->num_rows > 0) {
        echo '<h1 class="text-2xl font-bold text-yellow-600">This transaction has already been processed.</h1>';
    } else {
        // Fetch plan duration
        $stmt_plan = $conn->prepare("SELECT duration_days, promotion_type, commission_rate FROM subscriptions WHERE id = ?");
        $stmt_plan->bind_param("i", $plan_id);
        $stmt_plan->execute();
        $plan_details = $stmt_plan->get_result()->fetch_assoc();
        $plan_duration = $plan_details['duration_days'];
        $plan_commission_rate = $plan_details['commission_rate'];
        $stmt_plan->close();

        // Calculate end date
        $end_date = date('Y-m-d H:i:s', strtotime("+$plan_duration days"));

        $conn->begin_transaction();
        try {
            // Insert into user_subscriptions table
            $stmt_insert = $conn->prepare("INSERT INTO user_subscriptions (user_id, subscription_id, start_date, end_date, payment_status, payment_reference) VALUES (?, ?, NOW(), ?, 'paid', ?)");
            $stmt_insert->bind_param("iiss", $user_id, $plan_id, $end_date, $reference);
            $stmt_insert->execute();
            $user_subscription_id = $conn->insert_id;
            $stmt_insert->close();

            // Promote the selected ads
            if (!empty($ad_ids_to_promote)) {
                $stmt_promote = $conn->prepare("UPDATE ads SET user_subscription_id = ?, promotion_expiry_date = ? WHERE id = ? AND user_id = ?");
                foreach ($ad_ids_to_promote as $ad_id) {
                    $stmt_promote->bind_param("isii", $user_subscription_id, $end_date, $ad_id, $user_id);
                    $stmt_promote->execute();
                }
                $stmt_promote->close();
            }
            
            // --- COMMISSION LOGIC (MOVED HERE) ---
            $stmt_check_ref = $conn->prepare("SELECT id, partner_user_id FROM referrals WHERE referred_user_id = ?");
            $stmt_check_ref->bind_param("i", $user_id);
            $stmt_check_ref->execute();
            $referral = $stmt_check_ref->get_result()->fetch_assoc();
            $stmt_check_ref->close();

            if ($referral) {
                $referral_id = $referral['id'];
                $commission_amount = $amount * $plan_commission_rate;
                
                $stmt_commission = $conn->prepare("INSERT INTO commissions (referral_id, user_subscription_id, commission_amount, commission_rate) VALUES (?, ?, ?, ?)");
                $stmt_commission->bind_param("iidd", $referral_id, $user_subscription_id, $commission_amount, $plan_commission_rate);
                $stmt_commission->execute();
                $stmt_commission->close();
            }
            // --- END COMMISSION LOGIC ---

            $conn->commit();
            
            // Success message
            echo '<i data-lucide="check-circle" class="w-24 h-24 mx-auto text-green-500"></i>';
            echo '<h1 class="text-3xl font-bold mt-4">Payment Successful!</h1>';
            echo '<p class="text-gray-700 mt-2">Your subscription is now active, and your selected ads have been promoted.</p>';
            echo '<a href="/user/dashboard.php" class="mt-6 inline-block bg-blue-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-blue-700">Go to Dashboard</a>';

        } catch (Exception $e) {
            $conn->rollback();
            error_log("Database Error on verify.php: " . $e->getMessage());

            echo '<i data-lucide="x-circle" class="w-24 h-24 mx-auto text-red-500"></i>';
            echo '<h1 class="text-3xl font-bold mt-4">Database Error</h1>';
            echo '<p class="text-gray-700 mt-2">Your payment was successful, but we could not activate your subscription. Please contact support with reference: ' . htmlspecialchars($reference) . '</p>';
        }
    }
    $stmt_check->close();
} else {
    // Payment was not successful
    echo '<i data-lucide="x-circle" class="w-24 h-24 mx-auto text-red-500"></i>';
    echo '<h1 class="text-3xl font-bold mt-4">Payment Failed</h1>';
    echo '<p class="text-gray-700 mt-2">Unfortunately, the transaction was not successful: ' . htmlspecialchars($tranx->data->gateway_response) . '. Please try again.</p>';
    echo '<a href="/user/subscriptions.php" class="mt-6 inline-block bg-blue-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-blue-700">Try Again</a>';
}

echo '</div>';

require_once __DIR__ . '/../includes/footer.php';
?>