<?php
// frota_veiculo_form.php — Cadastrar / Editar Veículo
$pageActive = 'frota';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$usuario = usuarioLogado();
if ($usuario['perfil'] !== 'ADMIN') {
    header('Location: frota.php');
    exit;
}

$id = (int)($_GET['id'] ?? 0);
$veiculo = null;
if ($id) {
    $stmt = pdo()->prepare("SELECT * FROM frota_veiculos WHERE id = ?");
    $stmt->execute([$id]);
    $veiculo = $stmt->fetch();
}

$pageTitle = $id ? 'Editar Veículo' : 'Novo Veículo';

// Buscar técnicos para select de responsável
$stmtTec = pdo()->query("SELECT id, nome FROM usuarios WHERE perfil IN ('TECNICO', 'ADMIN') AND ativo = 1 ORDER BY nome");
$tecnicos = $stmtTec->fetchAll();

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

<style>
.veiculo-form {
    max-width: 600px;
    margin: 0 auto;
}
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
    <div>
        <div class="page-title"><?= $id ? ' Editar Veículo' : '+ Novo Veículo' ?></div>
        <div class="page-sub"><?= $id ? e($veiculo['placa'] ?? '') : 'Cadastrar veículo na frota' ?></div>
    </div>
    <div class="topbar-actions">
        <a href="frota.php" class="btn btn-ghost"> Voltar</a>
    </div>
</div>

<div class="content">
    <div class="veiculo-form">
        <div class="form-card">
            <div class="form-section-title"> DADOS DO VEÍCULO</div>
            
            <form id="form-veiculo" onsubmit="salvarVeiculo(event)">
                <input type="hidden" name="id" value="<?= $id ?>"/>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">PLACA *</label>
                        <input class="form-input" type="text" name="placa" id="placa" 
                               value="<?= e($veiculo['placa'] ?? '') ?>" 
                               required placeholder="ABC-1234" maxlength="10"
                               oninput="this.value = this.value.toUpperCase()"/>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">ANO</label>
                        <input class="form-input" type="number" name="ano" 
                               value="<?= e($veiculo['ano'] ?? '') ?>" 
                               placeholder="2024" min="2000" max="<?= date('Y')+1 ?>"/>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">MODELO</label>
                    <input class="form-input" type="text" name="modelo" 
                           value="<?= e($veiculo['modelo'] ?? '') ?>" 
                           placeholder="Ex: Fiat Strada Volcano"/>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">KM ATUAL</label>
                        <input class="form-input" type="number" name="km_atual" 
                               value="<?= (int)($veiculo['km_atual'] ?? 0) ?>" 
                               placeholder="0" min="0"/>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">RESPONSÁVEL</label>
                        <select class="form-select" name="responsavel_id">
                            <option value="">Selecione...</option>
                            <?php foreach ($tecnicos as $t): ?>
                            <option value="<?= $t['id'] ?>" <?= ($veiculo['responsavel_id'] ?? '') == $t['id'] ? 'selected' : '' ?>>
                                <?= e($t['nome']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div style="display:flex;gap:12px;justify-content:flex-end;margin-top:16px">
                    <a href="frota.php" class="btn btn-ghost">Cancelar</a>
                    <button type="submit" class="btn btn-primary">
                        <?= $id ? ' Atualizar' : ' Cadastrar Veículo' ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
async function salvarVeiculo(e) {
    e.preventDefault();
    const form = document.getElementById('form-veiculo');
    const formData = new FormData(form);
    formData.append('acao', 'salvar_veiculo');
    
    const btn = form.querySelector('button[type="submit"]');
    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(' ' + data.mensagem, 'success');
            setTimeout(() => window.location.href = 'frota.php', 800);
        } else {
            mostrarToast(' ' + (data.erro || 'Erro ao salvar'), 'error');
        }
    } catch(e) {
        mostrarToast(' Erro de conexão', 'error');
    }
    
    btn.disabled = false;
    btn.textContent = '<?= $id ? " Atualizar" : " Cadastrar Veículo" ?>';
}
</script>

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