<div class="content-wrapper">
    <section class="content-header">
        <h1>Reporte de Stock</h1>
    </section>

    <section class="content">

        <!-- ============================================================ -->
        <!-- CABECERA SOLO PARA IMPRESIÓN -->
        <!-- ============================================================ -->
        <div id="cabeceraImpresion" class="print-only">
            <table style="width:100%; border:none; margin-bottom:10px;">
                <tr>
                    <td style="width:90px; vertical-align:top; border:none;">
                        <?php if(!empty($empresa->logo)): ?>
                            <img src="<?php echo base_url('uploads/empresa/'.$empresa->logo); ?>" style="max-width:80px; max-height:80px;">
                        <?php endif; ?>
                    </td>
                    <td style="vertical-align:top; border:none;">
                        <div style="font-size:15px; font-weight:bold;"><?php echo !empty($empresa->nombre) ? $empresa->nombre : ''; ?></div>
                        <div style="font-size:11px; color:#555;">RUC: <?php echo !empty($empresa->ruc) ? $empresa->ruc : ''; ?></div>
                        <div style="font-size:11px; color:#555;"><?php echo !empty($empresa->direccion_fiscal) ? $empresa->direccion_fiscal : ''; ?></div>
                    </td>
                    <td style="text-align:right; vertical-align:top; border:none;">
                        <div style="font-size:16px; font-weight:bold; text-transform:uppercase;">Reporte de Stock</div>
                        <div style="font-size:11px; color:#555;">Emitido: <?php echo $fecha_reporte; ?></div>
                        <div style="font-size:11px; color:#555;">
                            <?php if($almacen_id): ?>
                                Almacén:
                                <?php
                                    foreach($almacenes as $a) {
                                        if ($a->id == $almacen_id) { echo $a->nombre; break; }
                                    }
                                ?>
                            <?php else: ?>
                                Almacén: Todos
                            <?php endif; ?>
                            &nbsp;|&nbsp;
                            <?php if($categoria_id): ?>
                                Categoría:
                                <?php
                                    foreach($categorias as $c) {
                                        if ($c->id == $categoria_id) { echo $c->nombre; break; }
                                    }
                                ?>
                            <?php else: ?>
                                Categoría: Todas
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            </table>
            <hr style="margin:6px 0 12px; border-top:2px solid #333;">
        </div>

        <!-- FILTROS -->
        <div class="row no-print" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-12">
                <div class="panel panel-primary">
                    <div class="panel-heading"><strong><i class="fa fa-filter"></i> Filtros</strong></div>
                    <div class="panel-body">
                        <form method="get" action="<?php echo base_url('index.php/almacen/stock'); ?>">
                            <div class="row">
                                <div class="col-md-3 form-group">
                                    <label>Almacén</label>
                                    <select name="almacen_id" class="form-control">
                                        <option value="">Todos los almacenes</option>
                                        <?php foreach($almacenes as $item): ?>
                                            <option value="<?php echo $item->id; ?>"
                                                <?php echo ($almacen_id == $item->id) ? 'selected' : ''; ?>>
                                                <?php echo $item->nombre; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 form-group">
                                    <label>Categoría</label>
                                    <select name="categoria_id" class="form-control">
                                        <option value="">Todas las categorías</option>
                                        <?php foreach($categorias as $item): ?>
                                            <option value="<?php echo $item->id; ?>"
                                                <?php echo ($categoria_id == $item->id) ? 'selected' : ''; ?>>
                                                <?php echo $item->nombre; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group" style="padding-top:25px;">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fa fa-search"></i> Filtrar
                                    </button>
                                    <a href="<?php echo base_url('index.php/almacen/stock'); ?>" class="btn btn-default">
                                        <i class="fa fa-refresh"></i>
                                    </a>
                                </div>
                                <div class="col-md-4 form-group" style="padding-top:25px;">
                                    <button type="button" onclick="window.print()" class="btn btn-default pull-right">
                                        <i class="fa fa-print"></i> Imprimir
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- LEYENDA -->
        <div class="row no-print" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-12">
                <div style="margin-bottom:10px;">
                    <span class="label label-danger" style="font-size:12px; padding:5px 10px;">
                        <i class="fa fa-arrow-down"></i> Stock bajo mínimo
                    </span>
                    &nbsp;
                    <span class="label label-warning" style="font-size:12px; padding:5px 10px;">
                        <i class="fa fa-exclamation-triangle"></i> Stock en punto de reposición
                    </span>
                    &nbsp;
                    <span class="label label-success" style="font-size:12px; padding:5px 10px;">
                        <i class="fa fa-check"></i> Stock normal
                    </span>
                    &nbsp;
                    <span class="label label-info" style="font-size:12px; padding:5px 10px;">
                        <i class="fa fa-arrow-up"></i> Stock sobre máximo
                    </span>
                </div>
            </div>
        </div>

        <!-- LEYENDA IMPRESIÓN -->
        <div class="print-only" style="margin-bottom:8px; font-size:9px;">
            <strong>Leyenda:</strong>
            <span style="border:1px solid #999; padding:2px 6px;">Bajo mínimo</span>
            <span style="border:1px solid #999; padding:2px 6px;">Reponer</span>
            <span style="border:1px solid #999; padding:2px 6px;">Normal</span>
            <span style="border:1px solid #999; padding:2px 6px;">Sobre máximo</span>
        </div>

        <!-- TABLA -->
        <div class="row" style="margin-bottom:5px !important;">
            <div class="col-md-12">
                <div class="panel panel-default reporte-panel">
                    <div class="panel-heading no-print">
                        <strong>Listado de productos</strong>
                        <span class="badge pull-right"><?php echo count($stock); ?> productos</span>
                    </div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table id="tablaStock" class="table table-bordered table-hover table-striped tabla-reporte">
                                <thead>
                                    <tr>
                                        <th>Código</th>
                                        <th>Producto</th>
                                        <th>Categoría</th>
                                        <th>Almacén</th>
                                        <th class="text-center">Und.</th>
                                        <th class="text-right">Stock Mín.</th>
                                        <th class="text-right">Stock Actual</th>
                                        <th class="text-right">Stock Máx.</th>
                                        <th class="text-right">P. Reposición</th>
                                        <th class="text-right">P. Promedio</th>
                                        <th class="text-right">Valor Stock</th>
                                        <th class="text-center">Estado</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($stock as $item): ?>
                                        <?php
                                            $stockActual    = (float)$item->cantidad_stock;
                                            $stockMin       = (float)$item->cantidad_minima;
                                            $stockMax       = (float)$item->cantidad_maxima;
                                            $stockRepos     = (float)$item->cantidad_reposicion;
                                            $precioPromedio = (float)$item->precio_promedio;
                                            $valorStock     = round($stockActual * $precioPromedio, 2);

                                            if ($stockActual <= $stockMin && $stockMin > 0) {
                                                $rowClass    = 'danger';
                                                $badgeClass  = 'label-danger';
                                                $badgeIcon   = 'fa-arrow-down';
                                                $badgeText   = 'Bajo mínimo';
                                            } elseif ($stockRepos > 0 && $stockActual <= $stockRepos) {
                                                $rowClass    = 'warning';
                                                $badgeClass  = 'label-warning';
                                                $badgeIcon   = 'fa-exclamation-triangle';
                                                $badgeText   = 'Reponer';
                                            } elseif ($stockMax > 0 && $stockActual > $stockMax) {
                                                $rowClass    = 'info';
                                                $badgeClass  = 'label-info';
                                                $badgeIcon   = 'fa-arrow-up';
                                                $badgeText   = 'Sobre máximo';
                                            } else {
                                                $rowClass    = '';
                                                $badgeClass  = 'label-success';
                                                $badgeIcon   = 'fa-check';
                                                $badgeText   = 'Normal';
                                            }
                                        ?>
                                        <tr class="<?php echo $rowClass; ?>">
                                            <td><?php echo $item->codigo; ?></td>
                                            <td><?php echo $item->producto; ?></td>
                                            <td><?php echo $item->categoria ?? '-'; ?></td>
                                            <td><?php echo $item->almacen; ?></td>
                                            <td class="text-center"><?php echo $item->unidad ?? '-'; ?></td>
                                            <td class="text-right"><?php echo number_format($stockMin, 2); ?></td>
                                            <td class="text-right"><strong><?php echo number_format($stockActual, 2); ?></strong></td>
                                            <td class="text-right"><?php echo $stockMax > 0 ? number_format($stockMax, 2) : '-'; ?></td>
                                            <td class="text-right"><?php echo $stockRepos > 0 ? number_format($stockRepos, 2) : '-'; ?></td>
                                            <td class="text-right"><?php echo number_format($precioPromedio, 4); ?></td>
                                            <td class="text-right"><?php echo number_format($valorStock, 2); ?></td>
                                            <td class="text-center">
                                                <span class="label <?php echo $badgeClass; ?>">
                                                    <i class="fa <?php echo $badgeIcon; ?>"></i>
                                                    <?php echo $badgeText; ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <?php if(!empty($stock)): ?>
                                <tfoot>
                                    <tr style="font-weight:bold; background:#f9f9f9;">
                                        <th colspan="10" class="text-right">Total valor en stock:</th>
                                        <th class="text-right">
                                            <?php
                                                $totalValor = 0;
                                                foreach($stock as $item) {
                                                    $totalValor += (float)$item->cantidad_stock * (float)$item->precio_promedio;
                                                }
                                                echo number_format($totalValor, 2);
                                            ?>
                                        </th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- PIE DE PÁGINA SOLO IMPRESIÓN -->
        <div class="print-only" style="margin-top:15px; font-size:10px; color:#888; text-align:center; border-top:1px solid #ccc; padding-top:6px;">
            Reporte generado el <?php echo $fecha_reporte; ?> — <?php echo !empty($empresa->nombre) ? $empresa->nombre : ''; ?>
        </div>

    </section>
