<?php $__env->startSection('content'); ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <div class="container-fluid my-4">
        <!-- Header Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h1 class="h3 mb-0 text-gray-800">Dashboard Gerencial</h1>
                        <p class="text-muted mb-0">Análisis de inventario y demanda</p>
                    </div>
                    <div class="text-right">
                        <small class="text-muted">Última actualización: <?php echo e(now()->format('d/m/Y H:i')); ?></small>
                    </div>
                </div>
            </div>
        </div>

        <?php if(Auth::user()->id != 7 || Auth::user()->id != 9): ?>
            <!-- Analytics Section -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-success text-light">
                            <h5 class="mb-0" style="color:white;"><i class="fas fa-chart-line me-2"></i>Análisis Gráfico</h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-lg-3 col-md-6">
                                    <a href="http://analytics.laravelrp.com/public/question/d36e9671-e3d1-41e5-95fc-4c1205e48f80"
                                        target="_blank" class="btn btn-outline-primary btn-lg w-100 h-100 d-flex flex-column justify-content-center">
                                        <i class="fas fa-boxes fa-2x mb-2"></i>
                                        <span>Inventario</span>
                                    </a>
                                </div>
                                <div class="col-lg-3 col-md-6">
                                    <a href="http://analytics.laravelrp.com/public/question/af527514-eccf-4389-af89-e6a618fb1788"
                                        target="_blank" class="btn btn-outline-success btn-lg w-100 h-100 d-flex flex-column justify-content-center">
                                        <i class="fas fa-chart-area fa-2x mb-2"></i>
                                        <span>Demanda</span>
                                    </a>
                                </div>
                                <div class="col-lg-3 col-md-6">
                                    <a href="http://analytics.laravelrp.com/public/question/fd405e1a-bbe0-4ddb-966b-ae7bfa4a8014"
                                        target="_blank" class="btn btn-outline-info btn-lg w-100 h-100 d-flex flex-column justify-content-center">
                                        <i class="fas fa-calendar-alt fa-2x mb-2"></i>
                                        <span>Facturación Mensual</span>
                                    </a>
                                </div>
                                <div class="col-lg-3 col-md-6">
                                    <a href="http://analytics.laravelrp.com/public/question/3bc7b2c4-51d8-4f01-bf99-7248ff978b36"
                                        target="_blank" class="btn btn-outline-warning btn-lg w-100 h-100 d-flex flex-column justify-content-center">
                                        <i class="fas fa-trending-up fa-2x mb-2"></i>
                                        <span>Crecimiento</span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Current Week Report -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-gradient-primary text-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="mb-0"><i class="fas fa-clipboard-list me-2"></i>Requerimiento de Materia Prima</h4>
                                    <small class="opacity-75">Semana actual - <?php echo e(now()->format('W/Y')); ?></small>
                                </div>
                                <div class="badge bg-light text-dark fs-6">
                                    <i class="fas fa-calendar-week me-1"></i><?php echo e(now()->format('d/m/Y')); ?>

                                </div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table id="example2" class="table table-hover mb-0" style="width:100%">
                                    <thead class="table-dark">
                                        <tr>
                                            <th class="border-0"><i class="fas fa-tag me-2"></i>DESCRIPCIÓN DE MATERIA PRIMA</th>
                                            <th class="border-0 text-center"><i class="fas fa-arrow-up me-2"></i>DEMANDA (KGS)</th>
                                            <th class="border-0 text-center"><i class="fas fa-warehouse me-2"></i>INVENTARIO (KGS)</th>
                                            <th class="border-0 text-center"><i class="fas fa-calculator me-2"></i>DIFERENCIA</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                            $total_demanda = 0;
                                            $total_inventario = 0;
                                            $total_diferencia = 0;
                                        ?>
                                        <?php $__currentLoopData = $materias; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $materia): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php
                                                $diferencia = floatval($materia->inventario) - floatval($materia->demanda);
                                            ?>
                                            <tr class="align-middle">
                                                <td class="fw-medium">
                                                    <div class="d-flex align-items-center">
                                                        <div class="bg-light rounded-circle p-2 me-3">
                                                            <i class="fas fa-industry text-primary"></i>
                                                        </div>
                                                        <?php echo e($materia->descripcion); ?>

                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <a href="#" class="demanda-link btn btn-link p-0 text-decoration-none fw-bold"
                                                        data-keywords='<?php echo json_encode($materia->keywords, 15, 512) ?>'
                                                        title="Ver detalle de demanda">
                                                        <span class="badge bg-info-subtle text-info fs-6">
                                                            <?php echo e(number_format(floatval($materia->demanda), 2, '.', ',')); ?>

                                                        </span>
                                                    </a>
                                                </td>
                                                <td class="text-center">
                                                    <a href="#" class="inventario-link btn btn-link p-0 text-decoration-none fw-bold"
                                                        data-keywords='<?php echo json_encode($materia->keywords, 15, 512) ?>'
                                                        title="Ver detalle de inventario">
                                                        <span class="badge bg-secondary-subtle text-secondary fs-6">
                                                            <?php echo e(number_format(floatval($materia->inventario), 2, '.', ',')); ?>

                                                        </span>
                                                    </a>
                                                </td>
                                                <td class="text-center">
                                                    <span class="badge fs-6 <?php echo e($diferencia < 0 ? 'bg-danger' : 'bg-success'); ?>">
                                                        <i class="fas <?php echo e($diferencia < 0 ? 'fa-arrow-down' : 'fa-arrow-up'); ?> me-1"></i>
                                                        <?php echo e(number_format($diferencia, 2, '.', ',')); ?>

                                                    </span>
                                                </td>
                                            </tr>
                                            <?php
                                                $total_demanda += floatval($materia->demanda);
                                                $total_inventario += floatval($materia->inventario);
                                                $total_diferencia += $diferencia;
                                            ?>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </tbody>
                                    <tfoot class="table-light border-top border-2">
                                        <tr class="fw-bold">
                                            <td class="py-3">
                                                <i class="fas fa-calculator me-2"></i>TOTAL GENERAL
                                            </td>
                                            <td class="text-center py-3">
                                                <span class="badge bg-info fs-6"><?php echo e(number_format($total_demanda, 2, '.', ',')); ?></span>
                                            </td>
                                            <td class="text-center py-3">
                                                <span class="badge bg-secondary fs-6"><?php echo e(number_format($total_inventario, 2, '.', ',')); ?></span>
                                            </td>
                                            <td class="text-center py-3">
                                                <span class="badge fs-6 <?php echo e($total_diferencia < 0 ? 'bg-danger' : 'bg-success'); ?>">
                                                    <i class="fas <?php echo e($total_diferencia < 0 ? 'fa-exclamation-triangle' : 'fa-check-circle'); ?> me-1"></i>
                                                    <?php echo e(number_format($total_diferencia, 2, '.', ',')); ?>

                                                </span>
                                            </td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Historical Data Section -->
            <div class="row">
                <div class="col-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-success">
                            <h4 class="mb-0" style="color: white;"><i class="fas fa-history me-2"></i>Historial de Requerimientos</h4>
                            <small class="opacity-75" style="color: white;">Datos históricos por año y semana</small>
                        </div>
                        <div class="card-body">
                            <?php $__currentLoopData = $historial_requerimientos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $year => $weeks): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="accordion mb-3" id="accordion-historial-<?php echo e($year); ?>">
                                    <div class="accordion-item border-0 shadow-sm">
                                        <h2 class="accordion-header" id="heading-historial-<?php echo e($year); ?>">
                                            <button class="accordion-button collapsed bg-light fw-bold" type="button"
                                                    data-bs-toggle="collapse" data-bs-target="#collapse-historial-<?php echo e($year); ?>"
                                                    aria-expanded="false" aria-controls="collapse-historial-<?php echo e($year); ?>">
                                                <i class="fas fa-calendar-alt me-3 text-primary"></i>
                                                <span class="fs-5">Año <?php echo e($year); ?></span>
                                                <span class="badge bg-primary ms-2"><?php echo e(count($weeks)); ?> semanas</span>
                                            </button>
                                        </h2>
                                        <div id="collapse-historial-<?php echo e($year); ?>" class="accordion-collapse collapse"
                                            aria-labelledby="heading-historial-<?php echo e($year); ?>"
                                            data-bs-parent="#accordion-historial-<?php echo e($year); ?>">
                                            <div class="accordion-body bg-light">
                                                <div class="accordion" id="accordion-weeks-<?php echo e($year); ?>">
                                                    <?php $__currentLoopData = $weeks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $week => $historials): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <div class="accordion-item border mb-2">
                                                            <h2 class="accordion-header" id="heading-week-<?php echo e($year); ?>-<?php echo e($week); ?>">
                                                                <button class="accordion-button collapsed" type="button"
                                                                        data-bs-toggle="collapse"
                                                                        data-bs-target="#collapse-week-<?php echo e($year); ?>-<?php echo e($week); ?>"
                                                                        aria-expanded="false"
                                                                        aria-controls="collapse-week-<?php echo e($year); ?>-<?php echo e($week); ?>">
                                                                    <i class="fas fa-calendar-week me-2 text-success"></i>
                                                                    Semana <?php echo e($week); ?>

                                                                    <span class="badge bg-secondary ms-2 text-light" style="color: white !important;"><?php echo e(count($historials)); ?> registros</span>
                                                                </button>
                                                            </h2>
                                                            <div id="collapse-week-<?php echo e($year); ?>-<?php echo e($week); ?>"
                                                                class="accordion-collapse collapse"
                                                                aria-labelledby="heading-week-<?php echo e($year); ?>-<?php echo e($week); ?>"
                                                                data-bs-parent="#accordion-weeks-<?php echo e($year); ?>">
                                                                <div class="accordion-body p-0">
                                                                    <div class="table-responsive">
                                                                        <table class="table table-hover mb-0">
                                                                            <thead class="table-dark">
                                                                                <tr>
                                                                                    <th>DESCRIPCIÓN DE MATERIA PRIMA</th>
                                                                                    <th class="text-center">DEMANDA (KGS)</th>
                                                                                    <th class="text-center">INVENTARIO (KGS)</th>
                                                                                    <th class="text-center">DIFERENCIA</th>
                                                                                </tr>
                                                                            </thead>
                                                                            <tbody>
                                                                                <?php
                                                                                    $total_demanda = 0;
                                                                                    $total_inventario = 0;
                                                                                    $total_diferencia = 0;
                                                                                ?>
                                                                                <?php $__currentLoopData = $historials; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $registro): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                    <?php
                                                                                        $diferencia = floatval($registro->inventario) - floatval($registro->demanda);
                                                                                    ?>
                                                                                    <tr class="align-middle">
                                                                                        <td>
                                                                                            <div class="d-flex align-items-center">
                                                                                                <div class="bg-light rounded-circle p-1 me-2">
                                                                                                    <i class="fas fa-industry text-muted"></i>
                                                                                                </div>
                                                                                                <?php echo e($registro->descripcion_producto); ?>

                                                                                            </div>
                                                                                        </td>
                                                                                        <td class="text-center">
                                                                                            <span class="badge bg-info-subtle text-info">
                                                                                                <?php echo e(number_format(floatval($registro->demanda), 2, '.', ',')); ?>

                                                                                            </span>
                                                                                        </td>
                                                                                        <td class="text-center">
                                                                                            <span class="badge bg-secondary-subtle text-secondary">
                                                                                                <?php echo e(number_format(floatval($registro->inventario), 2, '.', ',')); ?>

                                                                                            </span>
                                                                                        </td>
                                                                                        <td class="text-center">
                                                                                            <span class="badge <?php echo e($diferencia < 0 ? 'bg-danger' : 'bg-success'); ?>">
                                                                                                <?php echo e(number_format($diferencia, 2, '.', ',')); ?>

                                                                                            </span>
                                                                                        </td>
                                                                                    </tr>
                                                                                    <?php
                                                                                        $total_demanda += floatval($registro->demanda);
                                                                                        $total_inventario += floatval($registro->inventario);
                                                                                        $total_diferencia += $diferencia;
                                                                                    ?>
                                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                            </tbody>
                                                                            <tfoot class="table-light border-top">
                                                                                <tr class="fw-bold">
                                                                                    <td><i class="fas fa-calculator me-2"></i>TOTAL</td>
                                                                                    <td class="text-center">
                                                                                        <span class="badge bg-info"><?php echo e(number_format($total_demanda, 2, '.', ',')); ?></span>
                                                                                    </td>
                                                                                    <td class="text-center">
                                                                                        <span class="badge bg-secondary"><?php echo e(number_format($total_inventario, 2, '.', ',')); ?></span>
                                                                                    </td>
                                                                                    <td class="text-center">
                                                                                        <span class="badge <?php echo e($total_diferencia < 0 ? 'bg-danger' : 'bg-success'); ?>">
                                                                                            <?php echo e(number_format($total_diferencia, 2, '.', ',')); ?>

                                                                                        </span>
                                                                                    </td>
                                                                                </tr>
                                                                            </tfoot>
                                                                        </table>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Enhanced Modal -->
        <div class="modal fade" id="detalleModal" tabindex="-1" role="dialog" aria-labelledby="detalleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header bg-primary text-light">
                        <h5 class="modal-title" id="detalleModalLabel">
                            <i class="fas fa-info-circle me-2"></i>Detalle
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0">
                        <div id="detalleTableContainer" class="table-responsive"></div>
                    </div>
                    <div class="modal-footer bg-light">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-2"></i>Cerrar
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $('#example2').DataTable({
                "order": [
                    [1, "desc"]
                ],
                responsive: true,
                dom: 'Bfrtip',
                buttons: [{
                    extend: 'excel',
                    title: 'reporte_inventario',
                    filename: 'reporte_inventario',
                    className: 'btn btn-success'
                }]
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            // Función para procesar la respuesta y mostrar el detalle en el modal
            function mostrarDetalle(tituloModal, tableHtml) {
                $('#detalleModalLabel').text(tituloModal);
                $('#detalleTableContainer').html(tableHtml);
                $('#detalleModal').modal('show');
            }

            // Handler para demanda
            $('.demanda-link').click(function(e) {
                e.preventDefault();
                let keywords = $(this).data('keywords');
                // Se envían los keywords como query parameter en formato JSON
                let url = "<?php echo e(route('inventario.demanda_detalle')); ?>?keywords=" + encodeURIComponent(JSON
                    .stringify(keywords));

                Swal.fire({
                    title: 'Cargando detalle de demanda...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                fetch(url, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Error en la respuesta del servidor');
                        }
                        return response.json();
                    })
                    .then(data => {
                        Swal.close();
                        // Construir la tabla para detalle de demanda
                        let tableHtml =
                            '<table id="tabla-demanda-detalle" class="table table-bordered table-striped">';
                        tableHtml += '<thead><tr>';
                        tableHtml += '<th>Orden ID</th>';
                        tableHtml += '<th>Producto</th>';
                        tableHtml += '<th>Cantidad Pedida</th>';
                        tableHtml += '<th>Cantidad Fabricada</th>';
                        tableHtml += '<th>Pendiente de Fabricar</th>';
                        tableHtml += '<th>Factor Conversión</th>';
                        tableHtml += '<th>Total KGS Procesar</th>';
                        tableHtml += '</tr></thead><tbody>';

                        if (data.length > 0) {
                            data.forEach(item => {
                                tableHtml += '<tr>';
                                tableHtml += '<td>' + item.orden_id + '</td>';
                                tableHtml += '<td>' + item.producto + '</td>';
                                tableHtml += '<td>' + item.cantidad_total + '</td>';
                                tableHtml += '<td>' + item.total_parcialidades + '</td>';
                                tableHtml += '<td>' + parseFloat(item.cantidad_total - item
                                    .total_parcialidades).toFixed(2) + '</td>';
                                tableHtml += '<td>' + item.factor_conversion + '</td>';
                                tableHtml += '<td>' + parseFloat(item.Total_KGS_Procesar)
                                    .toFixed(2) + '</td>';
                                tableHtml += '</tr>';
                            });
                        } else {
                            tableHtml +=
                                '<tr><td colspan="6" class="text-center">No se encontraron registros</td></tr>';
                        }
                        tableHtml += '</tbody></table>';

                        mostrarDetalle('Detalle de Demanda', tableHtml);

                        // Inicializar DataTable
                        // $('#tabla-demanda-detalle').DataTable({
                        //     responsive: true,
                        //     dom: 'Bfrtip',
                        //     buttons: [{
                        //         extend: 'excel',
                        //         title: 'detalle_demanda',
                        //         filename: 'detalle_demanda',
                        //         className: 'btn btn-success'
                        //     }]
                        // });
                    })
                    .catch(error => {
                        Swal.fire('Error', error.message, 'error');
                    });
            });

            // Handler para inventario
            $('.inventario-link').click(function(e) {
                e.preventDefault();
                let keywords = $(this).data('keywords');
                let url = "<?php echo e(route('inventario.detalle')); ?>?keywords=" + encodeURIComponent(JSON
                    .stringify(keywords));

                Swal.fire({
                    title: 'Cargando detalle de inventario...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                fetch(url, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Error en la respuesta del servidor');
                        }
                        return response.json();
                    })
                    .then(data => {
                        Swal.close();
                        // Construir la tabla para detalle de inventario
                        let tableHtml =
                            '<table id="tabla-inventario-detalle" class="table table-bordered table-striped">';
                        tableHtml += '<thead><tr>';
                        tableHtml += '<th>Producto</th>';
                        tableHtml += '<th>Bobinas</th>';
                        tableHtml += '<th>Total Kilos</th>';
                        tableHtml += '</tr></thead><tbody>';

                        if (data.length > 0) {
                            data.forEach(item => {
                                tableHtml += '<tr>';
                                tableHtml += '<td>' + item.nombre + '</td>';
                                tableHtml += '<td>' + parseFloat(item.total_por_producto / item
                                        .factor_conversion ?? 1)
                                    .toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '</td>';
                                tableHtml += '<td>' + parseFloat(item.total_por_producto)
                                    .toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '</td>';
                                tableHtml += '</tr>';
                            });
                        } else {
                            tableHtml +=
                                '<tr><td colspan="2" class="text-center">No se encontraron registros</td></tr>';
                        }
                        tableHtml += '</tbody></table>';

                        mostrarDetalle('Detalle de Inventario', tableHtml);

                        // Inicializar DataTable
                        // $('#tabla-inventario-detalle').DataTable({
                        //     responsive: true,
                        //     dom: 'Bfrtip',
                        //     buttons: [{
                        //         extend: 'excel',
                        //         title: 'detalle_inventario',
                        //         filename: 'detalle_inventario',
                        //         className: 'btn btn-success'
                        //     }]
                        // });
                    })
                    .catch(error => {
                        Swal.fire('Error', error.message, 'error');
                    });
            });
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('reportes.menu', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/devpwg5/laravelrp.com/resources/views/reportes/gerencia/dashboard-gerencia.blade.php ENDPATH**/ ?>