<?php
header("Content-Type: application/json");
include_once 'model/service_model.php';

$service_model = new service_model();

// Get and decode JSON input
$data = json_decode(file_get_contents("php://input"), true);

// Validate required fields
$required = ['name', 'sex', 'phone', 'date', 'time', 'service', 'cost'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit;
    }
}

// OPTIONAL: Email and notes can be empty
$name = $data['name'];
$sex = $data['sex'];
$phone = $data['phone'];
$email = $data['email'] ?? '';
$notes = $data['notes'] ?? '';
$service = $data['service'];
$date = $data['date'];
$time = $data['time'];
$cost = $data['cost'];

try {
    $insert_booking = $service_model->captureBooking($name, $sex, $phone, $email, $notes, $service, $date, $time, $cost);

    if ($insert_booking) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Booking could not be saved.']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
