<?php
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';
require_once BASE_PATH . '/modules/shared/helpers.php';

// Verificar si el cliente está logueado
if (!isset($_SESSION['client_id'])) {
    header('Location: ' . module_url('client_portal/login.php'));
    exit();
}

$client_id = $_SESSION['client_id'];

// Obtener conexión a la base de datos
$db = Database::getInstance();
$pdo = $db->getConnection();

$client_id = (int)$_SESSION['client_id'];
$ticket_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($ticket_id <= 0) { header('Location: ' . module_url('client_portal/tickets.php')); exit; }

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

$stmt = $pdo->prepare("SELECT id, subject, status, priority, created_at FROM support_tickets WHERE id = ? AND client_id = ? LIMIT 1");
$stmt->execute([$ticket_id, $client_id]);
$ticket = $stmt->fetch();
if (!$ticket) { header('Location: ' . module_url('client_portal/tickets.php')); exit; }

$stmtMsg = $pdo->prepare("SELECT sender_type, message, created_at FROM support_ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
$stmtMsg->execute([$ticket_id]);
$messages = $stmtMsg->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'] ?> - <?= htmlspecialchars($ticket['subject']) ?></title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
</head>
<body>
    <div class="dashboard-container">
        <header class="dashboard-header">
            <div class="breadcrumbs">
        <a href="<?php echo module_url('client_portal/dashboard.php'); ?>" class="breadcrumb">Inicio</a>
                <span class="breadcrumb-sep">›</span>
        <a href="<?php echo module_url('client_portal/tickets.php'); ?>" class="breadcrumb">Mis Tickets</a>
                <span class="breadcrumb-sep">›</span>
                <span class="breadcrumb current">Ticket #<?= (int)$ticket['id'] ?></span>
            </div>
            <h1>Ticket #<?= (int)$ticket['id'] ?></h1>
            <div>
                <span class="doc-badge <?= $ticket['status'] === 'closed' ? 'rejected' : 'pending' ?>">Estado: <?= htmlspecialchars(ucfirst($ticket['status'])) ?></span>
                <span class="doc-badge verified">Prioridad: <?= htmlspecialchars(ucfirst($ticket['priority'])) ?></span>
            </div>
        </header>

        <main class="dashboard-main">
            <section class="support-section">
                <div class="section-header">
                    <h2 class="section-title"><i class="fas fa-comments"></i> Conversación</h2>
                </div>
                <div style="background:#fff;border-radius:12px;padding:1rem;">
                    <?php if ($messages): foreach ($messages as $m): ?>
                        <div style="margin-bottom:0.75rem;">
                            <strong><?= $m['sender_type'] === 'agent' ? 'Soporte' : 'Tú' ?></strong>
                            <span style="color:#666;">— <?= htmlspecialchars(date('Y-m-d H:i', strtotime($m['created_at']))) ?></span>
                            <div><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                        </div>
                    <?php endforeach; else: ?>
                        <p>Aún no hay mensajes.</p>
                    <?php endif; ?>
                </div>
                <form id="msg-form" onsubmit="return false" style="margin-top:1rem;">
                    <textarea id="msg-text" rows="3" placeholder="Escribe tu mensaje" style="width:100%;padding:0.6rem;border:1px solid #ddd;border-radius:8px;"></textarea>
                    <button id="msg-send" class="action-btn primary" style="margin-top:0.5rem"><i class="fas fa-paper-plane"></i> Enviar</button>
                </form>
            </section>
        </main>
    </div>

    <script>
    document.getElementById('msg-send').addEventListener('click', async () => {
        const txt = document.getElementById('msg-text').value.trim();
        if (!txt) { alert('Escribe un mensaje'); return; }
        try {
            const res = await fetch('/modules/client_portal/add_ticket_message.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ ticket_id: '<?= (int)$ticket['id'] ?>', message: txt })
            });
            const data = await res.json();
            if (!data.success) throw new Error(data.error || 'Error enviando mensaje');
            location.reload();
        } catch (e) { alert(e.message || 'Error enviando mensaje'); }
    });
    </script>

    <script src="https://kit.fontawesome.com/a2e0a6ad53.js" crossorigin="anonymous"></script>
</body>
</html>