<?php
// frota.php — Módulo de Gestão de Frota
$pageActive = 'frota';
$pageTitle  = 'Gestão de Frota';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$usuario = usuarioLogado();
$isAdmin = $usuario['perfil'] === 'ADMIN';

// Buscar veículos
if ($isAdmin) {
    $stmt = pdo()->query("
        SELECT v.*, u.nome AS responsavel_nome 
        FROM frota_veiculos v 
        LEFT JOIN usuarios u ON v.responsavel_id = u.id 
        WHERE v.ativo = 1 
        ORDER BY v.placa ASC
    ");
} else {
    $stmt = pdo()->prepare("
        SELECT v.*, u.nome AS responsavel_nome 
        FROM frota_veiculos v 
        LEFT JOIN usuarios u ON v.responsavel_id = u.id 
        WHERE v.responsavel_id = ? AND v.ativo = 1 
        ORDER BY v.placa ASC
    ");
    $stmt->execute([$usuario['id']]);
}
$veiculos = $stmt->fetchAll();

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

<style>
.frota-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 16px;
    padding: 4px 0;
}

.frota-card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 18px;
    transition: all .15s;
    position: relative;
}

.frota-card:hover {
    border-color: var(--cyan);
}

.frota-card-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 14px;
}

.frota-card-placa {
    font-size: 18px;
    font-weight: 800;
    color: var(--cyan);
    font-family: var(--mono);
    letter-spacing: 2px;
}

.frota-card-modelo {
    font-size: 13px;
    color: var(--text);
    font-weight: 600;
    margin-top: 2px;
}

.frota-card-info {
    font-size: 11px;
    color: var(--muted);
    font-family: var(--mono);
    margin-bottom: 14px;
    line-height: 1.6;
}

.frota-card-stats {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 8px;
    margin-bottom: 14px;
}

.frota-stat {
    text-align: center;
    padding: 10px 6px;
    background: var(--card2);
    border-radius: 8px;
    border: 1px solid var(--border);
}

.frota-stat-valor {
    font-size: 16px;
    font-weight: 800;
    font-family: var(--mono);
}

.frota-stat-label {
    font-size: 8px;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .5px;
    margin-top: 3px;
}

.frota-card-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
}

.frota-card-actions a,
.frota-card-actions button {
    padding: 8px 10px;
    border-radius: 6px;
    font-size: 10px;
    font-weight: 700;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    border: 1px solid var(--border);
    background: var(--card2);
    color: var(--text);
    transition: all .15s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    font-family: var(--ui);
}

.frota-card-actions a:hover,
.frota-card-actions button:hover {
    background: var(--cyan);
    color: #000;
    border-color: var(--cyan);
}

.frota-status-badge {
    font-size: 8px;
    font-weight: 700;
    padding: 4px 10px;
    border-radius: 12px;
    text-transform: uppercase;
    letter-spacing: .5px;
    flex-shrink: 0;
}

.frota-status-ok {
    background: rgba(16,185,129,.12);
    color: var(--green);
    border: 1px solid rgba(16,185,129,.25);
}

.frota-status-atencao {
    background: rgba(245,158,11,.12);
    color: var(--amber);
    border: 1px solid rgba(245,158,11,.25);
}

.btn-add-veiculo {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 10px 20px;
    background: var(--cyan);
    color: #000;
    border: none;
    border-radius: var(--radius);
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    transition: all .15s;
    text-decoration: none;
    font-family: var(--ui);
    margin-bottom: 18px;
}

.btn-add-veiculo:hover {
    opacity: .85;
    box-shadow: var(--glow);
}

.empty-state {
    text-align: center;
    padding: 50px 20px;
    color: var(--muted);
}

.empty-state-icon {
    font-size: 56px;
    margin-bottom: 14px;
}

.empty-state-text {
    font-size: 14px;
    margin-bottom: 18px;
}

/* Modal */
.modal-overlay .form-group {
    margin-bottom: 14px;
}

.modal-overlay .form-label {
    display: block;
    font-size: 10px;
    font-weight: 600;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: .5px;
    margin-bottom: 5px;
}

