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

require_once 'db_connection.php';

$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 !== null) { 
            if ($type === 'unica') {
                $stmt = $pdo->prepare("UPDATE unique_appointments SET status = ? WHERE id = ?");
                $stmt->execute([$new_status, $id]);
            }
            // Para 'recurrente' o cualquier otro, solo devolvemos éxito
            $response = ['status' => 'success', 'message' => 'GUARDADO'];
            
            ob_end_clean();
            echo json_encode($response); 
            exit;
        }

        $notes = filter_var($data['notes'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        
        if ($type === 'unica') {
            $appointment_date = filter_var($data['appointment_date'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $appointment_time = filter_var($data['appointment_time'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            if (empty($appointment_date) || empty($appointment_time)) {
                $response['message'] = 'FALTAN DATOS OBLIGATORIOS (FECHA, HORA)';
                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);

            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 INTERNO DEL SERVIDOR';
    }
}

ob_end_clean();
echo json_encode($response);