<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
include '../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$roleId = isset($_SESSION['user']['roleId']) ? (int)$_SESSION['user']['roleId'] : 0;
$isSuper = isset($_SESSION['user']['isSuper']) && (int)$_SESSION['user']['isSuper'] === 1;
$canSeeContabilidad = $isSuper || in_array($roleId, [1, 2, 4], true);
if (!$canSeeContabilidad) {
    http_response_code(403);
    die('No autorizado');
}

function fmt($v)
{
    return $v == 0 ? '-' : '$ ' . number_format(abs($v), 0, '', '.');
}
function txt($s)
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}
function getTextColor($hex)
{
    $h = ltrim((string)$hex, '#');
    $r = hexdec(substr($h, 0, 2));
    $g = hexdec(substr($h, 2, 2));
    $b = hexdec(substr($h, 4, 2));
    return (($r * 0.299 + $g * 0.587 + $b * 0.114) / 255 > 0.5) ? '#000' : '#fff';
}
function cpnParseBreakdownMap($raw, bool $showPercent = false): array
{
    if (is_string($raw)) {
        $decoded = json_decode($raw, true);
    } elseif (is_array($raw)) {
        $decoded = $raw;
    } else {
        $decoded = [];
    }
    if (!is_array($decoded)) return [];

    $out = [];
    foreach ($decoded as $it) {
        if (!is_array($it)) continue;
        $name = trim((string)($it['nombre'] ?? ''));
        if ($name === '') continue;
        $val = (float)($it['valor'] ?? 0);
        if (abs($val) < 0.000001) continue;

        $label = $name;
        if ($showPercent && isset($it['porcentaje']) && $it['porcentaje'] !== null && $it['porcentaje'] !== '') {
            $pct = (float)$it['porcentaje'];
            $pct = abs($pct) <= 1 ? ($pct * 100) : $pct;
            $dec = (abs($pct - round($pct)) < 0.0001) ? 0 : 2;
            $label .= ' ' . number_format($pct, $dec, '.', '') . '%';
        }

        if (!isset($out[$label])) $out[$label] = 0;
        $out[$label] += $val;
    }
    return $out;
}

$token = cpn_node_token_or_fail();
$nodeBase = cpn_node_api_base();

$idOrigen = intval($_GET['or'] ?? 0);

$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$filter_limit = trim((string)($_GET['filter_limit'] ?? '50'));
if (!in_array($filter_limit, ['20', '50', 'all'], true)) $filter_limit = '50';
$isAllRows = ($filter_limit === 'all');
$limit = $isAllRows ? 'all' : $filter_limit;
if ($isAllRows) $page = 1;

$fi = $_GET['filter_id'] ?? '';
$ff = $_GET['filter_factura'] ?? '';
$fb = $_GET['filter_beneficiario'] ?? '';
$ft = $_GET['idTercero'] ?? '';
$filter_empresa = isset($_GET['filter_empresa']) && $_GET['filter_empresa'] !== '0' && $_GET['filter_empresa'] !== ''
    ? intval($_GET['filter_empresa'])
    : '';
$filter_anio = isset($_GET['filter_anio']) && $_GET['filter_anio'] !== ''
    ? intval($_GET['filter_anio'])
    : '';

$rawFilterMes = $_GET['filter_mes'] ?? [];
$filterMesList = [];
if (is_array($rawFilterMes)) {
    foreach ($rawFilterMes as $m) {
        $mi = intval($m);
        if ($mi >= 1 && $mi <= 12) $filterMesList[] = str_pad((string)$mi, 2, '0', STR_PAD_LEFT);
    }
} else {
    $raw = trim((string)$rawFilterMes);
    if ($raw !== '') {
        foreach (explode(',', $raw) as $m) {
            $mi = intval(trim($m));
            if ($mi >= 1 && $mi <= 12) $filterMesList[] = str_pad((string)$mi, 2, '0', STR_PAD_LEFT);
        }
    }
}
$filterMesList = array_values(array_unique($filterMesList));
sort($filterMesList);
$fm = implode(',', $filterMesList);

$params = [
    'or' => $idOrigen,
    'page' => $page,
    'limit' => $limit,
    'filter_id' => $fi !== '' ? $fi : null,
    'filter_factura' => $ff !== '' ? $ff : null,
    'filter_beneficiario' => $fb !== '' ? $fb : null,
    'idTercero' => $ft !== '' ? $ft : null,
    'filter_empresa' => $filter_empresa !== '' ? $filter_empresa : null,
    'filter_anio' => $filter_anio !== '' ? $filter_anio : null,
    'filter_mes' => $fm !== '' ? $fm : null,
    'sort' => $_GET['sort'] ?? 'fecha',
    'dir' => $_GET['dir'] ?? 'DESC',
];
$params = array_filter($params, function ($v) {
    return $v !== null;
});