.modal-overlay .form-input,
.modal-overlay .form-select,
.modal-overlay .form-textarea {
    width: 100%;
    padding: 8px 12px;
    background: var(--card2);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text);
    font-family: var(--ui);
    font-size: 13px;
}

.modal-overlay .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}

@media (max-width: 767px) {
    .frota-grid {
        grid-template-columns: 1fr;
    }
    .frota-card-stats {
        grid-template-columns: 1fr 1fr 1fr;
    }
}
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
    <div>
        <div class="page-title">🚛 Gestão de Frota</div>
        <div class="page-sub"><?= $isAdmin ? 'Todos os veículos' : 'Meu veículo' ?></div>
    </div>
    <div class="topbar-actions">
        <button class="btn btn-ghost btn-sm" onclick="location.reload()">⟳ Atualizar</button>
    </div>
</div>

<div class="content">
    <?php if ($isAdmin): ?>
    <a href="frota_veiculo_form.php" class="btn-add-veiculo">+ Adicionar Veículo</a>
    <?php endif; ?>

    <?php if (empty($veiculos)): ?>
    <div class="empty-state">
        <div class="empty-state-icon">🚛</div>
        <div class="empty-state-text">
            <?= $isAdmin ? 'Nenhum veículo cadastrado ainda.' : 'Nenhum veículo vinculado ao seu usuário.' ?>
        </div>
        <?php if ($isAdmin): ?>
        <a href="frota_veiculo_form.php" class="btn btn-primary">Adicionar Veículo</a>
        <?php endif; ?>
    </div>
    <?php else: ?>

    <div class="frota-grid">
        <?php foreach ($veiculos as $v): 
            $kmAtual = (int)($v['km_atual'] ?? 0);
            
            // Último abastecimento
            $stmtAb = pdo()->prepare("SELECT km_atual, litros, valor_total, data FROM frota_abastecimentos WHERE veiculo_id = ? ORDER BY data DESC, id DESC LIMIT 1");
            $stmtAb->execute([$v['id']]);
            $ultimoAb = $stmtAb->fetch();
            
            // Última troca de óleo
            $stmtOl = pdo()->prepare("SELECT km_atual, data, proxima_km FROM frota_manutencoes WHERE veiculo_id = ? AND tipo = 'TROCA_OLEO' ORDER BY data DESC LIMIT 1");
            $stmtOl->execute([$v['id']]);
            $ultimaTroca = $stmtOl->fetch();
            
            // Totais do mês
            $stmtTot = pdo()->prepare("SELECT COUNT(*) AS qtd, COALESCE(SUM(litros),0) AS total_litros, COALESCE(SUM(valor_total),0) AS total_valor FROM frota_abastecimentos WHERE veiculo_id = ? AND MONTH(data) = MONTH(CURDATE()) AND YEAR(data) = YEAR(CURDATE())");
            $stmtTot->execute([$v['id']]);
            $totais = $stmtTot->fetch();
            
            // Alertas
            $alertaOleo = false;
            if ($ultimaTroca && $ultimaTroca['proxima_km'] && $kmAtual >= ($ultimaTroca['proxima_km'] - 500)) {
                $alertaOleo = true;
            }
            
            // KM restante para troca
            $kmRestante = $ultimaTroca && $ultimaTroca['proxima_km'] ? $ultimaTroca['proxima_km'] - $kmAtual : null;
        ?>
        <div class="frota-card">
            <div class="frota-card-header">
                <div>
                    <div class="frota-card-placa"><?= e($v['placa']) ?></div>
                    <div class="frota-card-modelo"><?= e($v['modelo'] ?: 'Modelo não informado') ?></div>
                </div>
                <span class="frota-status-badge <?= $alertaOleo ? 'frota-status-atencao' : 'frota-status-ok' ?>">
                    <?= $alertaOleo ? '⚠ Óleo' : '✓ OK' ?>
                </span>
            </div>
            
            <div class="frota-card-info">
                👤 <b><?= e($v['responsavel_nome'] ?: 'Não definido') ?></b>
                <?php if ($v['ano']): ?> | 📅 <?= e($v['ano']) ?><?php endif; ?>
            </div>
            
            <div class="frota-card-stats">
                <div class="frota-stat">
                    <div class="frota-stat-valor" style="color:var(--cyan)"><?= number_format($kmAtual, 0, ',', '.') ?></div>
                    <div class="frota-stat-label">KM Atual</div>
                </div>
                <div class="frota-stat">
                    <div class="frota-stat-valor" style="color:var(--green)"><?= number_format((float)$totais['total_litros'], 1, ',', '.') ?>L</div>
                    <div class="frota-stat-label">Litros/Mês</div>
                </div>
                <div class="frota-stat">
                    <div class="frota-stat-valor" style="color:var(--amber)">R$ <?= number_format((float)$totais['total_valor'], 0, ',', '.') ?></div>
                    <div class="frota-stat-label">Gasto/Mês</div>
                </div>
            </div>
            
            <?php if ($ultimaTroca): ?>
            <div class="frota-card-info" style="margin-bottom:12px;padding:8px;background:<?= $alertaOleo ? 'rgba(245,158,11,.08)' : 'rgba(16,185,129,.06)' ?>;border-radius:6px;border:1px solid <?= $alertaOleo ? 'rgba(245,158,11,.2)' : 'rgba(16,185,129,.15)' ?>">
                🛢 Óleo: <b><?= number_format((int)$ultimaTroca['km_atual'], 0, ',', '.') ?> km</b> 
                (<?= date('d/m/Y', strtotime($ultimaTroca['data'])) ?>)
                <?php if ($kmRestante !== null): ?>
                <br>⏭ <?= $kmRestante > 0 ? "Faltam <b style='color:".($alertaOleo?'var(--amber)':'var(--green)')."'>".number_format($kmRestante, 0, ',', '.')." km</b>" : "<b style='color:var(--red)'>Vencido!</b>" ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <div class="frota-card-actions">
                <button type="button" onclick="abrirModalAbastecimento(<?= $v['id'] ?>, '<?= e($v['placa']) ?>', <?= $kmAtual ?>)">
                    ⛽ Abastecer
                </button>
                <button type="button" onclick="abrirModalManutencao(<?= $v['id'] ?>, '<?= e($v['placa']) ?>', <?= $kmAtual ?>)">
                    🔧 Manutenção
                </button>
                <a href="frota_relatorio.php?veiculo_id=<?= $v['id'] ?>">
                    📊 Relatório
                </a>
                <?php if ($isAdmin): ?>
                <a href="frota_veiculo_form.php?id=<?= $v['id'] ?>">
                    ✎ Editar
                </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════ MODAL ABASTECIMENTO ═══════ -->
