<?php 
// Conexão com o banco de dados
// Nota: Autenticação já verificada em dashboard/index.php
require_once __DIR__ . '/../../config/config_db.php';

// Filtros opcionais
$filtro_status = isset($_GET['status']) ? $_GET['status'] : '';
$filtro_data_inicio = isset($_GET['data_inicio']) ? $_GET['data_inicio'] : '';
$filtro_data_fim = isset($_GET['data_fim']) ? $_GET['data_fim'] : '';
$busca = isset($_GET['busca']) ? $_GET['busca'] : '';

// Construir a consulta com filtros para carrinhos abandonados
$sql_carrinhos = "SELECT nome, sobrenome, email, telefone, descricao, status, created_at 
                  FROM transacoes 
                  WHERE (status IN ('pendente', 'reprovado') OR status IS NULL)";

$params = [];

if (!empty($filtro_status)) {
    $sql_carrinhos .= " AND status = :status";
    $params[':status'] = $filtro_status;
}

if (!empty($filtro_data_inicio)) {
    $sql_carrinhos .= " AND DATE(created_at) >= :data_inicio";
    $params[':data_inicio'] = $filtro_data_inicio;
}

if (!empty($filtro_data_fim)) {
    $sql_carrinhos .= " AND DATE(created_at) <= :data_fim";
    $params[':data_fim'] = $filtro_data_fim;
}

if (!empty($busca)) {
    $sql_carrinhos .= " AND (nome LIKE :busca OR sobrenome LIKE :busca OR email LIKE :busca OR descricao LIKE :busca)";
    $params[':busca'] = '%' . $busca . '%';
}

$sql_carrinhos .= " ORDER BY created_at DESC";

$stmt_carrinhos = $pdo->prepare($sql_carrinhos);
$stmt_carrinhos->execute($params);
$carrinhos = $stmt_carrinhos->fetchAll(PDO::FETCH_ASSOC);

// Estatísticas rápidas
$sql_stats = "SELECT 
    COUNT(*) as total_abandonados,
    SUM(CASE WHEN status = 'pendente' THEN 1 ELSE 0 END) as pendentes,
    SUM(CASE WHEN status = 'reprovado' THEN 1 ELSE 0 END) as reprovados,
    SUM(CASE WHEN status IS NULL THEN 1 ELSE 0 END) as sem_status
    FROM transacoes 
    WHERE (status IN ('pendente', 'reprovado') OR status IS NULL)";

$stmt_stats = $pdo->query($sql_stats);
$stats = $stmt_stats->fetch(PDO::FETCH_ASSOC);

// Função para formatar o telefone
function formatarTelefone($telefone) {
    return preg_replace('/[^0-9]/', '', $telefone);
}
?>

