<?php
// 1. CONFIGURAÇÕES DE ERRO E DATA
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');

// 2. INCLUSÃO DE CONFIGURAÇÃO E HEADER
if (file_exists('../config.php')) {
    include_once('../config.php');
} else {
    die("Erro Crítico: Arquivo de configuração não encontrado.");
}
include_once('../header.php');

// 3. FUNÇÃO DE AUTO-REPARO (Garante IDs válidos)
function obterIdVeiculo($conn, $nomeBusca, $nomePadrao) {
    $sql = "SELECT id FROM veiculos WHERE nome = '$nomePadrao' OR nome LIKE '%$nomeBusca%' LIMIT 1";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return (int)$row['id'];
    } else {
        $conn->query("INSERT INTO veiculos (nome) VALUES ('$nomePadrao')");
        return (int)$conn->insert_id;
    }
}

$id_cb300 = obterIdVeiculo($conn, 'CB%300', 'CB 300');
$id_civic = obterIdVeiculo($conn, 'CIVIC', 'HONDA CIVIC');

// 4. LÓGICA PARA EXCLUIR
if (isset($_GET['excluir'])) {
    $id_ex = intval($_GET['excluir']);
    $conn->query("DELETE FROM manutencoes_veiculos WHERE id = $id_ex");
    echo "<script>window.location.href='manutencaoveiculos.php';</script>";
    exit();
}

// 5. LÓGICA PARA SALVAR
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_manutencao'])) {
    $v_id   = intval($_POST['veiculo_id']);
    $desc   = strtoupper($conn->real_escape_string($_POST['descricao']));
    $valor  = str_replace(',', '.', $_POST['valor']); 
    $data   = $_POST['data_servico'];
    $km     = intval($_POST['km_atual']);
    $local  = strtoupper($conn->real_escape_string($_POST['local']));
    $obs    = strtoupper($conn->real_escape_string($_POST['observacao']));

    $sql = "INSERT INTO manutencoes_veiculos (veiculo_id, descricao, valor, data_servico, km_atual, local, observacao) 
            VALUES ($v_id, '$desc', '$valor', '$data', '$km', '$local', '$obs')";
    
    if($conn->query($sql)){
        echo "<script>window.location.href='manutencaoveiculos.php?msg=sucesso';</script>";
        exit();
    }
}
?>