<div class="modal-overlay" id="modal-abastecimento">
    <div class="modal">
        <div class="modal-header">
            <span class="modal-title">⛽ Registrar Abastecimento</span>
            <button class="modal-close" onclick="fecharModal('modal-abastecimento')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="form-abastecimento" onsubmit="salvarAbastecimento(event)" enctype="multipart/form-data">
                <input type="hidden" name="veiculo_id" id="ab-veiculo-id"/>
                
                <div class="form-group">
                    <label class="form-label">VEÍCULO</label>
                    <input class="form-input" type="text" id="ab-placa" readonly style="font-weight:700;color:var(--cyan)"/>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">DATA *</label>
                        <input class="form-input" type="date" name="data" id="ab-data" value="<?= date('Y-m-d') ?>" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label">HORA</label>
                        <input class="form-input" type="time" name="hora" id="ab-hora" value="<?= date('H:i') ?>"/>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">KM ATUAL *</label>
                    <input class="form-input" type="number" name="km_atual" id="ab-km" required placeholder="Ex: 85000" min="0" style="font-family:var(--mono);font-size:16px;font-weight:700"/>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">LITROS *</label>
                        <input class="form-input" type="number" name="litros" id="ab-litros" step="0.01" required placeholder="Ex: 45.5"/>
                    </div>
                    <div class="form-group">
                        <label class="form-label">VALOR TOTAL (R$) *</label>
                        <input class="form-input" type="number" name="valor_total" id="ab-valor" step="0.01" required placeholder="Ex: 250.00"/>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">FOTO DO HODÔMETRO (opcional)</label>
                    <input class="form-input" type="file" name="foto" id="ab-foto" accept="image/*" capture="environment" style="padding:8px"/>
                    <span style="font-size:9px;color:var(--muted)">JPG, PNG ou WEBP - Máx. 5MB</span>
                </div>
                
                <div class="form-group">
                    <label class="form-label">OBSERVAÇÕES</label>
                    <textarea class="form-textarea" name="observacoes" rows="2" placeholder="Ex: Posto Shell, etanol comum..."></textarea>
                </div>
                
                <button type="submit" class="btn btn-primary" style="width:100%;margin-top:8px;padding:12px">
                    💾 Salvar Abastecimento
                </button>
            </form>
        </div>
    </div>
