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

try {
    require_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'], $_POST['action'])) {
        
        $complaint_id = $_POST['id'];

        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
                ]);

                if ($stmt->rowCount()) {
                    $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
                    ";
                    $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'] = 'ESTADO ACTUALIZADO';
                    $response['complaint'] = $response_complaint;
                } else {
                    $response['message'] = 'SIN CAMBIOS';
                }

            } catch (PDOException $e) {
                $response['message'] = 'ERROR DE BASE DE DATOS';
            }
        } else {
            $response['message'] = 'ACCION INVALIDA';
        }
    } else {
        $response['message'] = 'DATOS REQUERIDOS FALTANTES';
    }

} catch (Exception $e) {
    $response['message'] = 'ERROR CRITICO';
}

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

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