<style>
    .v-wrapper { padding: 10px; font-family: 'Segoe UI', Tahoma, sans-serif; text-transform: uppercase; }
    
    /* ESTILO ABAS EXCEL */
    .tab-container { display: flex; border-bottom: 1px solid #999; margin-bottom: 10px; background: #ddd; }
    .tab-btn { padding: 6px 20px; cursor: pointer; border: 1px solid #999; border-bottom: none; background: #eee; font-weight: bold; font-size: 10px; color: #333; margin-right: 2px; }
    .tab-btn.active { background: #fff; color: #000; border-top: 3px solid #217346; }
    .tab-content { display: none; }
    .tab-content.active { display: block; }

    /* LAYOUT */
    .grid-main { display: grid; grid-template-columns: 320px 1fr; gap: 10px; align-items: start; }
    .card-veiculo { background: #fff; border: 1px solid #999; padding: 10px; height: fit-content; }
    label { display: block; margin-top: 5px; font-weight: bold; font-size: 9px; color: #444; }
    input, textarea { width: 100%; padding: 4px; margin-top: 2px; border: 1px solid #999; box-sizing: border-box; font-size: 10px; text-transform: uppercase; background: #fff; }
    .btn-salvar { background: #217346; color: white; border: 1px solid #1a5a37; padding: 8px; width: 100%; font-weight: bold; cursor: pointer; margin-top: 10px; font-size: 10px; }
    
    /* TABELA EXCEL */
    .table-excel { width: 100%; border-collapse: collapse; font-size: 10px; background: white; border: 1px solid #999; }
    .table-excel th { background: #e6e6e6; color: #333; padding: 2px 5px; text-align: left; border: 1px solid #999; font-weight: bold; }
    .table-excel td { padding: 1px 5px; border: 1px solid #ccc; line-height: 1.1; height: 16px; white-space: nowrap; }
    .table-excel tr:hover { background-color: #f2f2f2; }
    
    /* LINHA DE SOMA */
    .tr-soma { background-color: #d9d9d9; font-weight: bold; }
    .tr-soma td { border-top: 2px solid #999; }
    
    .obs-celula { font-size: 9px; color: #666; font-style: italic; margin-left: 5px; }
    .txt-valor { text-align: right; color: #000; }
    .txt-local { color: #217346; font-weight: bold; }
    .btn-acao { text-decoration: none; font-size: 12px; margin: 0 2px; }
</style>

<div class="v-wrapper">
    <div style="font-weight: bold; font-size: 12px; color: #217346; margin-bottom: 10px; border-bottom: 1px solid #ccc;">
        PLANILHA DE MANUTENÇÃO - VEÍCULOS
    </div>

    <div class="tab-container">
        <button class="tab-btn active" onclick="openTab(event, 'aba-moto')">CB 300</button>
        <button class="tab-btn" onclick="openTab(event, 'aba-carro')">HONDA CIVIC</button>
    </div>

    <div id="aba-moto" class="tab-content active">
        <div class="grid-main">
            <div class="card-veiculo">
                <form method="POST">
                    <input type="hidden" name="veiculo_id" value="<?php echo $id_cb300; ?>">
                    <label>DESCRIÇÃO DO SERVIÇO:</label>
                    <input type="text" name="descricao" required>
                    <div style="display: flex; gap: 5px;">
                        <div style="flex:1;"><label>VALOR R$:</label><input type="number" step="0.01" name="valor" required></div>
                        <div style="flex:1;"><label>KM ATUAL:</label><input type="number" name="km_atual"></div>
                    </div>
                    <label>LOCAL:</label>
                    <input type="text" name="local">
                    <label>DATA:</label>
                    <input type="date" name="data_servico" value="<?php echo date('Y-m-d'); ?>">
                    <label>OBSERVAÇÃO:</label>
                    <textarea name="observacao" rows="2" style="resize: none;"></textarea>
                    <button type="submit" name="add_manutencao" class="btn-salvar">REGISTRAR NA PLANILHA</button>
                </form>
            </div>

            <table class="table-excel">
                <thead>
                    <tr>
                        <th width="70">DATA</th>
                        <th>DESCRIÇÃO / OBSERVAÇÃO</th>
                        <th width="120">LOCAL</th>
                        <th width="70">KM</th>
                        <th width="90">VALOR (R$)</th>
                        <th width="50">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $total_moto = 0;
                    $res = $conn->query("SELECT * FROM manutencoes_veiculos WHERE veiculo_id = $id_cb300 ORDER BY data_servico DESC");
                    while($l = $res->fetch_assoc()): 
                        $total_moto += $l['valor'];
                    ?>
                        <tr>
                            <td><?php echo date('d/m/Y', strtotime($l['data_servico'])); ?></td>
                            <td>
                                <strong><?php echo $l['descricao']; ?></strong>
                                <?php if(($l['observacao'] ?? '')) echo "<span class='obs-celula'>- ".$l['observacao']."</span>"; ?>
                            </td>
                            <td class="txt-local"><?php echo ($l['local'] ?? ''); ?></td>
                            <td style="text-align: center;"><?php echo number_format($l['km_atual'], 0, '', '.'); ?></td>
                            <td class="txt-valor"><?php echo number_format($l['valor'], 2, ',', '.'); ?></td>
                            <td style="text-align:center;">
                                <a href="editar_manutencao.php?id=<?php echo $l['id']; ?>" class="btn-acao" title="EDITAR">✏️</a>
                                <a href="?excluir=<?php echo $l['id']; ?>" class="btn-acao" title="EXCLUIR" onclick="return confirm('EXCLUIR?')">🗑️</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
                <tfoot>
                    <tr class="tr-soma">
                        <td colspan="4" style="text-align: right;">TOTAL GERAL:</td>
                        <td class="txt-valor"><?php echo number_format($total_moto, 2, ',', '.'); ?></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div id="aba-carro" class="tab-content">
        <div class="grid-main">
            <div class="card-veiculo">
                <form method="POST">
                    <input type="hidden" name="veiculo_id" value="<?php echo $id_civic; ?>">
                    <label>DESCRIÇÃO DO SERVIÇO:</label>
                    <input type="text" name="descricao" required>
                    <div style="display: flex; gap: 5px;">
                        <div style="flex:1;"><label>VALOR R$:</label><input type="number" step="0.01" name="valor" required></div>
                        <div style="flex:1;"><label>KM ATUAL:</label><input type="number" name="km_atual"></div>
                    </div>
                    <label>LOCAL:</label>
                    <input type="text" name="local">
                    <label>DATA:</label>
                    <input type="date" name="data_servico" value="<?php echo date('Y-m-d'); ?>">
                    <label>OBSERVAÇÃO:</label>
                    <textarea name="observacao" rows="2" style="resize: none;"></textarea>
                    <button type="submit" name="add_manutencao" class="btn-salvar">REGISTRAR NA PLANILHA</button>
                </form>
            </div>

            <table class="table-excel">
                <thead>
                    <tr>
                        <th width="70">DATA</th>
                        <th>DESCRIÇÃO / OBSERVAÇÃO</th>
                        <th width="120">LOCAL</th>
                        <th width="70">KM</th>
                        <th width="90">VALOR (R$)</th>
                        <th width="50">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $total_carro = 0;
                    $res = $conn->query("SELECT * FROM manutencoes_veiculos WHERE veiculo_id = $id_civic ORDER BY data_servico DESC");
                    while($l = $res->fetch_assoc()): 
                        $total_carro += $l['valor'];
                    ?>
                        <tr>
                            <td><?php echo date('d/m/Y', strtotime($l['data_servico'])); ?></td>
                            <td>
                                <strong><?php echo $l['descricao']; ?></strong>
                                <?php if(($l['observacao'] ?? '')) echo "<span class='obs-celula'>- ".$l['observacao']."</span>"; ?>
                            </td>
                            <td class="txt-local"><?php echo ($l['local'] ?? ''); ?></td>
                            <td style="text-align: center;"><?php echo number_format($l['km_atual'], 0, '', '.'); ?></td>
                            <td class="txt-valor"><?php echo number_format($l['valor'], 2, ',', '.'); ?></td>
                            <td style="text-align:center;">
                                <a href="editar_manutencao.php?id=<?php echo $l['id']; ?>" class="btn-acao" title="EDITAR">✏️</a>
                                <a href="?excluir=<?php echo $l['id']; ?>" class="btn-acao" title="EXCLUIR" onclick="return confirm('EXCLUIR?')">🗑️</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
                <tfoot>
                    <tr class="tr-soma">
                        <td colspan="4" style="text-align: right;">TOTAL GERAL:</td>
                        <td class="txt-valor"><?php echo number_format($total_carro, 2, ',', '.'); ?></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<script>
function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; }
    tablinks = document.getElementsByClassName("tab-btn");
    for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
</script>