</div>

<!-- ═══════ MODAL MANUTENÇÃO ═══════ -->
<div class="modal-overlay" id="modal-manutencao">
    <div class="modal">
        <div class="modal-header">
            <span class="modal-title">🔧 Registrar Manutenção</span>
            <button class="modal-close" onclick="fecharModal('modal-manutencao')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="form-manutencao" onsubmit="salvarManutencao(event)" enctype="multipart/form-data">
                <input type="hidden" name="veiculo_id" id="man-veiculo-id"/>
                
                <div class="form-group">
                    <label class="form-label">VEÍCULO</label>
                    <input class="form-input" type="text" id="man-placa" readonly style="font-weight:700;color:var(--cyan)"/>
                </div>
                
                <div class="form-group">
                    <label class="form-label">TIPO DE MANUTENÇÃO *</label>
                    <select class="form-select" name="tipo" required>
                        <option value="">Selecione o tipo...</option>
                        <option value="TROCA_OLEO">🛢 Troca de Óleo</option>
                        <option value="FILTRO">🔍 Filtro (Ar/Combustível/Óleo)</option>
                        <option value="PNEU">🛞 Pneu</option>
                        <option value="REVISAO">🔩 Revisão Geral</option>
                        <option value="OUTRO">🔧 Outro</option>
                    </select>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">DATA *</label>
                        <input class="form-input" type="date" name="data" id="man-data" value="<?= date('Y-m-d') ?>" required/>
                    </div>
                    <div class="form-group">
                        <label class="form-label">KM ATUAL</label>
                        <input class="form-input" type="number" name="km_atual" id="man-km" min="0" style="font-family:var(--mono);font-size:16px;font-weight:700"/>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">PRÓXIMA TROCA (KM)</label>
                        <input class="form-input" type="number" name="proxima_km" placeholder="Ex: 90000" min="0"/>
                    </div>
                    <div class="form-group">
                        <label class="form-label">PRÓXIMA DATA</label>
                        <input class="form-input" type="date" name="proxima_data"/>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">DESCRIÇÃO</label>
                    <textarea class="form-textarea" name="descricao" rows="3" placeholder="Detalhes do serviço realizado, peças trocadas, valor..."></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">FOTO/COMPROVANTE (opcional)</label>
                    <input class="form-input" type="file" name="foto" accept="image/*" capture="environment" style="padding:8px"/>
                    <span style="font-size:9px;color:var(--muted)">JPG, PNG ou WEBP - Máx. 5MB</span>
                </div>
                
                <button type="submit" class="btn btn-primary" style="width:100%;margin-top:8px;padding:12px">
                    💾 Salvar Manutenção
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// ═══════════ ABRIR MODAL ABASTECIMENTO ═══════════
function abrirModalAbastecimento(veiculoId, placa, kmAtual) {
    document.getElementById('ab-veiculo-id').value = veiculoId;
    document.getElementById('ab-placa').value = placa;
    document.getElementById('ab-km').value = kmAtual || '';
    document.getElementById('ab-data').value = '<?= date('Y-m-d') ?>';
    document.getElementById('ab-hora').value = '<?= date('H:i') ?>';
    document.getElementById('ab-litros').value = '';
    document.getElementById('ab-valor').value = '';
    document.getElementById('ab-foto').value = '';
    document.querySelector('#form-abastecimento textarea').value = '';
    abrirModal('modal-abastecimento');
}

