<?php /* ============================================================
   ARCHIVO: application/views/produccion/costos/hojas_ver.php
   ============================================================ */
$c = $costo;
$h = $c->hoja;
$p = $c->producto;
?>
<div class="content-wrapper">
    <section class="content-header">
        <h1>
            Hoja de Costos
            <small><?php echo htmlspecialchars($p->nombre); ?>
                <?php if($h->nombre): ?> — <em><?php echo htmlspecialchars($h->nombre); ?></em><?php endif; ?>
            </small>
        </h1>
    </section>

    <section class="content">

        <?php if($this->session->flashdata('success')): ?>
            <div class="alert alert-success"><?php echo $this->session->flashdata('success'); ?></div>
        <?php endif; ?>
        <?php if($this->session->flashdata('error')): ?>
            <div class="alert alert-danger"><?php echo $this->session->flashdata('error'); ?></div>
        <?php endif; ?>

        <div class="row" style="margin-bottom:10px;">
            <div class="col-md-12">
                <a href="<?php echo base_url('index.php/produccion/costos/hojas'); ?>" class="btn btn-default btn-sm">
                    <i class="fa fa-arrow-left"></i> Volver
                </a>
                <?php if(tiene_permiso('costos_hoja_crear')): ?>
                <a href="<?php echo base_url('index.php/produccion/costos/hojas/create/'.$p->id); ?>" class="btn btn-info btn-sm">
                    <i class="fa fa-copy"></i> Nueva variante
                </a>
                <?php endif; ?>
                <code class="pull-right" style="font-size:13px;line-height:30px;"><?php echo $p->codigo; ?></code>
            </div>
        </div>

        <!-- Info boxes resumen -->
        <div class="row">
            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-aqua">
                    <span class="info-box-icon"><i class="fa fa-cube"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Insumos</span>
                        <span class="info-box-number">S/ <?php echo number_format($c->sub_insumos, 4); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:<?php echo $c->pct_insumos; ?>%"></div></div>
                        <span class="progress-description"><?php echo $c->pct_insumos; ?>% del total</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-green">
                    <span class="info-box-icon"><i class="fa fa-cogs"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Proc. Propios</span>
                        <span class="info-box-number">S/ <?php echo number_format($c->sub_propios, 4); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:<?php echo $c->pct_propios; ?>%"></div></div>
                        <span class="progress-description"><?php echo $c->pct_propios; ?>% del total</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="info-box" style="background:#8e44ad;color:#fff;">
                    <span class="info-box-icon"><i class="fa fa-truck"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Tercerizado</span>
                        <span class="info-box-number">S/ <?php echo number_format($c->sub_tercerizado, 4); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:<?php echo $c->pct_tercerizado; ?>%"></div></div>
                        <span class="progress-description"><?php echo $c->pct_tercerizado; ?>% del total</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-yellow">
                    <span class="info-box-icon"><i class="fa fa-building"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">G. Fijos</span>
                        <span class="info-box-number">S/ <?php echo number_format($c->sub_gastos, 4); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:<?php echo $c->pct_gastos; ?>%"></div></div>
                        <span class="progress-description"><?php echo $c->pct_gastos; ?>% del total</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Costo total callout -->
        <div class="callout callout-info">
            <h4>
                <i class="fa fa-calculator"></i>
                Costo Total por Unidad:
                <strong style="font-size:1.5em; margin-left:10px;">S/ <?php echo number_format($c->costo_total, 4); ?></strong>
            </h4>
        </div>

        <div class="row">

            <!-- ====================================================
                 COLUMNA IZQUIERDA: Insumos + Gastos Fijos
                 ==================================================== -->
            <div class="col-md-6">

                <!-- INSUMOS -->
                <div class="panel panel-primary">
                    <div class="panel-heading"><i class="fa fa-cube"></i> <strong>Insumos / Materias Primas</strong></div>
                    <div class="panel-body" style="padding:0;">
                        <table class="table table-condensed table-hover" style="margin:0;">
                            <thead>
                                <tr>
                                    <th>Insumo</th>
                                    <th class="text-center">Cant.</th>
                                    <th class="text-center">Rend.</th>
                                    <th class="text-right">P. Unit.</th>
                                    <th class="text-right">C. Unit.</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($c->insumos)): ?>
                                <tr><td colspan="6" class="text-center text-muted" style="padding:12px;">Sin insumos asignados</td></tr>
                                <?php else: ?>
                                <?php foreach($c->insumos as $ins): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($ins->insumo_nombre); ?> <small class="text-muted">(<?php echo $ins->um_abreviado; ?>)</small></td>
                                    <td class="text-center"><?php echo $ins->cantidad; ?></td>
                                    <td class="text-center"><?php echo $ins->rendimiento; ?></td>
                                    <td class="text-right">S/ <?php echo number_format($ins->precio_unitario, 4); ?></td>
                                    <td class="text-right"><strong>S/ <?php echo number_format($ins->costo_calc, 4); ?></strong></td>
                                    <td>
                                        <?php if(tiene_permiso('costos_hoja_crear')): ?>
                                        <a href="<?php echo base_url('index.php/produccion/costos/hoja/quitar_insumo/'.$ins->id.'/'.$h->id); ?>"
                                           class="btn btn-danger btn-xs"
                                           onclick="return confirm('¿Quitar este insumo?')">
                                            <i class="fa fa-times"></i>
                                        </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="active">
                                    <td colspan="4"><strong>Subtotal insumos</strong></td>
                                    <td class="text-right"><strong>S/ <?php echo number_format($c->sub_insumos, 4); ?></strong></td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <?php if(tiene_permiso('costos_hoja_crear')): ?>
                    <div class="panel-footer">
                        <form action="<?php echo base_url('index.php/produccion/costos/hoja/agregar_insumo/'.$h->id); ?>" method="post">
                            <div class="row">
                                <div class="col-sm-4">
                                    <select name="insumo_id" class="form-control input-sm" required>
                                        <option value="">-- Insumo --</option>
                                        <?php foreach($todos_insumos as $ti): ?>
                                        <option value="<?php echo $ti->id; ?>"><?php echo htmlspecialchars($ti->nombre); ?> (<?php echo $ti->um_abreviado; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-sm-2">
                                    <input type="number" name="cantidad" step="0.0001" min="0.0001" class="form-control input-sm" placeholder="Cant." value="1" required>
                                </div>
                                <div class="col-sm-2">
                                    <input type="number" name="rendimiento" step="0.0001" min="0.0001" class="form-control input-sm" placeholder="Rend." value="1" required title="Unidades del producto que salen de 1 unidad del insumo">
                                </div>
                                <div class="col-sm-2">
                                    <input type="text" name="notas" class="form-control input-sm" placeholder="Nota">
                                </div>
                                <div class="col-sm-2">
                                    <button type="submit" class="btn btn-primary btn-sm btn-block"><i class="fa fa-plus"></i> Agregar</button>
                                </div>
                            </div>
                            <small class="text-muted"><i class="fa fa-info-circle"></i> Rendimiento: cuántas unidades del producto salen de 1 unidad del insumo. Ej: 1 resma → 12 cajas = Rend. 12</small>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- GASTOS FIJOS -->
                <div class="panel panel-warning">
                    <div class="panel-heading">
                        <i class="fa fa-building"></i> <strong>Gastos Fijos</strong>
                        <a href="<?php echo base_url('index.php/produccion/costos/gastos_fijos'); ?>" class="btn btn-xs btn-default pull-right"><i class="fa fa-cog"></i> Configurar</a>
                    </div>
                    <div class="panel-body" style="padding:0;">
                        <table class="table table-condensed table-hover" style="margin:0;">
                            <thead><tr><th>Gasto</th><th>Tipo</th><th>Valor</th><th class="text-right">C. Unit.</th><th></th></tr></thead>
                            <tbody>
                                <?php if(empty($c->gastos)): ?>
                                <tr><td colspan="5" class="text-center text-muted" style="padding:12px;">Sin gastos asignados</td></tr>
                                <?php else: ?>
                                <?php foreach($c->gastos as $g): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($g->gasto_nombre); ?></td>
                                    <td><?php echo $g->tipo_asignacion === 'MONTO' ? '<span class="label label-default">S/ fijo</span>' : '<span class="label label-info">%</span>'; ?></td>
                                    <td><?php echo $g->tipo_asignacion === 'MONTO' ? 'S/ '.number_format($g->valor,4) : $g->valor.'%'; ?></td>
                                    <td class="text-right"><strong>S/ <?php echo number_format($g->costo_calc, 4); ?></strong></td>
                                    <td>
                                        <?php if(tiene_permiso('costos_hoja_crear')): ?>
                                        <a href="<?php echo base_url('index.php/produccion/costos/hoja/quitar_gasto/'.$g->id.'/'.$h->id); ?>" class="btn btn-danger btn-xs" onclick="return confirm('¿Quitar?')"><i class="fa fa-times"></i></a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="active">
                                    <td colspan="3"><strong>Subtotal gastos fijos</strong></td>
                                    <td class="text-right"><strong>S/ <?php echo number_format($c->sub_gastos, 4); ?></strong></td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <?php if(tiene_permiso('costos_hoja_crear')): ?>
                    <div class="panel-footer">
                        <form action="<?php echo base_url('index.php/produccion/costos/hoja/agregar_gasto/'.$h->id); ?>" method="post">
                            <div class="row">
                                <div class="col-sm-4">
                                    <select name="gasto_fijo_id" class="form-control input-sm" required>
                                        <option value="">-- Gasto fijo --</option>
                                        <?php foreach($todos_gastos as $tg): ?>
                                        <option value="<?php echo $tg->id; ?>"><?php echo htmlspecialchars($tg->nombre); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-sm-3">
                                    <select name="tipo_asignacion" class="form-control input-sm">
                                        <option value="MONTO">S/ fijo por unidad</option>
                                        <option value="PORCENTAJE">% sobre costos variables</option>
                                    </select>
                                </div>
                                <div class="col-sm-3">
                                    <input type="number" name="valor" step="0.0001" min="0" class="form-control input-sm" placeholder="Valor" required>
                                </div>
                                <div class="col-sm-2">
                                    <button type="submit" class="btn btn-warning btn-sm btn-block"><i class="fa fa-plus"></i> Agregar</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>

            </div><!-- /col-md-6 izquierda -->

            <!-- ====================================================
                 COLUMNA DERECHA: Procesos + Simulador
                 ==================================================== -->
            <div class="col-md-6">

                <!-- PROCESOS -->
                <div class="panel panel-success">
                    <div class="panel-heading"><i class="fa fa-cogs"></i> <strong>Procesos Productivos</strong></div>
                    <div class="panel-body" style="padding:0;">
                        <table class="table table-condensed table-hover" style="margin:0;">
                            <thead><tr><th>Proceso</th><th>Tipo</th><th>Parámetro</th><th>Flete</th><th class="text-right">C. Unit.</th><th></th></tr></thead>
                            <tbody>
                                <?php if(empty($c->procesos)): ?>
                                <tr><td colspan="6" class="text-center text-muted" style="padding:12px;">Sin procesos asignados</td></tr>
                                <?php else: ?>
                                <?php foreach($c->procesos as $proc): ?>
                                <tr>
                                    <td>
                                        <?php echo htmlspecialchars($proc->proceso_nombre); ?>
                                        <?php if($proc->es_tercerizado): ?><span class="label" style="background:#8e44ad;color:#fff;font-size:10px;">Terc.</span><?php endif; ?>
                                    </td>
                                    <td><?php echo $proc->tipo_costo === 'HORA' ? '<span class="label label-info">Hora</span>' : '<span class="label label-default">Lote</span>'; ?></td>
                                    <td>
                                        <?php if($proc->tipo_costo === 'HORA'): ?>
                                            <?php echo $proc->minutos; ?> min
                                        <?php else: ?>
                                            S/<?php echo number_format($proc->costo_lote_override ?? $proc->costo_base, 2); ?>/<?php echo number_format($proc->lote_cantidad); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $proc->incluye_flete ? '<small class="text-muted">+S/'.number_format($proc->flete_calc,4).'</small>' : '—'; ?></td>
                                    <td class="text-right"><strong>S/ <?php echo number_format($proc->costo_total_calc, 4); ?></strong></td>
                                    <td>
                                        <?php if(tiene_permiso('costos_hoja_crear')): ?>
                                        <a href="<?php echo base_url('index.php/produccion/costos/hoja/quitar_proceso/'.$proc->id.'/'.$h->id); ?>" class="btn btn-danger btn-xs" onclick="return confirm('¿Quitar?')"><i class="fa fa-times"></i></a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="active"><td colspan="4"><strong>Subtotal procesos propios</strong></td><td class="text-right"><strong>S/ <?php echo number_format($c->sub_propios, 4); ?></strong></td><td></td></tr>
                                <tr class="active"><td colspan="4"><strong>Subtotal tercerizado</strong></td><td class="text-right"><strong>S/ <?php echo number_format($c->sub_tercerizado, 4); ?></strong></td><td></td></tr>
                            </tfoot>
                        </table>
                    </div>
                    <?php if(tiene_permiso('costos_hoja_crear')): ?>
                    <div class="panel-footer">
                        <form action="<?php echo base_url('index.php/produccion/costos/hoja/agregar_proceso/'.$h->id); ?>" method="post" id="form-proc">
                            <div class="row">
                                <div class="col-sm-5">
                                    <select name="proceso_id" id="sel-proceso" class="form-control input-sm" required>
                                        <option value="">-- Proceso --</option>
                                        <?php foreach($todos_procesos as $tp): ?>
                                        <option value="<?php echo $tp->id; ?>"
                                                data-tipo="<?php echo $tp->tipo_costo; ?>"
                                                data-tercerizado="<?php echo $tp->es_tercerizado; ?>">
                                            <?php echo htmlspecialchars($tp->nombre); ?>
                                            (<?php echo $tp->tipo_costo === 'HORA' ? 'Hora' : 'Lote x'.number_format($tp->lote_cantidad); ?>)
                                            <?php echo $tp->es_tercerizado ? '★' : ''; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-sm-2" id="campo-minutos">
                                    <input type="number" name="minutos" step="0.01" min="0.01" class="form-control input-sm" placeholder="Minutos">
                                </div>
                                <div class="col-sm-3" id="campo-lote-ov" style="display:none;">
                                    <input type="number" name="costo_lote_override" step="0.01" class="form-control input-sm" placeholder="Costo lote (opc.)">
                                </div>
                                <div class="col-sm-2">
                                    <button type="submit" class="btn btn-success btn-sm btn-block"><i class="fa fa-plus"></i> Agregar</button>
                                </div>
                            </div>
                            <!-- Flete (solo para tercerizados) -->
                            <div id="bloque-flete" style="display:none; margin-top:8px; padding:8px; background:#f9f0ff; border:1px dashed #c39bd3; border-radius:4px;">
                                <label><input type="checkbox" name="incluye_flete" id="chk-flete"> Incluir flete de recojo</label>
                                <div id="campos-flete" style="display:none; margin-top:6px;">
                                    <div class="row">
                                        <div class="col-sm-4"><input type="number" name="costo_flete" step="0.01" class="form-control input-sm" placeholder="S/ flete total"></div>
                                        <div class="col-sm-4"><input type="number" name="flete_lote_qty" class="form-control input-sm" placeholder="Cant. del lote" value="1000"></div>
                                        <div class="col-sm-4"><small class="text-muted">S/ flete ÷ cant. = costo x unidad</small></div>
                                    </div>
                                </div>
                            </div>
                            <div style="margin-top:6px;">
                                <input type="text" name="notas" class="form-control input-sm" placeholder="Nota (opcional)">
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- SIMULADOR DE PRECIO -->
                <div class="panel panel-default">
                    <div class="panel-heading"><i class="fa fa-tag"></i> <strong>Simulador de Precio de Venta</strong></div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-sm-3">
                                <label>Costo total</label>
                                <div style="font-size:18px; font-weight:700; color:#2c3e50;">S/ <?php echo number_format($c->costo_total, 4); ?></div>
                            </div>
                            <div class="col-sm-3">
                                <label>Margen (%)</label>
                                <input type="number" id="sim-margen" class="form-control" value="30" min="0" step="1">
                            </div>
                            <div class="col-sm-3">
                                <label>Precio sugerido</label>
                                <div id="sim-precio" style="font-size:20px; font-weight:700; color:#27ae60;">S/ 0.00</div>
                            </div>
                            <div class="col-sm-3">
                                <label>Ganancia unit.</label>
                                <div id="sim-ganancia" style="font-size:18px; font-weight:700; color:#e67e22;">S/ 0.00</div>
                            </div>
                        </div>
                        <?php if($p->precio_unidad > 0): ?>
                        <hr>
                        <small class="text-muted">
                            <i class="fa fa-info-circle"></i>
                            Precio actual en sistema: <strong>S/ <?php echo number_format($p->precio_unidad, 4); ?></strong>
                            &rarr; Margen real:
                            <?php $mr = $c->costo_total > 0 ? round(($p->precio_unidad - $c->costo_total) / $p->precio_unidad * 100, 1) : 0; ?>
                            <strong class="<?php echo $mr >= 0 ? 'text-success' : 'text-danger'; ?>"><?php echo $mr; ?>%</strong>
                        </small>
                        <?php endif; ?>
                    </div>
                </div>

            </div><!-- /col-md-6 derecha -->

        </div><!-- /row -->

    </section>
</div>

<script>
// Simulador
var costoBase = <?php echo (float)$c->costo_total; ?>;
function calcSim() {
    var m = parseFloat(document.getElementById('sim-margen').value) || 0;
    var precio = costoBase * (1 + m / 100);
    document.getElementById('sim-precio').textContent   = 'S/ ' + precio.toFixed(4);
    document.getElementById('sim-ganancia').textContent = 'S/ ' + (precio - costoBase).toFixed(4);
}
document.getElementById('sim-margen').addEventListener('input', calcSim);
calcSim();

// Campos dinámicos según tipo de proceso
document.getElementById('sel-proceso').addEventListener('change', function() {
    var opt  = this.options[this.selectedIndex];
    var tipo = opt.getAttribute('data-tipo');
    var terc = opt.getAttribute('data-tercerizado');
    document.getElementById('campo-minutos').style.display  = (tipo === 'HORA') ? '' : 'none';
    document.getElementById('campo-lote-ov').style.display  = (tipo === 'LOTE') ? '' : 'none';
    document.getElementById('bloque-flete').style.display   = (terc === '1')    ? '' : 'none';
});

// Checkbox flete
document.getElementById('chk-flete').addEventListener('change', function() {
    document.getElementById('campos-flete').style.display = this.checked ? '' : 'none';
});
</script>