</div>

<style>
/* ============================================================ */
/* ESTILOS DE PANTALLA */
/* ============================================================ */
.print-only { display: none; }

/* ============================================================ */
/* ESTILOS DE IMPRESIÓN — REPORTE APAISADO */
/* ============================================================ */
@media print {

    @page {
        size: A4 landscape;
        margin: 10mm;
    }

    .main-header, .sidebar, .content-header, .main-footer,
    .no-print, .control-sidebar, .navbar,
    .dataTables_filter, .dataTables_length, .dataTables_paginate, .dataTables_info {
        display: none !important;
    }

    .content-wrapper {
        margin-left: 0 !important;
        padding: 0 !important;
    }

    .print-only { display: block !important; }

    .reporte-panel {
        border: 1px solid #999 !important;
        box-shadow: none !important;
        margin-bottom: 8px !important;
    }

    .tabla-reporte {
        font-size: 9px;
    }
    .tabla-reporte th, .tabla-reporte td {
        padding: 3px 4px !important;
    }
    .tabla-reporte thead tr,
    .tabla-reporte tfoot tr {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }

    tr.danger  td { background-color: #f9d6d5 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    tr.warning td { background-color: #fdf3d0 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    tr.info    td { background-color: #d3edf7 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }

    .label {
        border: 1px solid #999;
        background: #fff !important;
        color: #000 !important;
    }
}
</style>

<script>
window.addEventListener('load', function () {
    $('#tablaStock').css('visibility', 'hidden');

    $('#tablaStock').DataTable({
        language: {
            lengthMenu:   "Mostrar _MENU_ registros",
            zeroRecords:  "No se encontraron productos",
            info:         "Mostrando _START_ al _END_ de _TOTAL_ registros",
            infoEmpty:    "Sin registros",
            infoFiltered: "(filtrado de _MAX_ registros)",
            search:       "Buscar:",
            paginate: { first: "Primero", last: "Último", next: "Siguiente", previous: "Anterior" }
        },
        pageLength: 25,
        order: [[1, 'asc']],
        columnDefs: [
            { orderable: false, targets: [11] }
        ],
        initComplete: function() {
            $('#tablaStock').css('visibility', 'visible');
        }
    });

});
</script>