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

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

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

if (!$order_id) {
    set_flash_message('Invalid order.', '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');

if (!$paystack) {
    set_flash_message('Paystack is not configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

$config = $paystack['config'];
$secret_key = $config['secret_key'] ?? '';
$public_key = $config['public_key'] ?? '';

if (empty($secret_key)) {
    set_flash_message('Paystack is not properly configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Initialize Paystack transaction
$callback_url = BASE_URL . '/payment/paystack-callback.php?order_id=' . $order_id;

$post_data = [
    'email' => $order['customer_email'],
    'amount' => round($order['total'] * 100), // Amount in kobo (for NGN) or smallest currency unit
    'reference' => $order['order_number'] . '_' . time(),
    'callback_url' => $callback_url,
    'metadata' => [
        'order_id' => $order_id,
        'order_number' => $order['order_number'],
        'customer_name' => $order['customer_name']
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.paystack.co/transaction/initialize');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

$headers = [];
$headers[] = 'Authorization: Bearer ' . $secret_key;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    set_flash_message('Payment processing error.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}
curl_close($ch);

$response = json_decode($result, true);

if (isset($response['status']) && $response['status'] === true && isset($response['data']['authorization_url'])) {
    // Store Paystack reference
    $stmt = $pdo->prepare("UPDATE orders SET payment_id = ? WHERE id = ?");
    $stmt->execute([$post_data['reference'], $order_id]);
    
    // Record transaction
    record_payment_transaction($order_id, 'paystack', $post_data['reference'], $order['total']);
    
    // Redirect to Paystack
    header('Location: ' . $response['data']['authorization_url']);
    exit;
}

set_flash_message('Could not initialize Paystack payment.', 'error');
header('Location: ' . BASE_URL . '/checkout.php');
exit;
