<?php
session_start();
require_once('db_connection.php');

// 1. VERIFICAR LOGIN Y MÉTODO POST
if (!isset($_SESSION['client_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../clients/login.php');
    exit();
}

// 2. OBTENER Y VALIDAR DATOS
$client_id = $_SESSION['client_id'];
$complaint_id = filter_input(INPUT_POST, 'complaint_id', FILTER_VALIDATE_INT);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if (!$complaint_id || empty(trim($comment))) {
    $_SESSION['feedback'] = ['type' => 'error', 'message' => 'The comment cannot be empty.'];
    header('Location: ../clients/dashboard.php#complaints');
    exit();
}

try {
    // 3. VERIFICACIÓN DE SEGURIDAD: Comprobar que el reporte pertenece al cliente
    $stmt = $pdo->prepare("SELECT id FROM complaints WHERE id = ? AND client_id = ?");
    $stmt->execute([$complaint_id, $client_id]);
    if ($stmt->fetch() === false) {
        throw new Exception('Authorization error. Client does not own this complaint.');
    }

    // 4. INSERTAR EL NUEVO COMENTARIO EN LA TABLA 'complaint_updates'
    $insertStmt = $pdo->prepare(
        "INSERT INTO complaint_updates (complaint_id, message, type) VALUES (?, ?, 'portal_message')"
    );
    $insertStmt->execute([$complaint_id, $comment]);

    $_SESSION['feedback'] = ['type' => 'success', 'message' => 'Your comment has been submitted successfully!'];

} catch (Exception $e) {
    error_log("Error adding client comment: " . $e->getMessage());
    $_SESSION['feedback'] = ['type' => 'error', 'message' => 'An error occurred while submitting your comment.'];
}

header('Location: ../clients/dashboard.php#complaints');
exit();
?>