$resp = cpn_node_request(
    'GET',
    $nodeBase . '/api/gastos/generales/view?' . http_build_query($params),
    $token,
    null
);
if (!($resp['ok'] ?? false)) {
    $msg = $resp['error']['message'] ?? 'Error cargando datos';
    die($msg);
}

$view = $resp['data'] ?? [];
$config = $view['config'] ?? [];
$meta = $view['meta'] ?? [];
$OR_NAME  = $meta['nombre'] ?? '';
$OR_COLOR = $meta['colorHexa'] ?? '#000000';

$origenes = $view['origenes'] ?? [];
$empresas = $view['empresas'] ?? [];
$origines = [];
foreach ($origenes as $o) {
    if (isset($o['id'])) $origines[$o['id']] = $o;
}

$page = intval($view['page'] ?? 1);
$totalPages = intval($view['totalPages'] ?? 1);
$sort = $view['sort'] ?? 'fecha';
$dir = $view['dir'] ?? 'DESC';
$rows = $view['rows'] ?? [];
$filterOptions = $view['filterOptions'] ?? [];

$taxColumns = [];
$dedColumns = [];
$sumSubtotal = 0.0;
$sumTotal = 0.0;
foreach ($rows as &$r) {
    $taxMap = cpnParseBreakdownMap($r['impuestosDetalle'] ?? null, true);
    $dedMap = cpnParseBreakdownMap($r['deduccionesDetalle'] ?? null, false);
    $r['_taxMap'] = $taxMap;
    $r['_dedMap'] = $dedMap;
    foreach (array_keys($taxMap) as $k) $taxColumns[$k] = true;
    foreach (array_keys($dedMap) as $k) $dedColumns[$k] = true;
    $sumSubtotal += (float)($r['subtotal'] ?? 0);
    $sumTotal += (float)($r['total'] ?? 0);
}
unset($r);
$taxColumnList = array_keys($taxColumns);
$dedColumnList = array_keys($dedColumns);
sort($taxColumnList, SORT_NATURAL | SORT_FLAG_CASE);
sort($dedColumnList, SORT_NATURAL | SORT_FLAG_CASE);
$sumTaxCols = array_fill_keys($taxColumnList, 0.0);
$sumDedCols = array_fill_keys($dedColumnList, 0.0);
foreach ($rows as $r) {
    foreach ($taxColumnList as $taxCol) $sumTaxCols[$taxCol] += (float)($r['_taxMap'][$taxCol] ?? 0);
    foreach ($dedColumnList as $dedCol) $sumDedCols[$dedCol] += (float)($r['_dedMap'][$dedCol] ?? 0);
}
?>
<?php include '../templates/header.php'; ?>

