<?php
include '../config.php';
include '../configuracao/modelo.php'; // Garante que a função validaAcessoTela está carregada

session_start();
$numero_da_tela = 14; // ID gerado pelo banco

    if (!validaAcessoTela($mysqli, $_SESSION['id'], $numero_da_tela)) {
        echo "<script>alert('Sem permissão para o teste número $numero_da_tela!'); window.location.href='../lista/index.php';</script>";
        exit();
    }



// 1. Busca as contas para a lista de pesquisa (Modal)
$sql_contas = "SELECT reg_i050_cod_cta, reg_i050_cta FROM reg_i050 WHERE reg_i050_ind_cta = 'A' ORDER BY reg_i050_cod_cta";
$res_contas = $mysqli->query($sql_contas);

$conta_sel = $_GET['conta'] ?? '';
$data_ini = $_GET['inicio'] ?? '';
$data_fim = $_GET['fim'] ?? '';

$saldo_anterior = 0.00;
$total_debito = 0.00;
$total_credito = 0.00;

if ($conta_sel && $data_ini && $data_fim) {
    // 2. Saldo Anterior
    $sql_saldo = "SELECT SUM(CASE WHEN reg_i250_ind_dc = 'D' THEN REPLACE(reg_i250_vl_dc, ',', '.') ELSE -REPLACE(reg_i250_vl_dc, ',', '.') END) as total 
                  FROM reg_i250 
                  WHERE reg_i250_cod_cta = '$conta_sel' AND data < '$data_ini'";
    $res_saldo = $mysqli->query($sql_saldo);
    $saldo_anterior = (float)$res_saldo->fetch_assoc()['total'];

    // 3. Movimentação com Contrapartida
    $sql_mov = "SELECT 
                    i.data, i.reg_i250_vl_dc, i.reg_i250_ind_dc, i.enumsistema, i.reg_i250_hist,
                    (SELECT c.reg_i050_cta FROM reg_i250 i2 JOIN reg_i050 c ON i2.reg_i250_cod_cta = c.reg_i050_cod_cta 
                     WHERE i2.enumsistema = i.enumsistema AND i2.reg_i250_cod_cta <> i.reg_i250_cod_cta LIMIT 1) as contra_nome
                FROM reg_i250 i
                WHERE i.reg_i250_cod_cta = '$conta_sel' AND i.data BETWEEN '$data_ini' AND '$data_fim'
                ORDER BY i.data ASC";
    $res_mov = $mysqli->query($sql_mov);
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Razão Contábil Analítico</title>
    <style>
        * { box-sizing: border-box; }
        html, body { height: 100%; margin: 0; padding: 0; background-color: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; overflow: hidden; }
        .desktop-wrapper { display: flex; flex-direction: column; height: 100vh; padding: 4px; }
        .window { display: flex; flex-direction: column; flex-grow: 1; background-color: #d4d0c8; border: 2px solid; border-color: #ffffff #404040 #404040 #ffffff; }
        .title-bar { background: linear-gradient(90deg, #000080, #1084d0); padding: 3px 5px; color: white; font-weight: bold; display: flex; justify-content: space-between; align-items: center; }
        .content { display: flex; flex-direction: column; flex-grow: 1; padding: 8px; overflow: hidden; }
        fieldset { border: 1px solid; border-color: #808080 #ffffff #ffffff #808080; margin-bottom: 8px; padding: 10px; flex-shrink: 0; }
        input, select, button { background: #fff; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; font-family: Tahoma; font-size: 11px; margin-right: 5px; }
        button { background: #d4d0c8; padding: 2px 10px; cursor: pointer; }
        button:active { border-color: #404040 #ffffff #ffffff #404040; }
        .table-container { flex-grow: 1; overflow-y: auto; background: #fff; border: 2px solid; border-color: #808080 #ffffff #ffffff #808080; }
        table { width: 100%; border-collapse: collapse; min-width: 800px; }
        thead { position: sticky; top: 0; z-index: 10; }
        th { background: #d4d0c8; border: 1px solid #808080; padding: 5px; text-align: left; box-shadow: inset 1px 1px #fff, inset -1px -1px #404040; }
        td { border: 1px solid #d4d0c8; padding: 4px; }
        tr:nth-child(even) { background: #f8f8f8; }
        .text-right { text-align: right; }
        .row-saldo-ant { background-color: #ffffcc !important; font-weight: bold; }
        .row-total { background-color: #d4d0c8; font-weight: bold; position: sticky; bottom: 0; }
        .contra { color: #000080; font-style: italic; display: block; font-size: 10px; }
        
        /* Modal Style */
        #modalPesquisa { display:none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 450px; background: #d4d0c8; border: 2px solid; border-color: #fff #404040 #404040 #fff; z-index: 9999; box-shadow: 2px 2px 10px rgba(0,0,0,0.5); }
        #overlayModal { display:none; position: fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.3); z-index:9998; }
    </style>
</head>
<body>

<div class="desktop-wrapper">
    <div class="window">
        <div class="title-bar">
            <span>Razão Contábil Analítico - [Morfo Engine]</span>
            <div style="cursor:pointer;" onclick="window.history.back()">&#10006;</div>
        </div>

        <div class="content">
            <form method="GET">
                <fieldset>
                    <legend>Filtros de Relatório</legend>
                    Conta: 
                    <div style="display: inline-flex; gap: 2px; align-items: center;">
                        <input type="text" id="cod_cta_exibicao" name="conta" value="<?= $conta_sel ?>" style="width: 80px; text-align: center;" readonly required>
                        <input type="text" id="nome_cta_exibicao" style="width: 250px; background: #eee; border: 1px solid #808080;" placeholder="Selecione a conta contábil..." readonly>
                        <button type="button" onclick="abrirPesquisaContas()"><b>...</b></button>
                    </div>
                    
                    Data Inicial: <input type="date" name="inicio" value="<?= $data_ini ?>" required>
                    Data Final: <input type="date" name="fim" value="<?= $data_fim ?>" required>
                    
                    <button type="submit"><b>Processar</b></button>
                </fieldset>
            </form>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th width="80">Data</th>
                            <th>Histórico / Contrapartida</th>
                            <th class="text-right" width="100">Débito</th>
                            <th class="text-right" width="100">Crédito</th>
                            <th class="text-right" width="120">Saldo Acumulado</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($conta_sel): ?>
                            <tr class="row-saldo-ant">
                                <td colspan="4">SALDO ANTERIOR AO PERÍODO</td>
                                <td class="text-right">R$ <?= number_format($saldo_anterior, 2, ',', '.') ?></td>
                            </tr>

                            <?php 
                            $saldo_atual = $saldo_anterior;
                            if (isset($res_mov) && $res_mov):
                                while($l = $res_mov->fetch_assoc()): 
                                    $valor = (float)str_replace(',', '.', $l['reg_i250_vl_dc']);
                                    $d = ($l['reg_i250_ind_dc'] == 'D') ? $valor : 0;
                                    $c = ($l['reg_i250_ind_dc'] == 'C') ? $valor : 0;
                                    
                                    $total_debito += $d;
                                    $total_credito += $c;
                                    $saldo_atual += ($d - $c);
                            ?>
                            <tr>
                                <td><?= date('d/m/y', strtotime($l['data'])) ?></td>
                                <td>
                                    <strong><?= $l['reg_i250_hist'] ?></strong>
                                    <span class="contra">Origem: <?= $l['enumsistema'] ?> | CP: <?= $l['contra_nome'] ?: 'Lcto Diversos' ?></span>
                                </td>
                                <td class="text-right"><?= $d > 0 ? number_format($d, 2, ',', '.') : '0,00' ?></td>
                                <td class="text-right"><?= $c > 0 ? number_format($c, 2, ',', '.') : '0,00' ?></td>
                                <td class="text-right"><b><?= number_format($saldo_atual, 2, ',', '.') ?></b></td>
                            </tr>
                        <?php endwhile; endif; ?>
                        
                        <tr class="row-total">
                            <td colspan="2">TOTAIS DO PERÍODO</td>
                            <td class="text-right">R$ <?= number_format($total_debito, 2, ',', '.') ?></td>
                            <td class="text-right">R$ <?= number_format($total_credito, 2, ',', '.') ?></td>
                            <td class="text-right" style="background: #fff;">
                                <b>R$ <?= number_format($saldo_atual, 2, ',', '.') ?></b>
                            </td>
                        </tr>
                        <?php else: ?>
                            <tr><td colspan="5" style="text-align:center; padding: 50px; color: #666;">Selecione os filtros acima para gerar os lançamentos.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div style="background: #d4d0c8; border-top: 1px solid #808080; padding: 2px; display: flex; gap: 2px; flex-shrink: 0;">
            <div style="border: 1px inset #fff; padding: 2px 5px; flex-grow: 1;">Pronto</div>
            <div style="border: 1px inset #fff; padding: 2px 5px; width: 150px;">Registros: <?= isset($res_mov) ? $res_mov->num_rows : 0 ?></div>
        </div>
    </div>
</div>

<div id="modalPesquisa">
    <div class="title-bar">
        <span>Localizar Conta Contábil</span>
        <button type="button" onclick="fecharPesquisaContas()" style="width:16px; height:14px; font-size:9px;">X</button>
    </div>
    <div style="padding: 10px;">
        <label>Pesquisar por Código ou Nome:</label><br>
        <input type="text" id="inputFiltroCta" onkeyup="filtrarContasNaLista()" style="width: 100%; margin: 5px 0; border: 2px inset #fff;" autofocus>
        
        <div style="height: 250px; overflow-y: scroll; background: #fff; border: 2px inset #808080; margin-top: 5px;">
            <table id="listaContasPesquisa" style="width: 100%; min-width: auto; cursor: pointer;">
                <tbody id="corpoListaContas">
                    <?php 
                    $res_contas->data_seek(0); 
                    while($c = $res_contas->fetch_assoc()): 
                    ?>
                        <tr onclick="selecionarConta('<?= $c['reg_i050_cod_cta'] ?>', '<?= $c['reg_i050_cta'] ?>')">
                            <td style="border-bottom: 1px solid #eee; padding: 3px; width: 80px;"><?= $c['reg_i050_cod_cta'] ?></td>
                            <td style="border-bottom: 1px solid #eee; padding: 3px;"><?= $c['reg_i050_cta'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <div style="text-align: right; margin-top: 10px;">
            <button type="button" onclick="fecharPesquisaContas()">Cancelar</button>
        </div>
    </div>
</div>
<div id="overlayModal" onclick="fecharPesquisaContas()"></div>

<script>
function abrirPesquisaContas() {
    document.getElementById('modalPesquisa').style.display = 'block';
    document.getElementById('overlayModal').style.display = 'block';
    document.getElementById('inputFiltroCta').value = '';
    filtrarContasNaLista();
    document.getElementById('inputFiltroCta').focus();
}

function fecharPesquisaContas() {
    document.getElementById('modalPesquisa').style.display = 'none';
    document.getElementById('overlayModal').style.display = 'none';
}

function filtrarContasNaLista() {
    let input = document.getElementById('inputFiltroCta').value.toUpperCase();
    let rows = document.getElementById('corpoListaContas').getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        let text = rows[i].innerText.toUpperCase();
        rows[i].style.display = text.indexOf(input) > -1 ? "" : "none";
    }
}

function selecionarConta(codigo, nome) {
    document.getElementById('cod_cta_exibicao').value = codigo;
    document.getElementById('nome_cta_exibicao').value = nome;
    fecharPesquisaContas();
}

window.onload = function() {
    let codInicial = document.getElementById('cod_cta_exibicao').value;
    if(codInicial) {
        let rows = document.getElementById('corpoListaContas').getElementsByTagName('tr');
        for (let i = 0; i < rows.length; i++) {
            if(rows[i].cells[0].innerText === codInicial) {
                document.getElementById('nome_cta_exibicao').value = rows[i].cells[1].innerText;
                break;
            }
        }
    }
};
</script>

</body>
</html>	