<?php
// Desk - Detalle de Ticket (Staff)
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';

function isUserLoggedIn(){ return isset($_SESSION['user_id']); }
if (!isUserLoggedIn()) { header('Location: /modules/users/login.php'); exit; }

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

// Permisos: tickets.view para ver, tickets.reply para responder
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)) {
    http_response_code(403);
    echo '<h2 style="padding:20px;">Acceso restringido a Administrador</h2>';
    exit;
}
if (!userHasPermissionByName($pdo, 'tickets.view', $current_user_id)) {
    http_response_code(403);
    echo '<h2 style="padding:20px;">Permiso requerido: tickets.view</h2>';
    exit;
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo '<h2 style="padding:20px;">ID de ticket inválido</h2>';
    exit;
}

// Obtener ticket
$stmtT = $pdo->prepare("SELECT t.*, c.first_name, c.last_name, c.email FROM support_tickets t JOIN clients c ON c.id = t.client_id WHERE t.id = ? LIMIT 1");
$stmtT->execute([$id]);
$ticket = $stmtT->fetch();
if (!$ticket) { http_response_code(404); echo '<h2 style="padding:20px;">Ticket no encontrado</h2>'; exit; }

// Mensajes
$stmtM = $pdo->prepare("SELECT * FROM support_ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
$stmtM->execute([$id]);
$messages = $stmtM->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ticket #<?= (int)$ticket['id'] ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
    <link rel="stylesheet" href="/test/simple_crm/public/dashboard.css">
</head>
<body>
    <div class="dashboard-container">
        <header class="dashboard-header">
            <div class="breadcrumbs">
                <a href="/modules/dashboard/index.php" class="breadcrumb">Panel</a>
                <span class="breadcrumb-sep">›</span>
                <span class="breadcrumb current">Ticket #<?= (int)$ticket['id'] ?></span>
            </div>
            <h1>Ticket: <?= htmlspecialchars($ticket['subject']) ?></h1>
            <p>Cliente: <?= htmlspecialchars($ticket['first_name'].' '.$ticket['last_name']) ?> (<?= htmlspecialchars($ticket['email']) ?>)</p>
        </header>
        <main class="dashboard-main">
            <section class="documents-section">
                <div class="documents-table-container">
                    <h3>Conversación</h3>
                    <div class="ticket-thread">
                        <?php if ($messages): foreach ($messages as $m): ?>
                            <div class="ticket-message <?= $m['sender_type'] === 'agent' ? 'from-agent' : 'from-client' ?>">
                                <div class="ticket-meta">
                                    <span class="sender"><?= $m['sender_type'] === 'agent' ? 'Agente' : 'Cliente' ?></span>
                                    <span class="date"><?= htmlspecialchars(date('Y-m-d H:i', strtotime($m['created_at']))) ?></span>
                                </div>
                                <div class="ticket-body"><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                            </div>
                        <?php endforeach; else: ?>
                            <p>No hay mensajes todavía.</p>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="documents-table-container" style="margin-top:16px;">
                    <h3>Responder</h3>
                    <?php $canReply = userHasPermissionByName($pdo, 'tickets.reply', $current_user_id); ?>
                    <?php if ($canReply): ?>
                    <form id="replyForm">
                        <textarea name="message" id="message" rows="4" placeholder="Escribe tu respuesta..." required></textarea>
                        <button type="submit" class="action-btn">Enviar respuesta</button>
                    </form>
                    <?php else: ?>
                        <p>No tiene permiso para responder este ticket.</p>
                    <?php endif; ?>
                </div>
            </section>
        </main>
    </div>

    <script>
    const form = document.getElementById('replyForm');
    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const message = document.getElementById('message').value.trim();
            if (!message) return alert('Escribe un mensaje');
            try {
                const res = await fetch('/modules/desks/reply_ticket_message.php', {
                    method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({ ticket_id: '<?= (int)$ticket['id'] ?>', message })
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.error || 'Error al enviar respuesta');
                location.reload();
            } catch (err) {
                alert(err.message || 'Error');
            }
        });
    }
    </script>
</body>
</html>