<?php
require_once '../../app/db.php';

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

function calculatePrice($service, $region, $hours) {

    switch($service) {
        case 'arrival': return 65;
        case 'departure':
            return ($region === 'East') ? 60 : 70;
        case 'point': return 65;
        case 'city': return 120;
        case 'limo': return 120;
        case 'hourly': return 15 + ($hours * 15);
        default: return 0;
    }
}

try {

    $name   = trim($_POST['name'] ?? '');
    $phone  = trim($_POST['phone'] ?? '');
    $email  = trim($_POST['email'] ?? '');

    $service = $_POST['service_type'] ?? '';
    $region  = $_POST['region'] ?? null;
    $pickup  = trim($_POST['pickup_location'] ?? '');
    $dropoff = trim($_POST['dropoff_location'] ?? '');
    $hours   = intval($_POST['hours'] ?? 0);
    $vehicle = $_POST['vehicle_type'] ?? '';
    $pickup_datetime = $_POST['pickup_datetime'] ?? '';

    if (!$name || !$phone || !$service || !$pickup || !$dropoff || !$vehicle || !$pickup_datetime) {
        throw new Exception("Missing required fields.");
    }

    $price = calculatePrice($service, $region, $hours);

    if ($price <= 0) {
        throw new Exception("Invalid price calculation.");
    }

    $pdo->beginTransaction();

    /* ===== FIND OR CREATE CUSTOMER ===== */
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE phone=? LIMIT 1");
    $stmt->execute([$phone]);
    $existingCustomer = $stmt->fetchColumn();

    if ($existingCustomer) {
        $customer_id = $existingCustomer;
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO customers (name, phone, email)
            VALUES (?, ?, ?)
        ");
        $stmt->execute([$name, $phone, $email]);
        $customer_id = $pdo->lastInsertId();
    }

    /* ===== GENERATE BOOKING CODE ===== */
    $booking_code = 'EC' . strtoupper(substr(md5(uniqid()), 0, 6));

    /* ===== INSERT BOOKING ===== */
    $stmt = $pdo->prepare("
        INSERT INTO bookings
        (booking_code, customer_id, service_type, region,
         pickup_location, dropoff_location, hours,
         vehicle_type, estimated_price, status,
         pickup_datetime)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
    ");

    $stmt->execute([
        $booking_code,
        $customer_id,
        $service,
        $region,
        $pickup,
        $dropoff,
        $hours,
        $vehicle,
        $price,
        $pickup_datetime
    ]);

    $booking_id = $pdo->lastInsertId();

    /* ===== INSERT NOTIFICATION ===== */
    $stmt = $pdo->prepare("
        INSERT INTO notifications (title, message, type, booking_id)
        VALUES (
            'New Booking',
            CONCAT('Booking ', ?, ' created.'),
            'booking',
            ?
        )
    ");

    $stmt->execute([$booking_code, $booking_id]);

    $pdo->commit();

    /* ===== RESPONSE ===== */
    if (isset($_SERVER['HTTP_ACCEPT']) && 
        strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {

        echo json_encode([
            'success' => true,
            'booking_code' => $booking_code,
            'booking_id' => $booking_id,
            'estimated_price' => $price
        ]);
        exit;
    }

    /* Fallback for form submission */
    header("Location: ../booking_success.php?code=" . $booking_code);
    exit;

} catch (Exception $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    http_response_code(400);

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
