<?php
ob_start();
ini_set('display_errors', 0); 
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once __DIR__ . '/../core/api.php';
global $pdo;

$input = json_decode(file_get_contents('php://input'), true);
$token = $input['token'] ?? '';

if (!$token) {
    echo json_encode(['status' => 'error', 'message' => 'Missing token']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id, status FROM unique_appointments WHERE public_token = ? LIMIT 1");
    $stmt->execute([$token]);
    $cita = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$cita) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Appointment']);
        exit;
    }

    if ($cita['status'] === 'confirmed') {
        echo json_encode(['status' => 'success', 'message' => 'Already confirmed']);
        exit;
    }

    $update = $pdo->prepare("UPDATE unique_appointments SET status = 'confirmed' WHERE id = ?");
    $update->execute([$cita['id']]);

    echo json_encode(['status' => 'success', 'message' => 'Confirmed']);

} catch (PDOException $e) {
    error_log("Error PDO en agenda-confirm-handler.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database Error']);
} catch (Exception $e) {
    error_log("Error general en agenda-confirm-handler.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Server Error']);
}

ob_end_clean();
exit;