<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';

header('Location: /productos/inventarios.php');
exit;

include __DIR__ . '/../templates/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Proveedores &raquo; Inventarios</h1>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">Sincronización</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-sm" id="tablaProveedoresInv" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Proveedor</th>
                            <th>Última ejecución</th>
                            <th>Estado</th>
                            <th>Registros</th>
                            <th>Mensaje</th>
                            <th class="text-center">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr data-provider="marpico">
                            <td>Marpico</td>
                            <td class="col-fecha">—</td>
                            <td class="col-estado">—</td>
                            <td class="col-total">—</td>
                            <td class="col-msg">—</td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary btn-ejecutar">Ejecutar</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="mt-3">
                <div class="d-flex align-items-center justify-content-between mb-1">
                    <label class="small text-muted mb-0">Progreso</label>
                    <span id="progressText" class="small text-muted">—</span>
                </div>
                <div class="progress" style="height: 18px;">
                    <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                </div>

                <label class="small text-muted mb-1">Salida</label>
                <pre id="out" class="small" style="white-space: pre-wrap;">—</pre>
            </div>
        </div>
    </div>
</div>

<script>
    (function() {
        function setRowLoading($tr, loading) {
            $tr.find('.btn-ejecutar').prop('disabled', !!loading);
            $tr.toggleClass('table-warning', !!loading);
        }

        function renderStatusRow($tr, data) {
            const last = data?.lastImport || null;
            $tr.find('.col-fecha').text(last?.fechaInicioFmt || '—');
            $tr.find('.col-estado').text(last?.estado || '—');
            $tr.find('.col-total').text((last?.totalRegistros ?? '—'));
            $tr.find('.col-msg').text(last?.mensajeError || '');
        }

        function loadStatus(provider) {
            const $tr = $('#tablaProveedoresInv tr[data-provider="' + provider + '"]');
            return $.getJSON('/proveedores/api/inventarios.php', {
                action: 'status',
                provider
            }).done(resp => {
                if (!resp || resp.ok !== true) {
                    $('#out').text(resp?.error?.message || 'No se pudo cargar estado.');
                    return;
                }
                renderStatusRow($tr, resp.data);
            }).fail(() => {
                $('#out').text('No se pudo cargar estado.');
            });
        }

        function setProgress(percent, text) {
            const p = Math.max(0, Math.min(100, Number(percent || 0)));
            $('#progressBar')
                .css('width', p + '%')
                .attr('aria-valuenow', String(p))
                .text(p + '%');
            $('#progressText').text(text || '—');
        }

        function loadProgress(provider) {
            return $.getJSON('/proveedores/api/inventarios.php', {
                action: 'progress',
                provider
            }).done(resp => {
                if (!resp || resp.ok !== true) return;
                const p = resp.data || {};
                const percent = (p.percent ?? 0);
                const stage = p.stage || '';
                const msg = p.message || '';
                const running = !!p.running;
                const finished = !!p.finished;
                const ok = (typeof p.ok === 'boolean') ? p.ok : null;

                if (!running && !finished && !stage && !msg) {
                    return;
                }

                const suffix = running ? ' (en ejecución)' : (finished ? (ok ? ' (OK)' : ' (ERROR)') : '');
                const text = (stage ? stage : 'Progreso') + suffix + (msg ? (': ' + msg) : '');
                setProgress(percent, text);
            });
        }

        function runSync(provider) {
            const $tr = $('#tablaProveedoresInv tr[data-provider="' + provider + '"]');
            setRowLoading($tr, true);
            $('#out').text('Iniciando…');
            setProgress(0, 'Iniciando…');

            let pollTimer = null;

            function startPolling() {
                if (pollTimer) clearInterval(pollTimer);
                pollTimer = setInterval(() => {
                    loadProgress(provider);
                    loadStatus(provider);
                }, 5000);

                // stop after 10 minutes
                setTimeout(() => {
                    if (pollTimer) {
                        clearInterval(pollTimer);
                        pollTimer = null;
                    }
                }, 10 * 60 * 1000);
            }

            $.post('/proveedores/api/inventarios.php', {
                action: 'run',
                provider
            }, null, 'json').done(resp => {
                if (!resp || resp.ok !== true) {
                    $('#out').text(resp?.error?.message || 'Error ejecutando sincronización.');
                    return;
                }
                if (resp?.data?.started) {
                    $('#out').text('Sync iniciado. Actualizando estado…');
                    loadProgress(provider);
                    startPolling();
                } else {
                    $('#out').text(JSON.stringify(resp.data, null, 2));
                }
            }).fail(() => {
                $('#out').text('Error ejecutando sincronización.');
            }).always(() => {
                setRowLoading($tr, false);
                loadStatus(provider);
            });
        }

        $(function() {
            loadStatus('marpico');
            loadProgress('marpico');

            $('#tablaProveedoresInv').on('click', '.btn-ejecutar', function() {
                const $tr = $(this).closest('tr');
                const provider = $tr.data('provider');
                runSync(provider);
            });
        });
    })();
</script>

<?php include __DIR__ . '/../templates/footer.php';
