<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Payment.php');

session_start();

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$orderId = $data['order_id'] ?? null;
$paymentId = $data['payment_id'] ?? null;
$razorpayOrderId = $data['razorpay_order_id'] ?? null;

if (!$orderId || !$paymentId) {
    echo json_encode(['status' => 'error', 'message' => 'Missing payment details']);
    exit;
}

$db = Database::getInstance();
$payment = new Payment();
$userId = $_SESSION['user_id'];

// Verify order exists and belongs to user
$order = $db->fetch(
    'SELECT * FROM payment_orders WHERE order_id = ? AND user_id = ? AND status = "pending"',
    [$orderId, $userId]
);

if (!$order) {
    echo json_encode(['status' => 'error', 'message' => 'Order not found or already processed']);
    exit;
}

try {
    // In production, verify with Razorpay API
    // For now, we'll confirm the payment
    $result = $payment->confirmPayment($orderId, $paymentId, 'razorpay');
    
    if ($result['status']) {
        echo json_encode([
            'status' => 'success',
            'message' => 'Payment verified successfully'
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => $result['message']
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Payment verification failed: ' . $e->getMessage()
    ]);
}
?>
