<?php
ob_start();
ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';
global $pdo;

$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 {
    $pdo->beginTransaction();

    if ($type === 'unica') {
        $sql = "DELETE FROM unique_appointments WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $message = 'CITA ÚNICA ELIMINADA';
    } elseif ($type === 'recurrente') {
        $sql_children = "DELETE FROM unique_appointments WHERE recurring_parent_id = ?";
        $stmt_children = $pdo->prepare($sql_children);
        $stmt_children->execute([$id]);
        $deleted_children = $stmt_children->rowCount();

        $sql_master = "DELETE FROM recurring_appointments WHERE id = ?";
        $stmt_master = $pdo->prepare($sql_master);
        $stmt_master->execute([$id]);

        $message = "CITA RECURRENTE MAESTRA ELIMINADA y $deleted_children citas futuras canceladas.";
    } else {
        throw new Exception("TIPO DE CITA NO VÁLIDO");
    }

    $pdo->commit();
    $response = ['status' => 'success', 'message' => $message];

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

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