<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$dataFile = __DIR__ . '/../data/appointments.json';

// Read existing appointments
$appointments = [];
if (file_exists($dataFile)) {
    $content = file_get_contents($dataFile);
    $appointments = json_decode($content, true) ?: [];
}

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

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

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

// Create new appointment
$newAppointment = [
    'id' => time() . rand(100, 999),
    'name' => htmlspecialchars($input['name']),
    'email' => htmlspecialchars($input['email']),
    'phone' => htmlspecialchars($input['phone'] ?? 'Not provided'),
    'date' => htmlspecialchars($input['date']),
    'time' => htmlspecialchars($input['time']),
    'reason' => htmlspecialchars($input['reason']),
    'details' => htmlspecialchars($input['details'] ?? ''),
    'status' => 'pending',
    'submitted_at' => date('Y-m-d H:i:s')
];

// Add to appointments array
$appointments[] = $newAppointment;

// Save to file
if (file_put_contents($dataFile, json_encode($appointments, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true, 'message' => 'Appointment booked successfully', 'id' => $newAppointment['id']]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save appointment']);
}
