<?php
// 1. DATABASE ENGINE - SQLITE (Todos os campos mapeados)
$db = new PDO('sqlite:matriz_fiscal_completa.db');
$db->exec("CREATE TABLE IF NOT EXISTS matriz (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    regime TEXT, tipo_empresa TEXT, natureza_operacao TEXT, finalidade TEXT, ie_destinatario TEXT,
    ncm TEXT, extipi TEXT, uf_ori TEXT, uf_des TEXT, cfop_ori TEXT, cfop_des TEXT,
    origem_mercadoria TEXT,
    -- ICMS PROPRIO ORIGEM/DESTINO
    bc_icms_ori REAL, cst_icms_ori TEXT, aliq_icms_ori REAL, mod_bc_icms_ori TEXT, red_bc_icms_ori REAL,
    bc_icms_des REAL, cst_icms_des TEXT, aliq_icms_des REAL, mod_bc_icms_des TEXT, red_bc_icms_des REAL,
    -- ICMS ST ORIGEM/DESTINO
    bc_st_ori REAL, mod_bc_st_ori TEXT, red_bc_st_ori REAL, iva_st REAL,
    bc_st_des REAL, cst_st_des TEXT, aliq_st_des REAL, mod_bc_st_des TEXT, red_bc_st_des REAL,
    -- DIFERIMENTO
    perc_dif_ori REAL, motivo_dif_ori TEXT, perc_dif_des REAL, motivo_dif_des REAL,
    -- IPI / PIS / COFINS / FCP
    bc_ipi_ori REAL, aliq_ipi_ori REAL, bc_ipi_des REAL, aliq_ipi_des REAL,
    cst_pis_ori TEXT, cst_pis_des TEXT, cst_cof_ori TEXT, cst_cof_des TEXT,
    bc_fcp_ori REAL, perc_fcp_ori REAL,
    -- DIFAL E PIS/COFINS ST
    calcula_difal TEXT, aliq_interna_des REAL, bc_fcp_des REAL, aliq_fcp_des REAL,
    bc_pis_st_ori REAL, aliq_pis_st_ori REAL, bc_pis_st_des REAL, aliq_pis_st_des REAL
)");

