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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['payment_method_id']) || !isset($input['booking_id']) || !isset($input['amount'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request data']);
    exit();
}

$booking_id = (int) $input['booking_id'];
$amount = (float) $input['amount'];

try {
    $conn = createDatabaseConnection(true);
} catch (RuntimeException $exception) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit();
}

$stmt = $conn->prepare('SELECT user_id, total_amount FROM bookings WHERE id = ?');
$stmt->bind_param('i', $booking_id);
$stmt->execute();
$result = $stmt->get_result();
$booking = $result->fetch_assoc();
$stmt->close();

if (!$booking) {
    $conn->close();
    http_response_code(404);
    echo json_encode(['error' => 'Booking not found']);
    exit();
}

if (((float) $booking['total_amount']) * 100 != $amount) {
    $conn->close();
    http_response_code(400);
    echo json_encode(['error' => 'Amount mismatch']);
    exit();
}

$transaction_id = 'demo_txn_' . time() . '_' . rand(1000, 9999);
$amount_dollars = $amount / 100;
$payment_method = 'demo_card';
$status = 'completed';

$stmt = $conn->prepare("UPDATE bookings SET status = 'confirmed' WHERE id = ?");
$stmt->bind_param('i', $booking_id);
$stmt->execute();
$stmt->close();

$stmt = $conn->prepare('INSERT INTO payments (booking_id, user_id, amount, payment_method, transaction_id, status) VALUES (?, ?, ?, ?, ?, ?)');
$stmt->bind_param('iissss', $booking_id, $booking['user_id'], $amount_dollars, $payment_method, $transaction_id, $status);
$stmt->execute();
$stmt->close();
$conn->close();

echo json_encode(['success' => true, 'transaction_id' => $transaction_id]);
?>