<?php
// Endpoint: agregar mensaje a ticket del cliente
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

header('Content-Type: application/json; charset=utf-8');

function error_response($msg, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

if (!isset($_SESSION['client_id'])) {
    error_response('No autenticado', 401);
}
$client_id = (int)$_SESSION['client_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_response('Método no permitido', 405);
}

$ticket_id = (int)($_POST['ticket_id'] ?? 0);
$message = trim($_POST['message'] ?? '');
if ($ticket_id <= 0 || $message === '') {
    error_response('Ticket y mensaje son obligatorios');
}

$db = Database::getInstance();
$pdo = $db->getConnection();

// Verificar que el ticket pertenece al cliente
$stmt = $pdo->prepare("SELECT id FROM support_tickets WHERE id = ? AND client_id = ? LIMIT 1");
$stmt->execute([$ticket_id, $client_id]);
if (!$stmt->fetch()) { error_response('Ticket no encontrado', 404); }

$stmtIns = $pdo->prepare("INSERT INTO support_ticket_messages (ticket_id, sender_type, message, created_at) VALUES (?, 'client', ?, NOW())");
$stmtIns->execute([$ticket_id, $message]);

echo json_encode(['success' => true]);
?>