<?php
header('Content-Type: application/json');
require_once '../includes/init.php';

$json_data = file_get_contents('php://input');
$data = json_decode($json_data);

$orderID = $data->orderID ?? '';
$booking_ref = $data->booking_ref ?? '';
$booking_type = $data->booking_type ?? '';

// Map booking types to their respective tables
$table_map = ['tour' => 'bookings', 'hotel' => 'hotel_bookings', 'flight' => 'flight_bookings', 'ferry' => 'ferry_bookings'];
if (!array_key_exists($booking_type, $table_map)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid booking type.']);
    exit();
}
$table_name = $table_map[$booking_type];

// A professional site would now make a server-side call to the PayPal API to verify the orderID and amount paid.
// This step is critical for security to prevent fraudulent transactions.

$stmt = $conn->prepare("SELECT id, total_price, currency FROM `$table_name` WHERE booking_ref = ? AND payment_status = 'Unpaid'");
$stmt->bind_param("s", $booking_ref);
$stmt->execute();
$booking = $stmt->get_result()->fetch_assoc();

if ($booking) {
    $conn->begin_transaction();
    try {
        // 1. Update the booking status in the correct table
        $stmt_update = $conn->prepare("UPDATE `$table_name` SET payment_status = 'Paid' WHERE booking_ref = ?");
        $stmt_update->bind_param("s", $booking_ref);
        $stmt_update->execute();

        // 2. Log the payment in the `payments` table
        $stmt_log = $conn->prepare("INSERT INTO payments (booking_id, booking_ref, booking_type, transaction_id, payment_gateway, amount, currency, status) VALUES (?, ?, ?, ?, 'PayPal', ?, ?, 'Completed')");
        $stmt_log->bind_param("isssds", $booking['id'], $booking_ref, $booking_type, $orderID, $booking['total_price'], $booking['currency']);
        $stmt_log->execute();
        
        $conn->commit();
        echo json_encode(['status' => 'success', 'booking_ref' => $booking_ref]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Database update failed.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Booking not found or already paid.']);
}