<!-- Página incluída no dashboard/index.php - não precisa de tags HTML completas -->
<style>
        /* TEMA PADRÃO (CLARO) */
        :root {
            --primary-color: #009846;
            --primary-light: #00A85A;
            --primary-dark: #007635;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --danger-color: #F44336;
            --info-color: #2196F3;
            --whatsapp-color: #25d366;
            --whatsapp-hover: #128c7e;
            
            --text-primary: #212121;
            --text-secondary: #757575;
            --text-muted: #9E9E9E;
            
            --bg-light: #f4f4f4;
            --bg-white: var(--bg-card, #FFFFFF);
            --bg-input: var(--bg-card, #FFFFFF);
            
            --border-color: var(--border-color, #E0E0E0);
            --shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.1);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.15);
            --border-radius: 8px;
            --transition: all 0.3s ease;
            --table-hover: rgba(0, 152, 70, 0.05);
        }

        /* TEMA ESCURO (DARK MODE) */
        /* Essas variáveis sobrescrevem as de cima quando a classe 'dark' está ativa */
        [data-theme="dark"] {
            --text-primary: #e0e0e0;
            --text-secondary: #9ca3af;
            --text-muted: #6b7280;
            
            --bg-light: var(--bg-body, #020617); /* Fundo Geral */
            --bg-white: var(--bg-card, #0f172a); /* Fundo Cards - Herda customização */
            --bg-input: var(--bg-card, #1e293b); /* Fundo Inputs */
            
            --border-color: var(--border-color, #334155);
            --shadow-sm: 0 4px 6px rgba(0, 0, 0, 0.3);
            --table-hover: rgba(255, 255, 255, 0.05);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Montserrat', sans-serif;
        }

        body {
            background-color: var(--bg-light);
            color: var(--text-primary);
            transition: var(--transition);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }

        .header-actions {
            display: flex;
            gap: 12px;
        }

        .download-btn {
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .download-btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .download-btn.excel-btn {
            background-color: #217346;
        }

        .download-btn.excel-btn:hover {
            background-color: #1a5a36;
        }

        .download-btn.csv-btn {
            background-color: #6c757d;
        }

        .download-btn.csv-btn:hover {
            background-color: #5a6268;
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: var(--text-primary);
        }

        /* Cards de estatísticas */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .stat-card {
            background-color: var(--bg-white);
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: var(--border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .stat-icon.total { background-color: rgba(244, 67, 54, 0.1); color: var(--danger-color); }
        .stat-icon.pendentes { background-color: rgba(255, 193, 7, 0.1); color: var(--warning-color); }
        .stat-icon.reprovados { background-color: rgba(244, 67, 54, 0.1); color: var(--danger-color); }
        .stat-icon.sem-status { background-color: rgba(158, 158, 158, 0.1); color: var(--text-muted); }

        .stat-info h3 {
            font-size: 24px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
        }

        .stat-info p {
            font-size: 14px;
            color: var(--text-secondary);
        }

        /* Filtros */
        .filters-container {
            background-color: var(--bg-white);
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--border-color);
            margin-bottom: 24px;
        }

        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            align-items: end;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-label {
            font-size: 14px;
            color: var(--text-secondary);
            font-weight: 500;
            margin-bottom: 8px;
        }

        .filter-input {
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            font-size: 14px;
            color: var(--text-primary);
            background-color: var(--bg-input); /* Adaptado para Dark Mode */
            transition: var(--transition);
        }

        .filter-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(0, 152, 70, 0.1);
        }
        
        /* Ajuste de ícone de calendário no Dark Mode */
        [data-theme="dark"] .filter-input[type="date"]::-webkit-calendar-picker-indicator {
            filter: invert(1);
        }

        .search-container {
            position: relative;
        }

        .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
        }

        .search-input {
            padding-left: 40px;
        }

        .filter-btn {
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
        }

        /* Tabela */
        .table-container {
            background-color: var(--bg-white);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow-sm);
            overflow: hidden;
            border: 1px solid var(--border-color);
        }

        .table-responsive {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        table th {
            background-color: rgba(0, 152, 70, 0.05);
            color: var(--text-secondary);
            font-weight: 500;
            text-align: left;
            padding: 16px;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid var(--border-color);
        }
        
        /* Ajuste Header Tabela Dark Mode */
        [data-theme="dark"] table th {
            background-color: rgba(255, 255, 255, 0.05);
        }

        table td {
            padding: 16px;
            vertical-align: middle;
            border-bottom: 1px solid var(--border-color);
            font-size: 14px;
            color: var(--text-primary);
        }

        table tbody tr:hover {
            background-color: var(--table-hover);
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        /* Cliente info */
        .client-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .client-name {
            font-weight: 500;
            color: var(--text-primary);
        }

        .client-email {
            font-size: 12px;
            color: var(--text-secondary);
        }

        /* WhatsApp button */
        .whatsapp-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            background-color: var(--whatsapp-color);
            color: white;
            border-radius: 50%;
            text-decoration: none;
            font-size: 18px;
            transition: var(--transition);
            box-shadow: var(--shadow-sm);
        }

        .whatsapp-btn:hover {
            background-color: var(--whatsapp-hover);
            transform: scale(1.1);
            box-shadow: var(--shadow-md);
        }

        /* Produto */
        .product-name {
            font-weight: 500;
            color: var(--text-primary);
        }

        /* Telefone */
        .phone-number {
            font-family: 'Courier New', monospace;
            font-size: 13px;
            color: var(--text-secondary);
        }

        /* Data */
        .data {
            font-size: 13px;
            color: var(--text-secondary);
            white-space: nowrap;
        }

        /* Estado vazio */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 48px;
            color: var(--text-muted);
            margin-bottom: 16px;
        }

        .empty-state h3 {
            font-size: 18px;
            margin-bottom: 8px;
            color: var(--text-primary);
        }

        .empty-state p {
            font-size: 14px;
            margin-bottom: 24px;
        }

        /* Responsivo */
        @media (max-width: 768px) {
            .container { padding: 15px; }
            .page-header { flex-direction: column; align-items: flex-start; gap: 16px; }
            .stats-grid { grid-template-columns: 1fr; }
            .filters-grid { grid-template-columns: 1fr; }
            .table-responsive { overflow-x: auto; }
            
            table, thead, tbody, th, td, tr { display: block; width: 100%; }
            thead tr { display: none; }
            
            tbody tr {
                margin-bottom: 16px;
                border: 1px solid var(--border-color);
                border-radius: var(--border-radius);
                padding: 16px;
                background-color: var(--bg-white);
                box-shadow: var(--shadow-sm);
            }
            
            td {
                display: flex; justify-content: space-between; align-items: center;
                padding: 8px 0; border-bottom: 1px solid var(--border-color);
            }
            td:last-child { border-bottom: none; }
            
            td::before {
                content: attr(data-label);
                font-weight: 500;
                color: var(--text-secondary);
                font-size: 12px;
                text-transform: uppercase;
            }
            
            .client-info, .product-name, .phone-number, .data, .whatsapp-btn {
                margin-left: auto; text-align: right;
            }
        }

        .pagination-info {
            text-align: center;
            padding: 16px;
            color: var(--text-secondary);
            font-size: 14px;
            background-color: var(--bg-light);
            border-top: 1px solid var(--border-color);
        }

        .tooltip { position: relative; }
        .tooltip .tooltip-text {
            visibility: hidden;
            width: max-content;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            text-align: center;
            border-radius: 4px;
            padding: 5px 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 12px;
            white-space: nowrap;
        }
        
        [data-theme="dark"] .tooltip .tooltip-text {
            background-color: rgba(255, 255, 255, 0.9); color: #000;
        }

        .tooltip:hover .tooltip-text { visibility: visible; opacity: 1; }
    </style>
</head>
<body>

<div class="container">
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-shopping-cart"></i> Carrinhos Abandonados
        </h1>
        <div class="header-actions">
            <?php if (count($carrinhos) > 0): ?>
            <a href="/dashboard/pages/exportar_carrinhos.php?<?= http_build_query($_GET); ?>&formato=csv" class="download-btn csv-btn" title="Baixar CSV">
                <i class="fas fa-file-csv"></i> CSV
            </a>
            <a href="/dashboard/pages/exportar_carrinhos.php?<?= http_build_query($_GET); ?>&formato=excel" class="download-btn excel-btn" title="Baixar Excel">
                <i class="fas fa-file-excel"></i> Excel
            </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon total"><i class="fas fa-cart-arrow-down"></i></div>
            <div class="stat-info">
                <h3><?= number_format($stats['total_abandonados']); ?></h3>
                <p>Total Abandonados</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon pendentes"><i class="fas fa-clock"></i></div>
            <div class="stat-info">
                <h3><?= number_format($stats['pendentes']); ?></h3>
                <p>Pagamento Pendente</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon reprovados"><i class="fas fa-times-circle"></i></div>
            <div class="stat-info">
                <h3><?= number_format($stats['reprovados']); ?></h3>
                <p>Pagamento Reprovado</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon sem-status"><i class="fas fa-question-circle"></i></div>
            <div class="stat-info">
                <h3><?= number_format($stats['sem_status']); ?></h3>
                <p>Sem Status</p>
            </div>
        </div>
    </div>

    <div class="filters-container">
        <form method="GET" action="index.php">
            <input type="hidden" name="page" value="carrinhos">
            <div class="filters-grid">
                <div class="filter-group">
                    <label class="filter-label"><i class="fas fa-search"></i> Buscar</label>
                    <div class="search-container">
                        <i class="fas fa-search search-icon"></i>
                        <input type="text" name="busca" class="filter-input search-input" placeholder="Nome, email ou produto..." value="<?= htmlspecialchars($busca); ?>">
                    </div>
                </div>
                <div class="filter-group">
                    <label class="filter-label"><i class="fas fa-flag"></i> Status</label>
                    <select name="status" class="filter-input">
                        <option value="">Todos os status</option>
                        <option value="pendente" <?= $filtro_status === 'pendente' ? 'selected' : ''; ?>>Pendente</option>
                        <option value="reprovado" <?= $filtro_status === 'reprovado' ? 'selected' : ''; ?>>Reprovado</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label"><i class="fas fa-calendar"></i> Data Início</label>
                    <input type="date" name="data_inicio" class="filter-input" value="<?= htmlspecialchars($filtro_data_inicio); ?>">
                </div>
                <div class="filter-group">
                    <label class="filter-label"><i class="fas fa-calendar"></i> Data Fim</label>
                    <input type="date" name="data_fim" class="filter-input" value="<?= htmlspecialchars($filtro_data_fim); ?>">
                </div>
                <div class="filter-group">
                    <button type="submit" class="filter-btn"><i class="fas fa-filter"></i> Filtrar</button>
                </div>
            </div>
        </form>
    </div>

    <div class="table-container">
        <?php if (count($carrinhos) > 0): ?>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Data</th>
                            <th>Cliente</th>
                            <th>Telefone</th>
                            <th>Produto</th>
                            <th>Contato WhatsApp</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($carrinhos as $carrinho): ?>
                        <tr>
                            <td data-label="Data"><span class="data"><?= $carrinho['created_at'] ? date('d/m/Y H:i', strtotime($carrinho['created_at'])) : 'N/A'; ?></span></td>
                            <td data-label="Cliente">
                                <div class="client-info">
                                    <span class="client-name"><?= htmlspecialchars($carrinho['nome'] . ' ' . $carrinho['sobrenome']); ?></span>
                                    <span class="client-email"><?= htmlspecialchars($carrinho['email']); ?></span>
                                </div>
                            </td>
                            <td data-label="Telefone"><span class="phone-number"><?= htmlspecialchars($carrinho['telefone']); ?></span></td>
                            <td data-label="Produto"><span class="product-name"><?= htmlspecialchars($carrinho['descricao']); ?></span></td>
                            <td data-label="WhatsApp">
                                <?php $telefone_formatado = formatarTelefone($carrinho['telefone']); ?>
                                <div class="tooltip">
                                    <a href="https://wa.me/<?= $telefone_formatado; ?>?text=Olá%20<?= urlencode($carrinho['nome']); ?>,%20vi%20que%20você%20tentou%20garantir%20seu%20<?= urlencode($carrinho['descricao']); ?>,%20tem%20alguma%20dúvida?" target="_blank" class="whatsapp-btn"><i class="fab fa-whatsapp"></i></a>
                                    <span class="tooltip-text">Enviar mensagem no WhatsApp</span>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="pagination-info">Exibindo <?= count($carrinhos); ?> carrinho(s) abandonado(s)</div>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-cart-arrow-down"></i>
                <h3>Nenhum carrinho abandonado encontrado</h3>
                <p>Ótimo! Não há carrinhos abandonados no momento.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    (function() {
        const html = document.documentElement;
        
        // 1. Verifica tema inicial
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark') {
            html.setAttribute('data-theme', 'dark');
        }

        // 2. Escuta o clique no botão do menu principal (index.php)
        // Como o index.php e este arquivo compartilham o mesmo 'document' quando carregados, 
        // podemos ouvir o evento no body.
        const mainThemeBtn = window.parent.document.getElementById('themeBtn') || document.getElementById('themeBtn');
        
        if(mainThemeBtn) {
            mainThemeBtn.addEventListener('click', function() {
                // Pequeno delay para dar tempo do localStorage atualizar
                setTimeout(() => {
                    const currentTheme = localStorage.getItem('theme');
                    if (currentTheme === 'dark') {
                        html.setAttribute('data-theme', 'dark');
                    } else {
                        html.removeAttribute('data-theme');
                    }
                }, 50);
            });
        }
    })();
</script>