<?php
/**
 * Flutterwave 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['transaction_id']) || !isset($data['orderNumber'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit;
}

$transaction_id = sanitize($data['transaction_id']);
$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 Flutterwave settings
$flutterwave_settings = get_payment_settings('flutterwave');
$flutterwave_config = $flutterwave_settings['config'] ?? [];
$secret_key = $flutterwave_config['secret_key'] ?? '';
$test_mode = $flutterwave_settings['test_mode'] ?? 1;

// Verify payment with Flutterwave API
$verify_url = 'https://api.flutterwave.com/v3/transactions/' . $transaction_id . '/verify';

$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,
    'Content-Type: application/json'
]);

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

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

$result = json_decode($response, true);

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

$transaction = $result['data'];

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

// Verify amount matches
$expected_amount = floatval($order['total']);
$received_amount = floatval($transaction['amount']);

if (abs($received_amount - $expected_amount) > 0.01) {
    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([$transaction_id, $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', "Flutterwave payment for order {$order_number}");
    
    echo json_encode(['success' => true]);
    
} catch (PDOException $e) {
    error_log('Flutterwave verification failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>