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

require_once __DIR__ . '/../config/database.php';

// Get JSON data
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (!$data || !isset($data['reference']) || !isset($data['orderNumber'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit;
}

$reference = sanitize($data['reference']);
$order_number = sanitize($data['orderNumber']);

// Get order
$order = get_order_by_number($order_number);

if (!$order) {
    echo json_encode(['success' => false, 'message' => 'Order not found']);
    exit;
}

// Get Paystack settings
$paystack_settings = get_payment_settings('paystack');
$paystack_config = $paystack_settings['config'] ?? [];
$secret_key = $paystack_config['secret_key'] ?? '';
$test_mode = $paystack_settings['test_mode'] ?? 1;

// Verify payment with Paystack API
$verify_url = 'https://api.paystack.co/transaction/verify/' . $reference;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $verify_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $secret_key,
    'Cache-Control: no-cache'
]);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

if ($curl_error) {
    error_log('Paystack API error: ' . $curl_error);
    echo json_encode(['success' => false, 'message' => 'Payment verification failed']);
    exit;
}

$result = json_decode($response, true);

if (!$result || !$result['status']) {
    echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Verification failed']);
    exit;
}

$transaction = $result['data'];

// Check if payment was successful
if ($transaction['status'] !== 'success') {
    echo json_encode(['success' => false, 'message' => 'Payment was not successful']);
    exit;
}

// Verify amount matches (in kobo)
$expected_amount = intval($order['total'] * 100);
$received_amount = $transaction['amount'];

if ($received_amount < $expected_amount) {
    echo json_encode(['success' => false, 'message' => 'Amount mismatch']);
    exit;
}

try {
    // Update order status
    $stmt = $pdo->prepare("UPDATE orders SET 
        payment_status = 'completed',
        order_status = 'completed',
        transaction_id = ?,
        updated_at = NOW()
        WHERE order_number = ?");
    $stmt->execute([$reference, $order_number]);
    
    // Clear cart and coupon
    clear_cart();
    clear_coupon();
    
    // Send order confirmation email
    send_order_confirmation($order['id']);
    
    // Log activity
    log_activity('Payment Completed', "Paystack payment for order {$order_number}");
    
    echo json_encode(['success' => true]);
    
} catch (PDOException $e) {
    error_log('Paystack verification failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>