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

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

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        if (isset($_POST['title'], $_POST['description'], $_POST['client_id'])) {
            try {
                $pdo->beginTransaction();

                $sql = "INSERT INTO complaints (title, description, client_id, service_id, status) VALUES (:title, :description, :client_id, :service_id, 'Recibido')";
                $stmt = $pdo->prepare($sql);

                $stmt->execute([
                    ':title' => trim($_POST['title']),
                    ':description' => trim($_POST['description']),
                    ':client_id' => $_POST['client_id'],
                    ':service_id' => !empty($_POST['service_id']) ? $_POST['service_id'] : null
                ]);

                $new_complaint_id = $pdo->lastInsertId();

                $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' => $new_complaint_id]);
                $new_complaint = $stmt_select->fetch(PDO::FETCH_ASSOC);

                $response_complaint = [
                    'id' => $new_complaint['id'],
                    'title' => $new_complaint['title'],
                    'description' => $new_complaint['description'],
                    'client_name' => trim($new_complaint['first_name'] . ' ' . $new_complaint['last_name']),
                    'client_id' => $new_complaint['client_id'],
                    'service_name' => $new_complaint['service_name'] ?? 'NO ASIGNADO',
                    'service_id' => $new_complaint['service_id'] ?? null,
                    'created_at' => $new_complaint['created_at'],
                    'status' => $new_complaint['status'],
                    'updated_at' => $new_complaint['updated_at']
                ];

                $pdo->commit();
                $response['success'] = true;
                $response['message'] = 'QUEJA CREADA';
                $response['complaint'] = $response_complaint;

            } catch (PDOException $e) {
                $pdo->rollBack();
                error_log("Error PDO en complaints-create.php: " . $e->getMessage());
                $response['message'] = 'ERROR DE BASE DE DATOS';
            }
        } else {
            $response['message'] = 'DATOS REQUERIDOS FALTANTES';
        }
    } else {
        $response['message'] = 'METODO INVALIDO';
    }

} catch (Exception $e) {
    error_log("Error crítico en complaints-create.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;