<?php
// Endpoint staff: responder mensaje en ticket de soporte
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['user_id'])) { error_response('No autenticado', 401); }

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

// Verificación de permiso: tickets.reply
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName(PDO $pdo, string $permName, int $userId): bool {
        if ($userId <= 0) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
// Bloqueo: solo Administrador puede acceder por URL
if (!function_exists('isAdminRole')) {
    function isAdminRole(PDO $pdo, int $userId): bool {
        if ($userId <= 0) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM user_roles ur INNER JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ? AND r.name = 'admin' LIMIT 1");
        $stmt->execute([$userId]);
        return (bool)$stmt->fetchColumn();
    }
}
if (!isAdminRole($pdo, $current_user_id)) {
    error_response('Acceso restringido a Administrador', 403);
}
if (!userHasPermissionByName($pdo, 'tickets.reply', $current_user_id)) {
    error_response('Permiso requerido: tickets.reply', 403);
}

// Validar existencia del ticket
$stmt = $pdo->prepare("SELECT id FROM support_tickets WHERE id = ? LIMIT 1");
$stmt->execute([$ticket_id]);
if (!$stmt->fetch()) { error_response('Ticket no encontrado', 404); }

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

// Actualizar updated_at del ticket
$pdo->prepare("UPDATE support_tickets SET updated_at = NOW() WHERE id = ?")->execute([$ticket_id]);

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