<?php
/**
 * Paystack Callback Handler
 * Digital Product Store
 */

require_once __DIR__ . '/../config/database.php';
require_login();

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$reference = $_GET['reference'] ?? '';

if (!$order_id || !$reference) {
    set_flash_message('Invalid payment response.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    set_flash_message('Order not found.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get Paystack settings
$paystack = get_payment_gateway('paystack');
$secret_key = $paystack['config']['secret_key'] ?? '';

// Verify transaction
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.paystack.co/transaction/verify/' . $reference);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$headers = [];
$headers[] = 'Authorization: Bearer ' . $secret_key;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
curl_close($ch);

$response = json_decode($result, true);

if (isset($response['status']) && $response['status'] === true && $response['data']['status'] === 'success') {
    // Update order status
    update_order_payment_status($order_id, 'paid', $reference);
    
    // Update transaction
    $stmt = $pdo->prepare("UPDATE payment_transactions SET status = 'completed', response_data = ? WHERE transaction_id = ?");
    $stmt->execute([json_encode($response), $reference]);
    
    // Create download links
    $order_items = get_order_items($order_id);
    foreach ($order_items as $item) {
        create_download_link($order_id, $item['product_id'], get_current_user_id());
    }
    
    // Send confirmation email
    $subject = 'Order Confirmation - ' . $order['order_number'];
    $body = "<h2>Thank you for your order!</h2>
            <p>Your order <strong>{$order['order_number']}</strong> has been confirmed.</p>
            <p>Total: " . format_price($order['total']) . "</p>
            <p>You can view your order and download your products from your account.</p>";
    send_email($order['customer_email'], $subject, $body);
    
    // Send notification to admin
    $admin_email = get_setting('order_notification_email', get_setting('site_email'));
    if ($admin_email) {
        $admin_subject = 'New Order - ' . $order['order_number'];
        $admin_body = "<h2>New Order Received</h2>
                      <p>Order Number: {$order['order_number']}</p>
                      <p>Customer: {$order['customer_name']}</p>
                      <p>Total: " . format_price($order['total']) . "</p>";
        send_email($admin_email, $admin_subject, $admin_body);
    }
    
    // Create admin notification
    create_admin_notification('order', 'New Order', 'Order ' . $order['order_number'] . ' has been paid', 'orders.php');
    
    set_flash_message('Payment successful! Thank you for your order.', 'success');
    header('Location: ' . BASE_URL . '/order-confirmation.php?order_id=' . $order_id);
    exit;
} else {
    set_flash_message('Payment verification failed.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}
