<?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';

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

if (!$input || !isset($input['id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing id']);
    exit;
}

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

$originalCount = count($appointments);
$appointments = array_filter($appointments, function($apt) use ($input) {
    return $apt['id'] != $input['id'];
});
$appointments = array_values($appointments); // Re-index array

if (count($appointments) < $originalCount && file_put_contents($dataFile, json_encode($appointments, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true, 'message' => 'Appointment deleted']);
} else {
    echo json_encode(['success' => false, 'message' => 'Appointment not found or failed to delete']);
}