// 2. API ACTIONS
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    if ($_GET['action'] == 'listar') {
        echo json_encode($db->query("SELECT * FROM matriz ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC));
    }
    if ($_GET['action'] == 'salvar' && $_SERVER['REQUEST_METHOD'] == 'POST') {
        $keys = array_keys($_POST);
        $sql = "INSERT INTO matriz (" . implode(',', $keys) . ") VALUES (" . implode(',', array_fill(0, count($keys), '?')) . ")";
        $db->prepare($sql)->execute(array_values($_POST));
        echo json_encode(['status' => 'success']);
    }
    if ($_GET['action'] == 'excluir') {
        $db->prepare("DELETE FROM matriz WHERE id = ?")->execute([$_GET['id']]);
        echo json_encode(['status' => 'success']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>SGF - Sistema de Gestão Fiscal v2026.1</title>
    <style>
        * { box-sizing: border-box; font-family: "Tahoma", "Verdana", sans-serif; font-size: 11px; }
        body { background-color: #3a6ea5; margin: 0; padding: 4px; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
        
        /* Estilo Janela Win2000 */
        .win-window { background-color: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff; display: flex; flex-direction: column; flex: 1; box-shadow: 1px 1px 0px #000; }
        .win-title { background: linear-gradient(90deg, #000080, #1084d0); color: white; padding: 3px 5px; display: flex; justify-content: space-between; font-weight: bold; align-items: center; }
        .win-toolbar { padding: 4px; display: flex; gap: 4px; border-bottom: 1px solid #808080; }
        
        /* Botões */
        .win-btn { background: #d4d0c8; border: 1px solid; border-color: #fff #000 #000 #fff; padding: 3px 12px; cursor: pointer; outline: none; }
        .win-btn:active { border-color: #000 #fff #fff #000; padding: 4px 11px 2px 13px; }
        .win-btn-del { color: #a00; font-weight: bold; padding: 0 4px; }

        /* Formulário de 5 Colunas */
        .win-form-scroll { overflow-y: auto; max-height: 380px; border-bottom: 2px solid #808080; padding: 8px; }
        .win-grid-cols { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; }
        fieldset { border: 1px solid #fff; border-right-color: #808080; border-bottom-color: #808080; padding: 8px; margin-bottom: 5px; }
        legend { margin-left: 5px; padding: 0 3px; }

        .field { display: flex; margin-bottom: 3px; align-items: center; }
        .field label { width: 90px; text-align: right; margin-right: 6px; white-space: nowrap; }
        input, select { border: 1px solid; border-color: #808080 #fff #fff #808080; background: #fff; padding: 1px; flex: 1; height: 18px; }
        input:focus { background-color: #ffffca; }

        /* Tabela / Grid */
        .win-grid-container { flex: 1; background: #fff; margin: 6px; border: 1px solid; border-color: #808080 #fff #fff #808080; overflow: auto; }
        table { width: 100%; border-collapse: collapse; table-layout: fixed; }
        th { background: #d4d0c8; border: 1px solid; border-color: #fff #808080 #808080 #fff; padding: 3px; position: sticky; top: 0; text-align: left; z-index: 2; }
        td { border: 1px solid #d4d0c8; padding: 2px 4px; font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        tr:nth-child(even) { background: #f1f1f1; }
        tr:hover { background: #000080 !important; color: #fff; }

        .win-status { background: #d4d0c8; border-top: 1px solid #808080; padding: 2px 8px; display: flex; justify-content: space-between; font-size: 10px; }
    </style>
</head>
<body>

<div class="win-window">
    <div class="win-title">
        <span>Matriz_Fiscal_Total_Expert.exe</span>
        <span style="font-family:Webdings; cursor:default">0 2 r</span>
    </div>

    <div class="win-toolbar">
        <button class="win-btn" onclick="salvar()"><b>💾 Salvar Regra</b></button>
        <button class="win-btn" onclick="document.getElementById('fMatriz').reset()">📄 Limpar Tela</button>
        <button class="win-btn">🔍 Filtros Avançados</button>
    </div>

    <div class="win-form-scroll">
        <form id="fMatriz">
            <div class="win-grid-cols">
                <div>
                    <fieldset>
                        <legend>Dados Principais</legend>
                        <div class="field"><label>Regime:</label>
                            <select name="regime">
                                <option>Real</option><option>Presumido</option><option>Simples</option><option>MEI</option>
                            </select>
                        </div>
                        <div class="field"><label>Tipo Emp:</label>
                            <select name="tipo_empresa"><option>Industrial</option><option>Outras</option></select>
                        </div>
                        <div class="field"><label>Finalidade:</label>
                            <select name="finalidade"><option>Revenda</option><option>Cons. Final</option></select>
                        </div>
                        <div class="field"><label>NCM:</label><input type="text" name="ncm" required></div>
                        <div class="field"><label>UFs (O/D):</label>
                            <input type="text" name="uf_ori" maxlength="2" placeholder="SC">
                            <input type="text" name="uf_des" maxlength="2" placeholder="SP">
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend>Origem Mercadoria</legend>
                        <select name="origem_mercadoria" style="width:100%">
                            <option value="0">0 - Nacional</option>
                            <option value="1">1 - Estrangeira Direta</option>
                            <option value="2">2 - Estrangeira Interna</option>
                            <option value="3">3 - Nac. Conteúdo >40%</option>
                            <option value="5">5 - Nac. Conteúdo <40%</option>
                        </select>
                    </fieldset>
                </div>

                <div>
                    <fieldset style="background:#e8f0ff">
                        <legend>ICMS Próprio ORIGEM</legend>
                        <div class="field"><label>CST/CSOSN:</label><input type="text" name="cst_icms_ori"></div>
                        <div class="field"><label>BC ICMS:</label><input type="number" step="0.01" name="bc_icms_ori"></div>
                        <div class="field"><label>Alíquota %:</label><input type="number" step="0.01" name="aliq_icms_ori"></div>
                        <div class="field"><label>Redução %:</label><input type="number" step="0.01" name="red_bc_icms_ori"></div>
                    </fieldset>
                    <fieldset style="background:#e8f0ff">
                        <legend>ICMS Próprio DESTINO</legend>
                        <div class="field"><label>CST:</label><input type="text" name="cst_icms_des"></div>
                        <div class="field"><label>Alíquota %:</label><input type="number" step="0.01" name="aliq_icms_des"></div>
                        <div class="field"><label>CFOP (O/D):</label>
                            <input type="text" name="cfop_ori">
                            <input type="text" name="cfop_des">
                        </div>
                    </fieldset>
                </div>

                <div>
                    <fieldset style="background:#fff8e1">
                        <legend>ICMS ST (Substituição)</legend>
                        <div class="field"><label>IVA/MVA %:</label><input type="number" step="0.01" name="iva_st"></div>
                        <div class="field"><label>Mod. BC ST:</label>
                            <select name="mod_bc_st_ori">
                                <option value="4">4-MVA</option><option value="5">5-Pauta</option>
                                <option value="0">0-Tabelado</option>
                            </select>
                        </div>
                        <div class="field"><label>CST ST Des:</label><input type="text" name="cst_st_des"></div>
                        <div class="field"><label>Aliq ST Des:</label><input type="number" step="0.01" name="aliq_st_des"></div>
                    </fieldset>
                    <fieldset>
                        <legend>Diferimento</legend>
                        <div class="field"><label>% Dif. Ori:</label><input type="number" step="0.01" name="perc_dif_ori"></div>
                        <div class="field"><label>Motivo Ori:</label><input type="text" name="motivo_dif_ori"></div>
                    </fieldset>
                </div>

                <div>
                    <fieldset style="background:#f0ffe8">
                        <legend>IPI / FCP</legend>
                        <div class="field"><label>Aliq IPI Ori:</label><input type="number" step="0.01" name="aliq_ipi_ori"></div>
                        <div class="field"><label>Aliq IPI Des:</label><input type="number" step="0.01" name="aliq_ipi_des"></div>
                        <div class="field"><label>BC FCP Ori:</label><input type="number" step="0.01" name="bc_fcp_ori"></div>
                        <div class="field"><label>Aliq FCP %:</label><input type="number" step="0.01" name="perc_fcp_ori"></div>
                    </fieldset>
                    <fieldset>
                        <legend>DIFAL (Interestadual)</legend>
                        <div class="field"><label>Calc DIFAL:</label>
                            <select name="calcula_difal"><option>Não</option><option>Sim</option></select>
                        </div>
                        <div class="field"><label>Aliq Int Des:</label><input type="number" step="0.01" name="aliq_interna_des"></div>
                        <div class="field"><label>FCP Dest %:</label><input type="number" step="0.01" name="aliq_fcp_des"></div>
                    </fieldset>
                </div>

                <div>
                    <fieldset style="background:#f9e8ff">
                        <legend>PIS / COFINS</legend>
                        <div class="field"><label>CST PIS O:</label><input type="text" name="cst_pis_ori"></div>
                        <div class="field"><label>CST PIS D:</label><input type="text" name="cst_pis_des"></div>
                        <div class="field"><label>CST COF O:</label><input type="text" name="cst_cof_ori"></div>
                        <div class="field"><label>CST COF D:</label><input type="text" name="cst_cof_des"></div>
                    </fieldset>
                    <fieldset style="background:#f9e8ff">
                        <legend>PIS/COFINS ST</legend>
                        <div class="field"><label>Aliq PIS ST:</label><input type="number" step="0.01" name="aliq_pis_st_ori"></div>
                        <div class="field"><label>Aliq COF ST:</label><input type="number" step="0.01" name="aliq_pis_st_des"></div>
                    </fieldset>
                </div>
            </div>
        </form>
    </div>

    <div class="win-grid-container">
        <table>
            <thead>
                <tr>
                    <th width="30">ID</th>
                    <th width="80">NCM</th>
                    <th width="60">ROTA</th>
                    <th width="100">REGIME</th>
                    <th width="60">CFOP O.</th>
                    <th width="60">CST O.</th>
                    <th width="50">ICMS</th>
                    <th width="50">MVA%</th>
                    <th width="80">PIS/COF</th>
                    <th width="50">DIFAL</th>
                    <th width="50">FCP%</th>
                    <th width="40">AÇÃO</th>
                </tr>
            </thead>
            <tbody id="gridDados"></tbody>
        </table>
    </div>

    <div class="win-status">
        <span id="lbTotal">Registros: 0</span>
        <span>Unidade Fiscal: Ativa</span>
        <span>Acesso: ADMINISTRADOR</span>
    </div>
</div>

<script>
async function carregar() {
    const r = await fetch('?action=listar');
    const d = await r.json();
    const b = document.getElementById('gridDados');
    b.innerHTML = '';
    document.getElementById('lbTotal').innerText = `Registros: ${d.length}`;
    d.forEach(i => {
        b.innerHTML += `<tr>
            <td>${i.id}</td>
            <td><b>${i.ncm}</b></td>
            <td>${i.uf_ori}➜${i.uf_des}</td>
            <td>${i.regime}</td>
            <td>${i.cfop_ori}</td>
            <td>${i.cst_icms_ori}</td>
            <td>${i.aliq_icms_ori}%</td>
            <td>${i.iva_st}%</td>
            <td>${i.cst_pis_ori}/${i.cst_cof_ori}</td>
            <td>${i.calcula_difal}</td>
            <td>${i.aliq_fcp_des}%</td>
            <td align="center"><button class="win-btn win-btn-del" onclick="excluir(${i.id})">×</button></td>
        </tr>`;
    });
}

async function salvar() {
    const f = document.getElementById('fMatriz');
    await fetch('?action=salvar', { method: 'POST', body: new FormData(f) });
    f.reset();
    carregar();
}

async function excluir(id) {
    if(confirm('Excluir ID '+id+'?')) {
        await fetch(`?action=excluir&id=${id}`);
        carregar();
    }
}

carregar();
</script>
</body>
</html>