<style>
    #content .container-fluid .table { font-size: 12px; }
    #content .container-fluid .table th, #content .container-fluid .table td { padding: .25rem .35rem; line-height: 1.15; }
    #content .container-fluid .form-control { font-size: 12px !important; padding: .2rem .4rem; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-3 text-gray-800">
        Contabilidad - Gastos/Compras
        <span class="badge" style="background:<?= txt($OR_COLOR) ?>;color:<?= getTextColor($OR_COLOR) ?>;"><?= txt($OR_NAME) ?></span>
    </h1>
    <p class="text-muted">Vista de solo lectura para analisis contable</p>

    <form class="row g-2 mb-4">
        <div class="col-auto">
            <select name="or" class="form-control">
                <option value="0" <?= $idOrigen === 0 ? 'selected' : '' ?>>Todos los origenes</option>
                <?php foreach ($origenes as $o): ?>
                    <option value="<?= (int)$o['id'] ?>" <?= $idOrigen === (int)$o['id'] ? 'selected' : '' ?>><?= txt($o['nombre']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-auto"><input name="filter_id" class="form-control" placeholder="No." value="<?= txt($fi) ?>"></div>
        <div class="col-auto"><input name="filter_factura" class="form-control" placeholder="Factura" value="<?= txt($ff) ?>"></div>
        <div class="col-auto">
            <select name="filter_empresa" class="form-control">
                <option value="0">Todas las empresas</option>
                <?php foreach ($empresas as $emp): ?>
                    <option value="<?= (int)$emp['id'] ?>" <?= ($filter_empresa !== '' && (int)$filter_empresa === (int)$emp['id']) ? 'selected' : '' ?>><?= txt($emp['nombre']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if (($config['filter'] ?? '') === 'select'): ?>
            <div class="col-auto">
                <select name="idTercero" class="form-control">
                    <option value="">Todos los <?= txt($config['etq'] ?? 'terceros') ?></option>
                    <?php foreach ($filterOptions as $opt): ?>
                        <option value="<?= (int)$opt['id'] ?>" <?= $ft == $opt['id'] ? 'selected' : '' ?>><?= txt($opt['etiqueta']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php else: ?>
            <div class="col-auto"><input name="filter_beneficiario" class="form-control" placeholder="Beneficiario" value="<?= txt($fb) ?>"></div>
        <?php endif; ?>

        <div class="col-auto">
            <select name="filter_anio" class="form-control" style="width:130px;">
                <option value="">Todos los anos</option>
                <?php
                $currentYear = (int)date('Y');
                for ($yy = $currentYear + 1; $yy >= 2023; $yy--) {
                    $sel = ($filter_anio !== '' && (int)$filter_anio === $yy) ? 'selected' : '';
                    echo "<option value=\"{$yy}\" {$sel}>{$yy}</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-auto">
            <select name="filter_mes[]" id="filterMes" class="form-control" multiple="multiple" style="width:250px;">
                <option value="">Todos los meses</option>
            </select>
        </div>
        <div class="col-auto">
            <select name="filter_limit" class="form-control" style="width:110px;">
                <option value="20" <?= $filter_limit === '20' ? 'selected' : '' ?>>20</option>
                <option value="50" <?= $filter_limit === '50' ? 'selected' : '' ?>>50</option>
                <option value="all" <?= $filter_limit === 'all' ? 'selected' : '' ?>>Todo</option>
            </select>
        </div>
        <div class="col-auto"><button class="btn btn-primary">Filtrar</button></div>
        <div class="col-auto"><button type="button" id="btnExportExcel" class="btn btn-success">Exportar a Excel</button></div>
        <div class="col-auto"><a href="gastos.php?or=<?= $idOrigen ?>" class="btn btn-secondary">Limpiar</a></div>
    </form>

    <div class="table-responsive mb-4">
        <table class="table table-bordered table-sm align-middle" id="tablaGastosContabilidad">
            <thead class="table-light">
                <tr>
                    <th>No.</th>
                    <th>Emp</th>
                    <th>Or</th>
                    <th class="text-center">
                        <?php
                        $nextDir = ($sort === 'fecha' && $dir === 'ASC') ? 'desc' : 'asc';
                        $arrow   = ($sort === 'fecha') ? ($dir === 'ASC' ? ' ▲' : ' ▼') : '';
                        ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['sort' => 'fecha', 'dir' => $nextDir])) ?>">Fecha<?= $arrow ?></a>
                    </th>
                    <th>Factura</th>
                    <th>No Documento</th>
                    <th>Beneficiario</th>
                    <th>Concepto</th>
                    <th class="text-right">Subtotal</th>
                    <?php foreach ($taxColumnList as $taxCol): ?>
                        <th class="text-right" style="background-color:#0d6efd;color:#fff;"><?= txt($taxCol) ?></th>
                    <?php endforeach; ?>
                    <th class="text-right">Total</th>
                    <?php foreach ($dedColumnList as $dedCol): ?>
                        <th class="text-right" style="background-color:#dc3545;color:#fff;"><?= txt($dedCol) ?></th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $selOr = (int)($r['idOrigen'] ?? 0);
                    $orColor = (string)($origines[$selOr]['colorHexa'] ?? '#ccc');
                    $bg = (string)($r['empColor'] ?? '#fff');
                    $nombreCompleto = trim(((string)($r['nombre'] ?? '')) . ' ' . ((string)($r['apellido'] ?? '')));
                    $rs = trim((string)($r['razonSocial'] ?? ''));
                    $ben = ($rs !== '' && $rs !== $nombreCompleto) ? ($nombreCompleto . " ({$rs})") : $nombreCompleto;
                ?>
                    <tr>
                        <td class="text-center"><strong><?= (int)($r['id'] ?? 0) ?></strong></td>
                        <td class="text-center" style="background:<?= txt($bg) ?>;color:<?= getTextColor($bg) ?>;"><strong><?= txt($r['sigla'] ?? '') ?></strong></td>
                        <td class="text-center"><div style="background:<?= txt($orColor) ?>;color:<?= getTextColor($orColor) ?>;padding:2px;"><?= txt($origines[$selOr]['nombre'] ?? '') ?></div></td>
                        <td class="text-center"><?= !empty($r['fecha']) ? date('d-M-y', strtotime($r['fecha'])) : '-' ?></td>
                        <td class="text-center"><strong><?= txt($r['factura'] ?: '-') ?></strong></td>
                        <td class="text-center"><?= txt($r['noDocumento'] ?? '') ?></td>
                        <td><?= txt($ben) ?></td>
                        <td><?= txt($r['conceptos'] ?? '-') ?></td>
                        <td class="text-right"><?= fmt($r['subtotal'] ?? 0) ?></td>
                        <?php foreach ($taxColumnList as $taxCol): ?>
                            <td class="text-right"><?= fmt($r['_taxMap'][$taxCol] ?? 0) ?></td>
                        <?php endforeach; ?>
                        <td class="text-right"><?= fmt($r['total'] ?? 0) ?></td>
                        <?php foreach ($dedColumnList as $dedCol): ?>
                            <td class="text-right"><?= fmt($r['_dedMap'][$dedCol] ?? 0) ?></td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <?php if ($isAllRows && count($rows) > 0): ?>
                <tfoot class="table-light font-weight-bold">
                    <tr>
                        <td colspan="8" class="text-right"><strong>TOTALES:</strong></td>
                        <td class="text-right"><strong><?= fmt($sumSubtotal) ?></strong></td>
                        <?php foreach ($taxColumnList as $taxCol): ?>
                            <td class="text-right"><strong><?= fmt($sumTaxCols[$taxCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                        <td class="text-right"><strong><?= fmt($sumTotal) ?></strong></td>
                        <?php foreach ($dedColumnList as $dedCol): ?>
                            <td class="text-right"><strong><?= fmt($sumDedCols[$dedCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                    </tr>
                </tfoot>
            <?php endif; ?>
        </table>
    </div>

    <?php if (!$isAllRows): ?>
    <nav>
        <ul class="pagination justify-content-center">
            <?php if ($page > 1): ?>
                <li class="page-item"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo;</a></li>
            <?php endif;
            $start = max(1, $page - 2);
            $end = min($totalPages, $page + 2);
            if ($start > 1): ?>
                <li class="page-item"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => 1])) ?>">1</a></li>
                <?php if ($start > 2): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
            <?php endif;
            for ($p = $start; $p <= $end; $p++):
                $act = $p == $page ? ' active' : ''; ?>
                <li class="page-item<?= $act ?>"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"><?= $p ?></a></li>
            <?php endfor;
            if ($end < $totalPages):
                if ($end < $totalPages - 1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
                <li class="page-item"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $totalPages])) ?>"><?= $totalPages ?></a></li>
            <?php endif;
            if ($page < $totalPages): ?>
                <li class="page-item"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">&raquo;</a></li>
            <?php endif; ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<?php include '../templates/footer.php'; ?>
<script>
    jQuery(function($) {
        const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        const $select = $('#filterMes');
        for (let month = 1; month <= 12; month++) {
            const mm = String(month).padStart(2, '0');
            $select.append(`<option value="${mm}">${meses[month - 1]}</option>`);
        }
        $select.select2({ placeholder: 'Seleccionar meses...', allowClear: true, width: '100%' });
        const values = <?= json_encode(array_values($filterMesList), JSON_UNESCAPED_UNICODE) ?>;
        if (Array.isArray(values) && values.length > 0) $select.val(values).trigger('change');

        function exportTableToExcel(tableId, filename) {
            const table = document.getElementById(tableId);
            if (!table) return;
            const clone = table.cloneNode(true);
            clone.querySelectorAll('button').forEach((btn) => btn.remove());
            const html = `
            <html xmlns:o="urn:schemas-microsoft-com:office:office"
                  xmlns:x="urn:schemas-microsoft-com:office:excel"
                  xmlns="http://www.w3.org/TR/REC-html40">
            <head><meta charset="UTF-8"></head>
            <body>${clone.outerHTML}</body>
            </html>`;
            const blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        $('#btnExportExcel').on('click', function() {
            const now = new Date();
            const pad = (n) => String(n).padStart(2, '0');
            const stamp = `${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`;
            exportTableToExcel('tablaGastosContabilidad', `contabilidad_gastos_${stamp}.xls`);
        });
    });
</script>
