<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/notifications.php';
require_once __DIR__ . '/src/sync_checker.php';
require_login();

if (isset($_GET['send_alerts'])) {
    $notify_msg = send_expiry_notifications();
}

$pdo = get_db_connection();

// Buscar caminho configurado no banco ou usar o padrão
$stmtPath = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'nc_path'");
$stmtPath->execute();
$nc_path = $stmtPath->fetchColumn() ?: NC_CONTRACTS_PATH_DEFAULT;

// Orfãos do Nextcloud - Carregados via AJAX para não travar a página
$orphaned_count = 0; 

// Stats
$total_units = $pdo->query("SELECT COUNT(*) FROM units")->fetchColumn();
$total_contracts = $pdo->query("SELECT COUNT(*) FROM contracts")->fetchColumn();
$active_contracts = $pdo->query("SELECT COUNT(*) FROM contracts WHERE status = 'active'")->fetchColumn();
$renewing_contracts = $pdo->query("SELECT COUNT(*) FROM contracts WHERE status = 'renewing'")->fetchColumn();
$expired_contracts = $pdo->query("SELECT COUNT(*) FROM contracts WHERE end_date < CURDATE() AND status NOT IN ('completed', 'canceled')")->fetchColumn();
$expiring_soon = $pdo->query("SELECT COUNT(*) FROM contracts WHERE end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) AND status = 'active'")->fetchColumn();
$total_value = $pdo->query("SELECT SUM(value) FROM contracts WHERE status IN ('active', 'renewing')")->fetchColumn();

