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

$stmt = $pdo->prepare("SELECT id, subject, message, status, priority, created_at, updated_at FROM support_tickets WHERE client_id = ? ORDER BY created_at DESC");
$stmt->execute([$client_id]);
$tickets = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Soporte - PR Trader Room</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
    <!-- Botón de menú móvil -->
    <button class="mobile-menu-toggle" aria-label="Abrir menú" aria-controls="sidebar" aria-expanded="false">
        <i class="fas fa-bars"></i>
    </button>
    <div class="client-portal-layout">
        <!-- Sidebar (shared style) -->
        <?php include __DIR__ . '/sidebar.php'; ?>

        <!-- Main Content -->
        <div class="client-main-wrapper">
            <!-- Header -->
            <header class="client-header">
                <div class="client-header-content">
                    <div class="client-header-left">
                        <nav class="client-breadcrumb">
                            <span class="client-breadcrumb-item">
                        <a href="<?php echo module_url('client_portal/dashboard.php'); ?>">Dashboard</a>
                            </span>
                            <span class="client-breadcrumb-separator">›</span>
                            <span class="client-breadcrumb-item current">Soporte</span>
                        </nav>
                    </div>
                    <div class="client-header-right">
                        <div class="client-header-actions">
                            <button class="client-header-btn" onclick="document.getElementById('ticket-form').scrollIntoView()">
                                <i class="fas fa-plus"></i>
                                Nuevo Ticket
                            </button>
                        </div>
                        <div class="client-user-dropdown">
                            <div class="client-user-btn">
                                <div class="client-user-avatar">
                                    <?= strtoupper(substr($_SESSION['client_first_name'] ?? 'C', 0, 1)) ?>
                                </div>
                                <div class="client-user-info">
                                    <span class="client-user-name"><?= htmlspecialchars($_SESSION['client_first_name'] ?? 'Cliente') ?></span>
                                    <span class="client-user-status">Activo</span>
                                </div>
                                <i class="fas fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Main Content -->
            <main class="client-main-content">
                <!-- Create New Ticket Section -->
                <section class="support-section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <i class="fas fa-life-ring"></i>
                            Crear Nuevo Ticket
                        </h2>
                        <div class="section-actions">
                            <button class="client-action-btn secondary">
                                <i class="fas fa-question-circle"></i>
                                Ayuda
                            </button>
                        </div>
                    </div>
                    
                    <div class="support-card">
                        <form id="ticket-form" class="ticket-form" onsubmit="return false">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="ticket-subject">Asunto del Ticket</label>
                                    <input type="text" id="ticket-subject" placeholder="Describe brevemente tu consulta" required>
                                </div>
                                <div class="form-group">
                                    <label for="ticket-priority">Prioridad</label>
                                    <select id="ticket-priority">
                                        <option value="low">🟢 Baja</option>
                                        <option value="medium" selected>🟡 Media</option>
                                        <option value="high">🔴 Alta</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="ticket-message">Descripción Detallada</label>
                                <textarea id="ticket-message" placeholder="Describe tu solicitud o problema en detalle..." rows="5" required></textarea>
                            </div>
                            <div class="form-actions">
                                <button type="button" class="client-action-btn secondary">
                                    <i class="fas fa-times"></i>
                                    Cancelar
                                </button>
                                <button id="ticket-submit" class="client-action-btn primary">
                                    <i class="fas fa-paper-plane"></i>
                                    Enviar Ticket
                                </button>
                            </div>
                        </form>
                    </div>
                </section>

                <!-- Tickets History Section -->
                <section class="support-section">
                    <div class="section-header">
                        <h2 class="section-title">
                            <i class="fas fa-list"></i>
                            Historial de Tickets
                        </h2>
                        <div class="section-actions">
                            <button class="client-action-btn secondary">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="documents-table-container">
                        <table class="documents-table">
                            <thead>
                                <tr>
                                    <th><i class="fas fa-hashtag"></i> ID</th>
                                    <th><i class="fas fa-envelope"></i> Asunto</th>
                                    <th><i class="fas fa-flag"></i> Prioridad</th>
                                    <th><i class="fas fa-info-circle"></i> Estado</th>
                                    <th><i class="fas fa-calendar-plus"></i> Creado</th>
                                    <th><i class="fas fa-calendar-check"></i> Actualizado</th>
                                    <th><i class="fas fa-cog"></i> Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($tickets): foreach ($tickets as $t): ?>
                                    <tr>
                                        <td><span class="ticket-id">#<?= (int)$t['id'] ?></span></td>
                                        <td>
                        <a href="<?php echo module_url('client_portal/ticket.php'); ?>?id=<?= (int)$t['id'] ?>" class="ticket-subject-link">
                                                <?= htmlspecialchars($t['subject']) ?>
                                            </a>
                                        </td>
                                        <td>
                                            <?php
                                                $priority = $t['priority'];
                                                $priorityClass = $priority === 'high' ? 'high' : ($priority === 'medium' ? 'medium' : 'low');
                                                $priorityIcon = $priority === 'high' ? '🔴' : ($priority === 'medium' ? '🟡' : '🟢');
                                            ?>
                                            <span class="priority-badge <?= $priorityClass ?>">
                                                <?= $priorityIcon ?> <?= htmlspecialchars(ucfirst($priority)) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php
                                                $status = $t['status'];
                                                $statusClass = $status === 'closed' ? 'closed' : ($status === 'in_progress' ? 'in-progress' : 'open');
                                            ?>
                                            <span class="status-badge <?= $statusClass ?>">
                                                <?php if ($status === 'open'): ?><i class="fas fa-circle"></i> Abierto
                                                <?php elseif ($status === 'in_progress'): ?><i class="fas fa-clock"></i> En Progreso
                                                <?php else: ?><i class="fas fa-check-circle"></i> Cerrado<?php endif; ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars(date('d/m/Y', strtotime($t['created_at']))) ?></td>
                                        <td><?= htmlspecialchars(date('d/m/Y', strtotime($t['updated_at']))) ?></td>
                                        <td>
                                            <div class="action-buttons">
                        <a class="action-btn-small view" href="<?php echo module_url('client_portal/ticket.php'); ?>?id=<?= (int)$t['id'] ?>" title="Ver ticket">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <?php if ($status !== 'closed'): ?>
                                                <button class="action-btn-small edit" title="Responder">
                                                    <i class="fas fa-reply"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="7" style="text-align: center; padding: 2rem; color: var(--text-muted);">
                                            <i class="fas fa-life-ring" style="font-size: 2rem; margin-bottom: 1rem; display: block;"></i>
                                            No tienes tickets aún. 
                                            <button onclick="document.getElementById('ticket-form').scrollIntoView()" style="color: var(--primary-color); background: none; border: none; text-decoration: underline; cursor: pointer;">
                                                Crea tu primer ticket
                                            </button>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            </main>
        </div>
        <!-- Overlay para móvil -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
    </div>

    <script>
    document.getElementById('ticket-submit').addEventListener('click', async () => {
        const subject = document.getElementById('ticket-subject').value.trim();
        const message = document.getElementById('ticket-message').value.trim();
        const priority = document.getElementById('ticket-priority').value;
        
        if (!subject || !message) { 
            alert('Por favor completa el asunto y la descripción del ticket'); 
            return; 
        }
        
        // Disable button during submission
        const submitBtn = document.getElementById('ticket-submit');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enviando...';
        submitBtn.disabled = true;
        
        try {
            const res = await fetch('/modules/client_portal/create_ticket.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ subject, message, priority })
            });
            const data = await res.json();
            if (!data.success) throw new Error(data.error || 'Error creando ticket');
            
            alert('✅ Ticket creado exitosamente');
            location.reload();
        } catch (e) {
            alert('❌ ' + (e.message || 'Error creando ticket'));
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    });
    </script>

    <script src="<?php echo asset('public/script.js'); ?>"></script>
    <script src="https://kit.fontawesome.com/a2e0a6ad53.js" crossorigin="anonymous"></script>
</body>
</html>