<?php
// Desk - Listado de Tickets (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';

// Unificar helper de autenticación con el layout corporativo
if (!function_exists('isLoggedIn')) {
    function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
}
if (!isLoggedIn()) { header('Location: /index.php?module=auth&action=login'); exit; }

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

// Helper: verificar permisos por nombre
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;
}

// Filtros
$status = $_GET['status'] ?? '';
$priority = $_GET['priority'] ?? '';
$q = trim($_GET['q'] ?? '');
// Paginación
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$allowedStatus = ['open','pending','closed'];
$allowedPriority = ['low','medium','high'];

$where = [];
$params = [];
if (in_array($status, $allowedStatus, true)) { $where[] = 't.status = ?'; $params[] = $status; }
if (in_array($priority, $allowedPriority, true)) { $where[] = 't.priority = ?'; $params[] = $priority; }
if ($q !== '') { $where[] = '(t.subject LIKE ? OR c.email LIKE ? OR CONCAT(c.first_name, " ", c.last_name) LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; $params[] = "%$q%"; }

// Total para paginación
$countSql = "SELECT COUNT(*) FROM support_tickets t JOIN clients c ON c.id = t.client_id";
if ($where) { $countSql .= ' WHERE ' . implode(' AND ', $where); }
$stmtCount = $pdo->prepare($countSql);
$stmtCount->execute($params);
$total = (int)$stmtCount->fetchColumn();
$totalPages = (int)ceil($total / $perPage);

$sql = "SELECT t.id, t.subject, t.status, t.priority, t.created_at, t.updated_at,
               c.first_name, c.last_name, c.email
        FROM support_tickets t
        JOIN clients c ON c.id = t.client_id";
if ($where) { $sql .= ' WHERE ' . implode(' AND ', $where); }
$sql .= ' ORDER BY t.updated_at DESC LIMIT ? OFFSET ?';

$stmt = $pdo->prepare($sql);
$execParams = array_merge($params, [$perPage, $offset]);
$stmt->execute($execParams);
$tickets = $stmt->fetchAll();

// Integración con layout central
$page_title = 'Tickets de soporte';
$current_module = 'desks';
$current_action = 'tickets';

// Widgets de estadísticas globales
$openCount = $pendingCount = $closedCount = 0;
try {
    $statsStmt = $pdo->query("SELECT status, COUNT(*) AS cnt FROM support_tickets GROUP BY status");
    foreach ($statsStmt->fetchAll() as $row) {
        switch ($row['status']) {
            case 'open': $openCount = (int)$row['cnt']; break;
            case 'pending': $pendingCount = (int)$row['cnt']; break;
            case 'closed': $closedCount = (int)$row['cnt']; break;
        }
    }
} catch (Exception $e) { /* evitar romper vista si no existe tabla */ }
$totalCount = $openCount + $pendingCount + $closedCount;

ob_start();
?>
<style>
    .filters { display:flex; gap:12px; align-items:center; margin-bottom:16px; }
    .filters .form-control { padding:8px 10px; border:1px solid #e2e8f0; border-radius:8px; }
    .filters .btn { padding:8px 12px; border-radius:8px; }
    .tickets-table .status-open { color:#1e40af; }
    .tickets-table .status-pending { color:#ca8a04; }
    .tickets-table .status-closed { color:#16a34a; }
    .tickets-table .priority-low { color:#475569; }
    .tickets-table .priority-medium { color:#1e3a8a; }
    .tickets-table .priority-high { color:#dc2626; }
</style>

<div class="roles-header">
    <div class="header-left">
        <h1 class="page-title">
            <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="7" width="18" height="11" rx="2"/>
                <path d="M7 7V4h10v3"/>
            </svg>
            Gestión de Soporte
        </h1>
        <p class="page-subtitle">Gestiona tickets, prioridades y estados de atención.</p>
    </div>
</div>
<section class="stats-grid" style="margin-bottom:1rem;">
    <div class="stat-card" data-stat-key="open">
        <div class="stat-icon bg-blue-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M4 7h16v10H4z"/>
                <path d="M8 11h8M8 15h6"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?= number_format($openCount, 0, ',', '.') ?></div>
            <div class="stat-label">Abiertos</div>
        </div>
    </div>
    <div class="stat-card" data-stat-key="pending">
        <div class="stat-icon bg-yellow-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="9"/>
                <path d="M12 7v5l3 3"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?= number_format($pendingCount, 0, ',', '.') ?></div>
            <div class="stat-label">Pendientes</div>
        </div>
    </div>
    <div class="stat-card" data-stat-key="closed">
        <div class="stat-icon bg-green-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 12l2 2 4-4"/>
                <circle cx="12" cy="12" r="10"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?= number_format($closedCount, 0, ',', '.') ?></div>
            <div class="stat-label">Cerrados</div>
        </div>
    </div>
    <div class="stat-card" data-stat-key="total">
        <div class="stat-icon bg-teal-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M4 7h16v10H4z"/>
                <path d="M8 11h8M8 15h6"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number"><?= number_format($totalCount, 0, ',', '.') ?></div>
            <div class="stat-label">Total</div>
        </div>
    </div>
</section>
<section class="card">
    <div class="card-body">
        <form class="filters" method="get" action="">
            <input type="hidden" name="module" value="desks">
            <input type="hidden" name="action" value="tickets">
            <select name="status" class="form-control">
                <option value="">Estado</option>
                <option value="open" <?php echo $status==='open'?'selected':''; ?>>Abierto</option>
                <option value="pending" <?php echo $status==='pending'?'selected':''; ?>>Pendiente</option>
                <option value="closed" <?php echo $status==='closed'?'selected':''; ?>>Cerrado</option>
            </select>
            <select name="priority" class="form-control">
                <option value="">Prioridad</option>
                <option value="low" <?php echo $priority==='low'?'selected':''; ?>>Baja</option>
                <option value="medium" <?php echo $priority==='medium'?'selected':''; ?>>Media</option>
                <option value="high" <?php echo $priority==='high'?'selected':''; ?>>Alta</option>
            </select>
            <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Buscar por asunto, email o nombre" class="form-control" style="flex:1;" />
            <button type="submit" class="btn btn-primary">Filtrar</button>
            <a href="?module=desks&action=tickets" class="btn btn-secondary">Limpiar</a>
        </form>

        <table class="table tickets-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Asunto</th>
                    <th>Cliente</th>
                    <th>Estado</th>
                    <th>Prioridad</th>
                    <th>Actualizado</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($tickets): foreach ($tickets as $t): ?>
                    <tr>
                        <td><?php echo (int)$t['id']; ?></td>
                        <td><?php echo htmlspecialchars($t['subject']); ?></td>
                        <td><?php echo htmlspecialchars(($t['first_name'].' '.$t['last_name']).' ('.$t['email'].')'); ?></td>
                        <td><span class="status-<?php echo htmlspecialchars($t['status']); ?>"><?php echo htmlspecialchars($t['status']); ?></span></td>
                        <td><span class="priority-<?php echo htmlspecialchars($t['priority']); ?>"><?php echo htmlspecialchars($t['priority']); ?></span></td>
                        <td><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($t['updated_at']))); ?></td>
                        <td><a class="action-btn" href="?module=desks&action=ticket&id=<?php echo (int)$t['id']; ?>">Ver</a></td>
                    </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="7">No se encontraron tickets con los filtros actuales.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        <div class="pagination" style="margin-top:12px; display:flex; gap:8px; align-items:center;">
            <?php if ($totalPages > 1): ?>
                <?php $base = '?module=desks&action=tickets&status=' . urlencode($status) . '&priority=' . urlencode($priority) . '&q=' . urlencode($q); ?>
                <a class="btn btn-secondary" href="<?= $base . '&page=' . max(1, $page-1) ?>" <?= $page<=1?'style="pointer-events:none;opacity:0.6"':''; ?>>Anterior</a>
                <span>Página <?= (int)$page ?> de <?= (int)$totalPages ?></span>
                <a class="btn btn-secondary" href="<?= $base . '&page=' . min($totalPages, $page+1) ?>" <?= $page>=$totalPages?'style="pointer-events:none;opacity:0.6"':''; ?>>Siguiente</a>
            <?php endif; ?>
        </div>
    </div>
</section>
<?php
$content = ob_get_clean();
include BASE_PATH . '/modules/shared/layout.php';
return;