<?php

// Rest of your code...

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/payment_error.log');

if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

try {
    require_once __DIR__ . '/config/db.php';
    require_once __DIR__ . '/config/razorpay.php';

    $input = json_decode(file_get_contents('php://input'), true);

    // Validate required fields
    if (!$input || !isset($input['razorpay_order_id']) || 
        !isset($input['razorpay_payment_id']) || 
        !isset($input['razorpay_signature'])) {
        throw new Exception('Missing required payment verification fields');
    }

    $razorpayOrderId = $input['razorpay_order_id'];
    $razorpayPaymentId = $input['razorpay_payment_id'];
    $razorpaySignature = $input['razorpay_signature'];
    $orderId = $input['orderId'] ?? null;

    // Verify signature
    $expectedSignature = hash_hmac(
        'sha256',
        "{$razorpayOrderId}|{$razorpayPaymentId}",
        RAZORPAY_KEY_SECRET
    );

    if ($expectedSignature !== $razorpaySignature) {
        throw new Exception('Invalid payment signature. Signature verification failed.');
    }

    // Fetch payment details from Razorpay
    $api = new RazorpayAPI(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET);
    $payment = $api->payment->fetch($razorpayPaymentId);

    if (!$payment) {
        throw new Exception('Payment details not found on Razorpay');
    }

    // Verify payment status
    if ($payment['status'] !== 'captured') {
        throw new Exception('Payment not captured. Status: ' . $payment['status']);
    }

    // Update order in database
    $updateQuery = "UPDATE orders 
                    SET razorpay_payment_id = ?, 
                        payment_status = 'success',
                        updated_at = NOW()
                    WHERE id = ? OR razorpay_order_id = ?";

    $updateStmt = $conn->prepare($updateQuery);
    if (!$updateStmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $paymentStatus = 'success';
    $updateStmt->bind_param('sis', $razorpayPaymentId, $orderId, $razorpayOrderId);
    
    if (!$updateStmt->execute()) {
        throw new Exception('Failed to update order: ' . $updateStmt->error);
    }

    $updateStmt->close();

    // Fetch updated order details
    $orderQuery = "SELECT id, razorpay_order_id, razorpay_payment_id, amount, 
                          subtotal, gst, payment_status, created_at 
                   FROM orders 
                   WHERE razorpay_order_id = ? 
                   LIMIT 1";

    $orderStmt = $conn->prepare($orderQuery);
    if (!$orderStmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $orderStmt->bind_param('s', $razorpayOrderId);
    if (!$orderStmt->execute()) {
        throw new Exception('Failed to fetch order: ' . $orderStmt->error);
    }

    $orderResult = $orderStmt->get_result();
    if ($orderResult->num_rows === 0) {
        throw new Exception('Order not found after verification');
    }

    $order = $orderResult->fetch_assoc();
    $orderStmt->close();

    // Return success response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Payment verified successfully',
        'orderId' => $order['id'],
        'razorpay_order_id' => $order['razorpay_order_id'],
        'razorpay_payment_id' => $order['razorpay_payment_id'],
        'amount' => floatval($order['amount']),
        'payment_status' => $order['payment_status'],
        'timestamp' => $order['created_at']
    ]);

} catch (Exception $e) {
    error_log('Payment verification error: ' . $e->getMessage());
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => $e->getMessage()
    ]);
}
?>