<?php
session_start();
include "db.php";

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

if (!isset($_GET['reference'], $_GET['course'])) {
    die("Invalid request");
}

$reference = $_GET['reference'];
$course_id = intval($_GET['course']);
$user_id   = $_SESSION['user_id'];

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

// Get user fullname
$userStmt = $conn->prepare("SELECT fullname FROM users WHERE id = ?");
$userStmt->bind_param("i", $user_id);
$userStmt->execute();
$userResult = $userStmt->get_result();

if ($userResult->num_rows === 0) {
    die("User not found");
}

$user = $userResult->fetch_assoc();
$fullname = $user['fullname'];

// Verify payment
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $secret_key"
    ]
]);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if ($result['status'] && $result['data']['status'] === 'success') {

    $amount = $result['data']['amount'] / 100;
    $status = "success";

    // Prevent duplicate payment
    $checkPay = $conn->prepare(
        "SELECT id FROM user_payments WHERE reference = ?"
    );
    $checkPay->bind_param("s", $reference);
    $checkPay->execute();
    $exists = $checkPay->get_result();

    if ($exists->num_rows === 0) {
        $insertPay = $conn->prepare("
            INSERT INTO user_payments
            (user_id, fullname, course_id, reference, amount, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        $insertPay->bind_param(
            "isisss",
            $user_id,
            $fullname,
            $course_id,
            $reference,
            $amount,
            $status
        );
        $insertPay->execute();
    }

    // Grant course access
    $courseCheck = $conn->prepare(
        "SELECT id FROM user_courses WHERE user_id = ? AND course_id = ?"
    );
    $courseCheck->bind_param("ii", $user_id, $course_id);
    $courseCheck->execute();
    $hasCourse = $courseCheck->get_result();

    if ($hasCourse->num_rows === 0) {
        $addCourse = $conn->prepare("
            INSERT INTO user_courses
            (user_id, course_id, progress, purchased_at)
            VALUES (?, ?, 0, NOW())
        ");
        $addCourse->bind_param("ii", $user_id, $course_id);
        $addCourse->execute();
    }

    echo "<script>
        alert('Payment Successful! Course added to your account.');
        window.location='dashboard.php';
    </script>";

} else {
    echo "<script>
        alert('Payment verification failed!');
        window.location='pay.php?course=$course_id';
    </script>";
}