// Dados para o Gráfico (Últimos 6 meses)
$chart_data = $pdo->query("
    SELECT DATE_FORMAT(created_at, '%m/%Y') as month, COUNT(*) as total 
    FROM contracts 
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
    GROUP BY month 
    ORDER BY created_at ASC
")->fetchAll();

$months = [];
$counts = [];
foreach ($chart_data as $row) {
    $months[] = $row['month'];
    $counts[] = $row['total'];
}

// Alertas de Vencimento (Vencidos ou Próximos de vencer)
$alerts = $pdo->query("
    SELECT c.*, u.name as unit_name 
    FROM contracts c 
    JOIN units u ON c.unit_id = u.id 
    WHERE (
        c.end_date < CURDATE() -- Já vencidos
        OR c.alert_date <= CURDATE() -- Data de alerta atingida
        OR c.end_date <= DATE_ADD(CURDATE(), INTERVAL 15 DAY) -- Vencendo nos próximos 15 dias
    )
    AND c.status IN ('active', 'renewing')
    ORDER BY c.end_date ASC
    LIMIT 20
")->fetchAll();

require_once __DIR__ . '/templates/header.php';
?>

<style>
    .overflow-auto::-webkit-scrollbar {
        width: 6px;
    }
    .overflow-auto::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    .overflow-auto::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 10px;
    }
    .overflow-auto::-webkit-scrollbar-thumb:hover {
        background: #999;
    }
    .btn-xs {
        padding: 1px 5px;
        font-size: 0.75rem;
        line-height: 1.5;
        border-radius: 3px;
    }
</style>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Dashboard</h2>
        <div>
            <?php if (isset($notify_msg)): ?>
                <span class="badge bg-success me-2"><?= $notify_msg ?></span>
            <?php endif; ?>
            <button onclick="loadOrphansCount(true)" class="btn btn-outline-secondary btn-sm me-2">
                <i class="fas fa-sync-alt" id="dash-refresh-icon"></i> Atualizar Lista do Servidor
            </button>
            <a href="dashboard.php?send_alerts=1" class="btn btn-outline-primary btn-sm"><i class="fas fa-paper-plane me-1"></i> Disparar Alertas por E-mail</a>
        </div>
    </div>
    
    <div class="row">
        <!-- Container para alertas do Nextcloud carregados via AJAX -->
        <div id="nc-alerts-container" class="col-12 mb-4" style="display:none;">
            <div class="alert alert-info d-flex align-items-center shadow-sm border-0 bg-white" style="border-left: 5px solid #0dcaf0 !important;">
                <div class="rounded-circle bg-info bg-opacity-10 text-info d-flex align-items-center justify-content-center me-3" style="width: 50px; height: 50px;">
                    <i class="fas fa-cloud-upload-alt fa-lg"></i>
                </div>
                <div class="flex-grow-1">
                    <h6 class="alert-heading mb-1 fw-bold text-dark">Arquivos Pendentes no Nextcloud</h6>
                    <p class="mb-0 text-muted small">Detectamos <strong id="nc-orphans-count" class="text-info">0</strong> arquivo(s) PDF no Nextcloud sem vínculo ao sistema.</p>
                </div>
                <div>
                    <a href="sync_manager.php" class="btn btn-sm btn-info text-white fw-bold px-3 rounded-pill"><i class="fas fa-link me-1"></i> Vincular Agora</a>
                    <button onclick="loadOrphansCount(true)" class="btn btn-sm btn-light border ms-1 rounded-circle" title="Atualizar lista do servidor"><i class="fas fa-sync-alt" id="nc-refresh-icon"></i></button>
                </div>
            </div>
        </div>

        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-primary bg-opacity-10 text-primary d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-building"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">Unidades</h6>
                    <h3 class="card-text mb-0 fw-bold"><?= $total_units ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-success bg-opacity-10 text-success d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">Ativos</h6>
                    <h3 class="card-text mb-0 fw-bold"><?= $active_contracts ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-info bg-opacity-10 text-info d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-sync"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">Renovação</h6>
                    <h3 class="card-text mb-0 fw-bold"><?= $renewing_contracts ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-warning bg-opacity-10 text-warning d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-clock"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">A Vencer</h6>
                    <h3 class="card-text mb-0 fw-bold"><?= $expiring_soon ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-danger bg-opacity-10 text-danger d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-exclamation-circle"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">Vencidos</h6>
                    <h3 class="card-text mb-0 fw-bold text-danger"><?= $expired_contracts ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-3 text-center">
                    <div class="rounded-circle bg-dark bg-opacity-10 text-dark d-inline-flex align-items-center justify-content-center mb-2" style="width: 40px; height: 40px;">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <h6 class="card-title mb-1 text-muted small fw-bold">Valor Ativo</h6>
                    <h5 class="card-text mb-0 fw-bold">R$ <?= number_format($total_value ?: 0, 0, ',', '.') ?></h5>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8 mb-4">
            <div class="card">
                <div class="card-header">Contratos Criados por Mês</div>
                <div class="card-body">
                    <canvas id="contractsChart" height="100"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-4">
            <div class="card h-100 shadow-sm border-0 alert-card">
                <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center alert-card-header">
                    <h6 class="mb-0 fw-bold"><i class="fas fa-bell me-2 text-warning"></i> Alertas de Vencimento</h6>
                    <div class="d-flex gap-1">
                        <?php 
                        $vencidos_count = 0;
                        $a_vencer_count = 0;
                        foreach ($alerts as $a) {
                            if (strtotime($a['end_date']) < time()) $vencidos_count++;
                            else $a_vencer_count++;
                        }
                        ?>
                        <?php if ($vencidos_count > 0): ?>
                            <span class="badge bg-danger rounded-pill" title="Vencidos"><?= $vencidos_count ?></span>
                        <?php endif; ?>
                        <?php if ($a_vencer_count > 0): ?>
                            <span class="badge bg-warning text-dark rounded-pill" title="A Vencer"><?= $a_vencer_count ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="card-body p-0 overflow-auto" style="max-height: 450px;">
                    <?php if (!empty($alerts)): ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($alerts as $a): 
                                $is_vencido = strtotime($a['end_date']) < time();
                                $item_class = $is_vencido ? 'expired bg-danger bg-opacity-10' : 'warning bg-warning bg-opacity-10';
                                $icon = $is_vencido ? 'fa-calendar-times text-danger' : 'fa-calendar-day text-warning';
                                $badge_class = $is_vencido ? 'bg-danger' : 'bg-warning text-dark';
                                $days_diff = round((strtotime($a['end_date']) - time()) / (60 * 60 * 24));
                            ?>
                                <div class="list-group-item alert-item <?= $item_class ?> border-start border-4 py-3">
                                    <div class="d-flex justify-content-between align-items-start mb-1">
                                        <div class="alert-title text-truncate" style="max-width: 75%;" title="<?= htmlspecialchars($a['title']) ?>">
                                            <?= htmlspecialchars($a['title']) ?>
                                        </div>
                                        <span class="alert-badge <?= $badge_class ?>">
                                            <?= $is_vencido ? 'Vencido' : 'A Vencer' ?>
                                        </span>
                                    </div>
                                    <div class="alert-unit mb-2">
                                        <i class="fas fa-building me-1"></i> <?= htmlspecialchars($a['unit_name']) ?>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="alert-date <?= $is_vencido ? 'text-danger' : 'text-dark' ?>">
                                            <i class="fas <?= $icon ?> me-1"></i> <?= date('d/m/Y', strtotime($a['end_date'])) ?>
                                            <span class="ms-1 small fw-normal text-muted" style="font-size: 0.7rem;">
                                                (<?= $is_vencido ? abs($days_diff) . ' dias atrás' : 'em ' . $days_diff . ' dias' ?>)
                                            </span>
                                        </div>
                                        <a href="edit_contract.php?id=<?= $a['id'] ?>" class="btn btn-view-alert btn-outline-secondary">
                                            <i class="fas fa-external-link-alt me-1"></i> Ver
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="p-5 text-center">
                            <i class="fas fa-check-circle fa-4x text-success opacity-25 mb-3"></i>
                            <p class="text-muted fw-bold">Tudo em dia!</p>
                            <p class="text-muted small">Nenhum alerta crítico para os próximos dias.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>Últimos Contratos Cadastrados</span>
                    <a href="contracts.php" class="btn btn-sm btn-link text-decoration-none">Ver Todos</a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 small">
                            <thead>
                                <tr>
                                    <th>Título</th>
                                    <th>Tipo</th>
                                    <th>Fornecedor</th>
                                    <th>Unidade</th>
                                    <th>Status</th>
                                    <th>Vencimento</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $recent = $pdo->query("
                                    SELECT c.title, c.contract_type, c.supplier, c.status, c.end_date, u.name as unit_name 
                                    FROM contracts c 
                                    JOIN units u ON c.unit_id = u.id 
                                    ORDER BY c.created_at DESC 
                                    LIMIT 5
                                ")->fetchAll();
                                foreach ($recent as $r):
                                    $vencido = strtotime($r['end_date']) < time() && $r['status'] !== 'completed';
                                ?>
                                <tr>
                                    <td><?= htmlspecialchars($r['title']) ?></td>
                                    <td><?= htmlspecialchars($r['contract_type'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($r['supplier']) ?></td>
                                    <td><?= htmlspecialchars($r['unit_name']) ?></td>
                                    <td>
                                        <?php if ($vencido): ?>
                                            <span class="badge bg-danger">Vencido</span>
                                        <?php else: ?>
                                            <span class="badge bg-<?= $r['status'] === 'active' ? 'success' : ($r['status'] === 'renewing' ? 'info' : 'secondary') ?>"><?= ucfirst($r['status']) ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="<?= $vencido ? 'text-danger fw-bold' : '' ?>"><?= date('d/m/Y', strtotime($r['end_date'])) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('contractsChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode($months) ?>,
        datasets: [{
            label: 'Contratos Criados',
            data: <?= json_encode($counts) ?>,
            borderColor: '#0d6efd',
            tension: 0.1,
            fill: true,
            backgroundColor: 'rgba(13, 110, 253, 0.1)'
        }]
    },
    options: {
        scales: {
            y: { beginAtZero: true, ticks: { stepSize: 1 } }
        }
    }
});

function loadOrphansCount(refresh = false) {
    const container = document.getElementById('nc-alerts-container');
    const countSpan = document.getElementById('nc-orphans-count');
    const icon = document.getElementById('nc-refresh-icon');
    const dashRefreshIcon = document.getElementById('dash-refresh-icon');
    const requestUrl = 'ajax_orphans_count.php' + (refresh ? '?refresh=1&t=' + Date.now() : '?t=' + Date.now());
    
    if (refresh) {
        if (icon) icon.classList.add('fa-spin');
        if (dashRefreshIcon) dashRefreshIcon.classList.add('fa-spin');
    }

    fetch(requestUrl, { cache: 'no-store' })
        .then(response => response.json())
        .then(data => {
            if (data.debug) {
                console.log('Debug Nextcloud:', data.debug);
            }
            if (data.success) {
                if (data.count > 0) {
                    countSpan.textContent = data.count;
                    container.style.display = 'block';
                } else {
                    countSpan.textContent = '0';
                    container.style.display = 'block';
                }
                if (refresh) {
                    let msg = 'Lista do servidor atualizada com sucesso! Foram encontrados ' + data.count + ' arquivos pendentes.';
                    if (data.count === 0 && data.debug) {
                        const samples = Array.isArray(data.debug.remote_samples) && data.debug.remote_samples.length
                            ? data.debug.remote_samples.join('\n')
                            : 'Nenhum caminho remoto retornado.';
                        const roots = Array.isArray(data.debug.root_directories) && data.debug.root_directories.length
                            ? data.debug.root_directories.map(item => (item.relative_path || item.name || '')).join('\n')
                            : 'Nenhuma pasta raiz retornada.';
                        const contratoEntries = Array.isArray(data.debug.remote_root_entries) && data.debug.remote_root_entries.length
                            ? data.debug.remote_root_entries.map(item => (item.is_dir ? '[DIR] ' : '[ARQ] ') + (item.relative_path || item.name || '')).join('\n')
                            : 'Nenhuma entrada imediata retornada.';
                        const treeEntries = Array.isArray(data.debug.remote_tree_entries) && data.debug.remote_tree_entries.length
                            ? data.debug.remote_tree_entries.map(item => {
                                const type = item.is_dir ? '[DIR] ' : '[ARQ] ';
                                const ext = item.extension ? ' .' + item.extension : '';
                                return type + (item.relative_path || item.name || '') + ext;
                            }).join('\n')
                            : 'Nenhuma entrada recursiva retornada.';
                        const extCounts = data.debug.extension_counts && typeof data.debug.extension_counts === 'object' && Object.keys(data.debug.extension_counts).length
                            ? Object.entries(data.debug.extension_counts).map(([ext, count]) => ext + ': ' + count).join('\n')
                            : 'Nenhuma extensao contabilizada.';
                        const attempts = Array.isArray(data.debug.webdav_attempts) && data.debug.webdav_attempts.length
                            ? data.debug.webdav_attempts.map(item => {
                                return 'user=' + (item.webdav_user || 'N/D')
                                    + ' | path=' + (item.path || '/')
                                    + ' | depth=' + (item.depth || 'N/D')
                                    + ' | http=' + (item.http_code ?? 'N/D')
                                    + ' | entradas=' + (item.entry_count ?? 0);
                            }).join('\n')
                            : 'Nenhuma tentativa registrada.';
                        msg += '\nUsuario WebDAV: ' + (data.debug.webdav_user || 'N/D');
                        msg += '\n\nPasta remota: ' + (data.debug.remote_root || 'N/D');
                        msg += '\nArquivos remotos lidos: ' + (data.debug.remote_total ?? 0);
                        msg += '\nExemplos:\n' + samples;
                        msg += '\n\nExtensoes encontradas:\n' + extCounts;
                        msg += '\n\nTentativas WebDAV:\n' + attempts;
                        msg += '\n\nPastas na raiz do WebDAV:\n' + roots;
                        msg += '\n\nConteudo imediato de ' + (data.debug.remote_root || 'N/D') + ' (HTTP ' + (data.debug.remote_root_http_code ?? 'N/D') + '):\n' + contratoEntries;
                        msg += '\n\nArvore recursiva de ' + (data.debug.remote_root || 'N/D') + ':\n' + treeEntries;
                    }
                    alert(msg);
                }
            } else {
                if (refresh) alert('Erro ao atualizar lista: ' + (data.error || 'Erro desconhecido'));
            }
        })
        .catch(error => {
            console.error('Erro ao carregar arquivos pendentes:', error);
            if (refresh) alert('Erro ao atualizar lista do servidor: ' + error.message);
        })
        .finally(() => {
            if (refresh) {
                if (icon) icon.classList.remove('fa-spin');
                if (dashRefreshIcon) dashRefreshIcon.classList.remove('fa-spin');
            }
        });
}

// Carregar ao iniciar
document.addEventListener('DOMContentLoaded', () => loadOrphansCount(false));
</script>
</div>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
