<?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']) || !isset($input['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing id or status']);
    exit;
}

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

$found = false;
foreach ($appointments as &$apt) {
    if ($apt['id'] == $input['id']) {
        $apt['status'] = htmlspecialchars($input['status']);
        $apt['updated_at'] = date('Y-m-d H:i:s');
        $found = true;
        break;
    }
}

if ($found && file_put_contents($dataFile, json_encode($appointments, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true, 'message' => 'Status updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Appointment not found or failed to save']);
}