// ═══════════ ABRIR MODAL MANUTENÇÃO ═══════════
function abrirModalManutencao(veiculoId, placa, kmAtual) {
    document.getElementById('man-veiculo-id').value = veiculoId;
    document.getElementById('man-placa').value = placa;
    document.getElementById('man-km').value = kmAtual || '';
    document.getElementById('man-data').value = '<?= date('Y-m-d') ?>';
    document.querySelector('#form-manutencao select[name="tipo"]').value = '';
    document.querySelector('#form-manutencao textarea').value = '';
    abrirModal('modal-manutencao');
}

// ═══════════ SALVAR ABASTECIMENTO ═══════════
async function salvarAbastecimento(e) {
    e.preventDefault();
    const form = document.getElementById('form-abastecimento');
    const formData = new FormData(form);
    formData.append('acao', 'abastecimento');
    
    const btn = form.querySelector('button[type="submit"]');
    const txtOriginal = btn.textContent;
    btn.disabled = true;
    btn.textContent = '⟳ Salvando...';
    
    try {
        const resp = await fetch('ajax/frota_salvar.php', {
            method: 'POST',
            body: formData
        });
        const data = await resp.json();
        
        if (data.ok) {
            mostrarToast('✅ Abastecimento registrado!', 'success');
            fecharModal('modal-abastecimento');
            setTimeout(() => location.reload(), 1000);
        } else {
            mostrarToast('❌ ' + (data.erro || 'Erro ao salvar'), 'error');
        }
    } catch(err) {
        mostrarToast('❌ Erro de conexão: ' + err.message, 'error');
    }
    
    btn.disabled = false;
    btn.textContent = txtOriginal;
}

// ═══════════ SALVAR MANUTENÇÃO ═══════════
async function salvarManutencao(e) {
    e.preventDefault();
    const form = document.getElementById('form-manutencao');
    const formData = new FormData(form);
    formData.append('acao', 'manutencao');
    
    const btn = form.querySelector('button[type="submit"]');
    const txtOriginal = btn.textContent;
    btn.disabled = true;
    btn.textContent = '⟳ Salvando...';
    
    try {
        const resp = await fetch('ajax/frota_salvar.php', {
            method: 'POST',
            body: formData
        });
        const data = await resp.json();
        
        if (data.ok) {
            mostrarToast('✅ Manutenção registrada!', 'success');
            fecharModal('modal-manutencao');
            setTimeout(() => location.reload(), 1000);
        } else {
            mostrarToast('❌ ' + (data.erro || 'Erro ao salvar'), 'error');
        }
    } catch(err) {
        mostrarToast('❌ Erro de conexão: ' + err.message, 'error');
    }
    
    btn.disabled = false;
    btn.textContent = txtOriginal;
}

// ═══════════ TOAST ═══════════
function mostrarToast(mensagem, tipo) {
    const cores = {success:'var(--green)',error:'var(--red)',info:'var(--cyan)',warning:'var(--amber, #f59e0b)'};
    const toast = document.createElement('div');
    toast.textContent = mensagem;
    toast.style.cssText = 'position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:'+(cores[tipo]||cores.success)+';color:'+(tipo==='warning'?'#000':'#fff')+';padding:12px 28px;border-radius:24px;font-size:14px;z-index:999999;font-weight:700;box-shadow:0 6px 24px rgba(0,0,0,.6);max-width:90vw;text-align:center;transition:opacity .3s;pointer-events:none';
    document.body.appendChild(toast);
    setTimeout(() => { toast.style.opacity = '0'; }, 2800);
    setTimeout(() => toast.remove(), 3500);
}
</script>

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