<?php
require_once 'config_numerado.php';

$pdo = getDBConnection();

// Filtros
$filtro_numero = $_GET['numero'] ?? '';
$filtro_acao = $_GET['acao'] ?? 'todas';
$limite = 50;

$where = [];
$params = [];

if (!empty($filtro_numero)) {
    $where[] = "numero = :numero";
    $params[':numero'] = $filtro_numero;
}

if ($filtro_acao !== 'todas') {
    $where[] = "acao = :acao";
    $params[':acao'] = $filtro_acao;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Buscar histórico
$stmt = $pdo->prepare("
    SELECT h.*, i.nome_convidado as nome_atual
    FROM historico_alteracoes h
    LEFT JOIN ingressos i ON h.ingresso_id = i.id
    $where_sql
    ORDER BY h.data_alteracao DESC
    LIMIT $limite
");
$stmt->execute($params);
$historico = $stmt->fetchAll();

// Estatísticas do histórico
$stats = $pdo->query("
    SELECT 
        COUNT(*) as total_alteracoes,
        SUM(CASE WHEN acao = 'atribuicao' THEN 1 ELSE 0 END) as atribuicoes,
        SUM(CASE WHEN acao = 'edicao' THEN 1 ELSE 0 END) as edicoes,
        SUM(CASE WHEN acao = 'limpeza' THEN 1 ELSE 0 END) as limpezas
    FROM historico_alteracoes
")->fetch();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Histórico de Alterações</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f6fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 24px;
        }
        
        .btn-header {
            padding: 10px 20px;
            background: rgba(255,255,255,0.2);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .btn-header:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .stat-card h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
        }
        
        .filters {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .filters-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 100px;
            gap: 15px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            margin-bottom: 5px;
            color: #666;
            font-size: 14px;
        }
        
        .form-group select,
        .form-group input {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .timeline {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .timeline-item {
            display: flex;
            padding: 20px 0;
            border-left: 3px solid #ddd;
            margin-left: 20px;
            position: relative;
        }
        
        .timeline-item:last-child {
            border-left-color: transparent;
        }
        
        .timeline-dot {
            position: absolute;
            left: -12px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: white;
            border: 3px solid #667eea;
        }
        
        .timeline-dot.atribuicao {
            border-color: #28a745;
        }
        
        .timeline-dot.edicao {
            border-color: #ffc107;
        }
        
        .timeline-dot.limpeza {
            border-color: #dc3545;
        }
        
        .timeline-content {
            flex: 1;
            padding-left: 30px;
        }
        
        .timeline-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .timeline-numero {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .timeline-data {
            color: #999;
            font-size: 13px;
        }
        
        .timeline-acao {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .acao-atribuicao {
            background: #d4edda;
            color: #155724;
        }
        
        .acao-edicao {
            background: #fff3cd;
            color: #856404;
        }
        
        .acao-limpeza {
            background: #f8d7da;
            color: #721c24;
        }
        
        .timeline-mudanca {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .nome-anterior {
            color: #dc3545;
            text-decoration: line-through;
        }
        
        .nome-novo {
            color: #28a745;
            font-weight: 600;
        }
        
        .no-records {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .no-records-icon {
            font-size: 60px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>📜 Histórico de Alterações</h1>
            <a href="admin.php" class="btn-header">← Voltar ao Painel</a>
        </div>
    </div>
    
    <div class="container">
        <!-- Estatísticas -->
        <div class="stats">
            <div class="stat-card">
                <h3>Total de Alterações</h3>
                <div class="number"><?= $stats['total_alteracoes'] ?></div>
            </div>
            <div class="stat-card">
                <h3>Atribuições</h3>
                <div class="number" style="color: #28a745;"><?= $stats['atribuicoes'] ?></div>
            </div>
            <div class="stat-card">
                <h3>Edições</h3>
                <div class="number" style="color: #ffc107;"><?= $stats['edicoes'] ?></div>
            </div>
            <div class="stat-card">
                <h3>Limpezas</h3>
                <div class="number" style="color: #dc3545;"><?= $stats['limpezas'] ?></div>
            </div>
        </div>
        
        <!-- Filtros -->
        <div class="filters">
            <form method="GET" class="filters-grid">
                <div class="form-group">
                    <label>Número do Ingresso</label>
                    <input type="number" name="numero" placeholder="Ex: 1, 2, 3..." value="<?= htmlspecialchars($filtro_numero) ?>" min="1" max="<?= TOTAL_INGRESSOS ?>">
                </div>
                
                <div class="form-group">
                    <label>Tipo de Ação</label>
                    <select name="acao">
                        <option value="todas" <?= $filtro_acao === 'todas' ? 'selected' : '' ?>>Todas</option>
                        <option value="atribuicao" <?= $filtro_acao === 'atribuicao' ? 'selected' : '' ?>>Atribuições</option>
                        <option value="edicao" <?= $filtro_acao === 'edicao' ? 'selected' : '' ?>>Edições</option>
                        <option value="limpeza" <?= $filtro_acao === 'limpeza' ? 'selected' : '' ?>>Limpezas</option>
                    </select>
                </div>
                
                <button type="submit" class="btn btn-primary">Filtrar</button>
            </form>
        </div>
        
        <!-- Timeline -->
        <div class="timeline">
            <?php if (empty($historico)): ?>
                <div class="no-records">
                    <div class="no-records-icon">📋</div>
                    <p>Nenhuma alteração encontrada</p>
                </div>
            <?php else: ?>
                <?php foreach ($historico as $item): ?>
                <div class="timeline-item">
                    <div class="timeline-dot <?= $item['acao'] ?>"></div>
                    <div class="timeline-content">
                        <div class="timeline-header">
                            <div>
                                <span class="timeline-numero">#<?= formatarNumero($item['numero']) ?></span>
                                <span class="timeline-acao acao-<?= $item['acao'] ?>">
                                    <?php
                                    echo match($item['acao']) {
                                        'atribuicao' => '➕ Nova Atribuição',
                                        'edicao' => '✏️ Edição',
                                        'limpeza' => '🗑️ Limpeza',
                                        default => $item['acao']
                                    };
                                    ?>
                                </span>
                            </div>
                            <div class="timeline-data">
                                <?= date('d/m/Y H:i', strtotime($item['data_alteracao'])) ?>
                            </div>
                        </div>
                        
                        <div class="timeline-mudanca">
                            <?php if ($item['acao'] === 'atribuicao'): ?>
                                <strong>Ingresso atribuído para:</strong><br>
                                <span class="nome-novo"><?= htmlspecialchars($item['nome_novo']) ?></span>
                            
                            <?php elseif ($item['acao'] === 'edicao'): ?>
                                <strong>Nome alterado:</strong><br>
                                <span class="nome-anterior"><?= htmlspecialchars($item['nome_anterior']) ?></span>
                                →
                                <span class="nome-novo"><?= htmlspecialchars($item['nome_novo']) ?></span>
                            
                            <?php elseif ($item['acao'] === 'limpeza'): ?>
                                <strong>Ingresso liberado:</strong><br>
                                <span class="nome-anterior"><?= htmlspecialchars($item['nome_anterior']) ?></span>
                                foi removido
                            <?php endif; ?>
                            
                            <?php if (!empty($item['nome_atual'])): ?>
                            <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #ddd; color: #666; font-size: 12px;">
                                <strong>Nome atual:</strong> <?= htmlspecialchars($item['nome_atual']) ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <?php if (count($historico) >= $limite): ?>
        <div style="text-align: center; margin-top: 20px; color: #666;">
            <p>Mostrando as últimas <?= $limite ?> alterações</p>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
