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

$response = ['status' => 'error', 'message' => 'SOLICITUD NO VÁLIDA'];

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en agenda-update.php: " . json_last_error_msg());
        $response['message'] = 'ERROR AL PROCESAR LOS DATOS';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $id = isset($data['id']) ? filter_var($data['id'], FILTER_VALIDATE_INT) : null;
    $type = filter_var($data['type'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $new_status = filter_var($data['status'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if ($id === false || empty($type)) {
        $response['message'] = 'FALTAN DATOS OBLIGATORIOS (ID, TIPO)';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    try {
        if ($new_status) {
            $stmt = $pdo->prepare("UPDATE unique_appointments SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $id]);
            $response = ['status' => 'success', 'message' => 'ESTADO ACTUALIZADO'];
            
        } elseif ($type === 'unica' || $type === 'child_recurrente') {
            $appointment_date = filter_var($data['appointment_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $raw_time = $data['appointment_time'] ?? '09:00';
            $appointment_time = date('H:i:s', strtotime($raw_time));
            $notes = filter_var($data['notes'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            if (empty($appointment_date)) {
                $response['message'] = 'FALTA DATO OBLIGATORIO (FECHA)';
                ob_end_clean();
                echo json_encode($response);
                exit;
            }

            $stmt = $pdo->prepare("UPDATE unique_appointments SET appointment_date = ?, appointment_time = ?, notes = ? WHERE id = ?");
            $stmt->execute([$appointment_date, $appointment_time, $notes, $id]);
            $response = ['status' => 'success', 'message' => 'GUARDADO'];

        } elseif ($type === 'recurrente') {
            $frequency = filter_var($data['frequency'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $notes = filter_var($data['notes'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            if (empty($frequency)) {
                $response['message'] = 'FALTA DATO OBLIGATORIO (FRECUENCIA)';
                ob_end_clean();
                echo json_encode($response);
                exit;
            }

            $stmt = $pdo->prepare("UPDATE recurring_appointments SET frequency = ?, notes = ? WHERE id = ?");
            $stmt->execute([$frequency, $notes, $id]);
            $response = ['status' => 'success', 'message' => 'GUARDADO'];

        } else {
            $response['message'] = 'TIPO DE CITA NO RECONOCIDO';
        }

    } catch (PDOException $e) {
        error_log("Error PDO al actualizar cita en agenda-update.php: " . $e->getMessage());
        $response['message'] = 'ERROR DE BASE DE DATOS';
    } catch (Exception $e) {
        error_log("Error general al actualizar cita en agenda-update.php: " . $e->getMessage());
        $response['message'] = 'ERROR GENERAL';
    }

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