<?php ob_start();
require_once '../files/guardiankey.php'; ?>
<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

header('Content-Type: application/json');
include_once 'db_connection.php';

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

if (!$data || !isset($data['id']) || !isset($data['type'])) {
    $response = ['status' => 'error', 'message' => 'ID O TIPO DE CITA NO PROPORCIONADO'];
    ob_end_clean();
    echo json_encode($response);
    exit;
}

$id_parts = explode('-', $data['id']);
$id = filter_var(end($id_parts), FILTER_VALIDATE_INT);
$type = filter_var($data['type'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); 

if ($id === false) { 
    $response = ['status' => 'error', 'message' => 'ID DE CITA INVÁLIDO'];
    ob_end_clean();
    echo json_encode($response);
    exit;
}

try {
    $sql = "";
    if ($type === 'unica') {
        $sql = "DELETE FROM unique_appointments WHERE id = ?";
    } elseif ($type === 'recurrente') {
        $sql = "DELETE FROM recurring_appointments WHERE id = ?";
    } else {
        throw new Exception("TIPO DE CITA NO VÁLIDO");
    }

    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$id])) {
        if ($stmt->rowCount() > 0) {
            $response = ['status' => 'success', 'message' => 'ELIMINADO'];
        } else {
            $response = ['status' => 'error', 'message' => 'NO SE ENCONTRÓ LA CITA'];
        }
    } else {
        throw new Exception('FALLÓ LA CONSULTA DE ELIMINACIÓN');
    }

} catch (PDOException $e) {
    error_log("Error PDO en agenda-delete.php: " . $e->getMessage());
    $response = ['status' => 'error', 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("Error general en agenda-delete.php: " . $e->getMessage());
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

ob_end_clean();
echo json_encode($response);
exit;