<?php
include "db.php";

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') exit;

// Get Paystack webhook body
$input = file_get_contents("php://input");
$event = json_decode($input, true);

if ($event['event'] == 'charge.success') {
    $reference = $event['data']['reference'];
    $email = $event['data']['customer']['email'];
    $course_id = $event['data']['metadata']['course_id']; // send this in metadata when creating transaction

    // Get user_id by email
    $stmt = $conn->prepare("SELECT id FROM users WHERE email=?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($user) {
        $user_id = $user['id'];

        // Insert into user_courses if not exists
        $stmt = $conn->prepare("SELECT * FROM user_courses WHERE user_id=? AND course_id=?");
        $stmt->bind_param("ii", $user_id, $course_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0) {
            $stmt = $conn->prepare("INSERT INTO user_courses (user_id, course_id, progress, purchased_at) VALUES (?, ?, 0, NOW())");
            $stmt->bind_param("ii", $user_id, $course_id);
            $stmt->execute();
        }
    }
}

// Respond to Paystack
http_response_code(200);
