<?php
ob_start();
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

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

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'], $_POST['action'])) {
        
        $complaint_id = $_POST['id'];
        $sql_select = "
            SELECT 
                comp.id, comp.title, comp.description, comp.status, comp.created_at, comp.updated_at, 
                c.first_name, c.last_name, comp.client_id, 
                s.name as service_name, s.id as service_id
            FROM complaints comp
            LEFT JOIN clients c ON comp.client_id = c.id
            LEFT JOIN services s ON comp.service_id = s.id
            WHERE comp.id = :id
        ";

        // --- CASO 1: Actualizar Estado (Drag & Drop) ---
        if ($_POST['action'] === 'update_status' && isset($_POST['status'])) {
            try {
                $sql = "UPDATE complaints SET status = :status, updated_at = NOW() WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':status' => $_POST['status'],
                    ':id' => $complaint_id
                ]);

            } catch (PDOException $e) {
                error_log("Error PDO (Status) en complaints-update.php: " . $e->getMessage());
                $response['message'] = 'ERROR DE BASE DE DATOS (STATUS)';
            }
        } 
        
        // --- CASO 2: Actualizar Servicio (Dropdown) ---
        else if ($_POST['action'] === 'update_service') {
             try {
                $service_id = !empty($_POST['service_id']) ? $_POST['service_id'] : null;
                
                $sql = "UPDATE complaints SET service_id = :service_id, updated_at = NOW() WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':service_id' => $service_id,
                    ':id' => $complaint_id
                ]);

            } catch (PDOException $e) {
                error_log("Error PDO (Service) en complaints-update.php: " . $e->getMessage());
                $response['message'] = 'ERROR DE BASE DE DATOS (SERVICIO)';
            }
        }
        
        else {
            $response['message'] = 'ACCION INVALIDA';
            ob_end_clean();
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }

        // --- Respuesta común: Devolver la queja actualizada ---
        try {
            $stmt_select = $pdo->prepare($sql_select);
            $stmt_select->execute([':id' => $complaint_id]);
            $updated_complaint = $stmt_select->fetch(PDO::FETCH_ASSOC);
                
            $response_complaint = [
                'id' => $updated_complaint['id'],
                'title' => $updated_complaint['title'],
                'description' => $updated_complaint['description'],
                'client_name' => $updated_complaint['first_name'] ? trim($updated_complaint['first_name'] . ' ' . $updated_complaint['last_name']) : 'CLIENTE NO ENCONTRADO',
                'client_id' => $updated_complaint['client_id'],
                'service_name' => $updated_complaint['service_name'] ?? 'No asignado',
                'service_id' => $updated_complaint['service_id'] ?? null,
                'created_at' => $updated_complaint['created_at'],
                'status' => $updated_complaint['status'],
                'updated_at' => $updated_complaint['updated_at']
            ];

            $response['success'] = true;
            $response['message'] = 'QUEJA ACTUALIZADA';
            $response['complaint'] = $response_complaint;

        } catch (PDOException $e) {
             error_log("Error PDO al obtener queja actualizada en complaints-update.php: " . $e->getMessage());
             $response['message'] = 'ERROR AL OBTENER QUEJA ACTUALIZADA';
        }


    } else {
        $response['message'] = 'DATOS REQUERIDOS FALTANTES';
    }

} catch (Exception $e) {
    error_log("Error crítico en complaints-update.php: " . $e->getMessage());
    $response['message'] = 'ERROR CRITICO';
}

if (ob_get_level() > 0) {
    ob_end_clean(); 
}

header('Content-Type: application/json');
echo json_encode($response);
exit;