<?php
/**
 * PayPal Payment Callback Handler
 * Digital Marketplace
 */

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

header('Content-Type: application/json');

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

if (!$data) {
    json_response(['success' => false, 'message' => 'Invalid data']);
}

$order_id = (int)($data['order_id'] ?? 0);
$paypal_order_id = sanitize($data['paypal_order_id'] ?? '');
$paypal_payment_id = sanitize($data['paypal_payment_id'] ?? '');
$payer_email = sanitize($data['payer_email'] ?? '');
$status = sanitize($data['status'] ?? '');

if (!$order_id || !$paypal_payment_id) {
    json_response(['success' => false, 'message' => 'Missing required data']);
}

// Get order
$order = get_order_by_id($order_id);

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

if ($order['payment_status'] === 'paid') {
    json_response(['success' => true, 'redirect_url' => BASE_URL . '/account/order-view.php?id=' . $order_id]);
}

// Verify payment status
if ($status === 'COMPLETED') {
    try {
        // Update order payment status
        $stmt = $pdo->prepare("UPDATE orders SET 
            payment_status = 'paid',
            payment_id = ?,
            order_status = 'processing',
            paid_at = NOW(),
            updated_at = NOW()
            WHERE id = ?");
        $stmt->execute([$paypal_payment_id, $order_id]);
        
        // Log payment
        $stmt = $pdo->prepare("INSERT INTO payment_logs 
            (order_id, gateway, transaction_id, amount, currency, status, response, created_at)
            VALUES (?, 'paypal', ?, ?, ?, 'success', ?, NOW())");
        $stmt->execute([
            $order_id,
            $paypal_payment_id,
            $order['total'],
            CURRENCY,
            json_encode($data)
        ]);
        
        // Send confirmation email
        send_order_confirmation($order_id);
        
        // Log activity
        log_activity('payment_completed', "PayPal payment received for order #{$order['order_number']}");
        
        json_response([
            'success' => true,
            'message' => 'Payment successful!',
            'redirect_url' => BASE_URL . '/account/order-view.php?id=' . $order_id
        ]);
        
    } catch (PDOException $e) {
        error_log("PayPal callback error: " . $e->getMessage());
        json_response(['success' => false, 'message' => 'Payment processing error']);
    }
} else {
    // Payment failed or pending
    $stmt = $pdo->prepare("UPDATE orders SET 
        payment_status = ?,
        updated_at = NOW()
        WHERE id = ?");
    $stmt->execute([strtolower($status), $order_id]);
    
    json_response(['success' => false, 'message' => 'Payment ' . strtolower($status)]);
}
