<?php 
session_start(); 
require_once('../conexion.php'); 
require_once('../include/sesiones.php');

if (!isset($_SESSION['usu_nombre'])) {
    echo '<script>alert("Primero debes iniciar sesión para ver esta página")</script>';
    echo '<script>location.href = "index.php";</script>';
    exit;
}

// =========================
//  CONFIGURACIÓN FACTURA
// =========================
$sql = mysqli_query($con, "SELECT * FROM factura WHERE empresa='$empresa'");
$factura = mysqli_fetch_assoc($sql);
$fac_tam = $factura['fac_cm'];
$fac_msj = $factura['fac_msj'];

// =========================
//  DATOS DEL PEDIDO
// =========================
$pen_id = $_GET['pen_id'];
$propi  = isset($_GET['propi']) ? $_GET['propi'] : 'no';

$sql = mysqli_query($con, "SELECT * FROM pedido WHERE pen_id='$pen_id'");
$pedido = mysqli_fetch_assoc($sql);

$pen_comentario = $pedido['pen_comentario'];
$clie_id        = $pedido['clie_id'];
$pen_n          = $pedido['pen_n'];
$vendedor_id    = $pedido['usuario'];
$fecha_pedido   = $pedido['pen_fecha'];

// =========================
//  CLIENTE
// =========================
$sql = mysqli_query($con,"SELECT * FROM cliente WHERE clie_id='$clie_id'");
$cliente = mysqli_fetch_assoc($sql);

// =========================
//  MESA Y ZONA
// =========================
$sql = mysqli_query($con, "SELECT mesa_id FROM mesa_temp WHERE pedido_pen_id='$pen_id'");
$temp = mysqli_fetch_assoc($sql);

$sql = mysqli_query($con, "SELECT * FROM mesas WHERE mes_id='{$temp['mesa_id']}'");
$mesa = mysqli_fetch_assoc($sql);

$sql = mysqli_query($con,"SELECT * FROM zonas WHERE zon_id='{$mesa['zon_id']}' AND empresa='$empresa'");
$zona = mysqli_fetch_assoc($sql);

// =========================
//  VENDEDOR
// =========================
$sql = mysqli_query($con,"SELECT * FROM usuario WHERE usu_id='$vendedor_id'");
$vendedor = mysqli_fetch_assoc($sql);

?>
<head>
    <style type="text/css">
#receipt_wrapper{font-family:Tahoma,Geneva,sans-serif;font-size:100%;width:100%;}#receipt_header{text-align:center;}#company_name{font-weight:bold;}#company_phone{margin-bottom:15px;}#sale_time{margin-bottom:5px;}#receipt_items{position:relative;border-collapse:collapse;margin-top:15px;margin-bottom:15px;width:100%;}#receipt_items td{position:relative;padding:3px;}.short_name{display:none;}#sale_return_policy{width:80%;margin:0 auto;text-align:center;}#barcode{margin-top:10px;text-align:center;}#signature{margin-top:10px;text-align:center;font-size:72%;}#receipt_items td{font-size:100%;}#receipt_header{width:100%;}#receipt_items td{font-size:15px;}#receipt_header>div{float:inherit;}#receipt_membrete{width:40%;}#receipt_titulos{width:10%;}#receipt_cliente{width:50%;}#receipt_cliente>span,#receipt_titulos>span{display:block;overflow:hidden;width:100%;height:12px;font-size:80%;}#receipt_titulos .numero_factura{min-height:36px;height:36px;font-size:90%;}#receipt_cliente span.numero_factura{font-size:1.4em;padding-top:7px;height:29px;min-height:29px;}#observaciones,#sale_return_policy{margin-top:8px;font-size:10px;}#receipt_items td{padding:0;}#receipt_wrapper{background:white;}#receipt_items th{font-size:80%;font-weight:normal;}#receipt_items td.receipt-cell-totals-cell-line{border-top:1px solid;height:4px;}#receipt_items tr.receipt-row-totales td{font-size:97%;text-align:right;}#receipt_items tr.receipt-row-total td{font-weight:bold;}.receipt-numero-factura{font-weight:bold;}#receipt_wrapper .my-font{font-size:150%;font-weight:normal!important;}#receipt_wrapper .my-strong{font-size:106%;}#receipt_wrapper .receipt-row-cambio{text-transform:uppercase;}#receipt_wrapper .receipt-item-row td{vertical-align:middle;}.receipt-item-cell-description{width:56%;}.receipt-item-cell-price{width:24%;}.receipt-item-cell-quantity{width:16%;}.receipt-item-cell-discount{width:14%;}#receipt_wrapper.factura_small #receipt_header{font-size:90%;}
html{overflow:auto;}#receipt_header{width:100%;}#receipt_items td{font-size:15px;}#receipt_header>div{float:inherit;}#receipt_membrete{width:40%;}#receipt_titulos{width:10%;}#receipt_cliente{width:50%;}#receipt_cliente>span,#receipt_titulos>span{display:block;overflow:hidden;width:100%;height:12px;font-size:80%;}#receipt_titulos .numero_factura{min-height:36px;height:36px;font-size:90%;}#receipt_cliente span.numero_factura{font-size:1.4em;padding-top:7px;height:29px;min-height:29px;}#observaciones,#sale_return_policy{margin-top:8px;font-size:10px;}#receipt_items td{padding:0;}.wordbreak{word-break:break-all!important;}.wordtruncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.td_category span,.td_location span{width:40px!important;display:block;}.td_location span{width:30px!important;}#register_container.receiving #register_wrapper form,#register_container.sales #salesmode form{padding-top:7px;background-color:#1e5a96;padding-bottom:9px;border-radius:6px;background:linear-gradient(#205b97,#5482af,#205b97);}#register_container.sales #register_wrapper{background-color:#1e5a96;background:linear-gradient(#205b97,#5482af,#205b97);}form select{border-radius:4px;}#register_container.receiving td#register_wrapper{background:none transparent;}#register_container.sales #salesmode span{color:#fff;width:100%;text-align:center;display:block;}#register_container.sales #register_wrapper{background-color:#5582b0;background:linear-gradient(#255f99,#3f72a5,#31689f);}#register_container.sales #salesmode{height:52px;margin-top:-9px;}#suspend div span,#cancel div span{padding-top:2px;display:block;}#customer_info_shell #customer,#customer_info_shell #supplier{padding:5px 5px;}#add_customer_info a{padding:1px 5px;}#register_container.receiving #payment_types{width:146px;}[class*='pws-width-']{float:left!important;display:block!important;}.pws-width-1-4{width:25%!important;margin:0!important;}.pws-width-1-3{width:33.33%!important;margin:0!important;}.pws-width-2-4,.pws-width-1-2{width:50%!important;margin:0!important;}.my-margin-top{margin-top:25px;}.my-margin-bottom{margin-bottom:25px;}p.my-desc{padding-top:7px;}div.my-report-row:not(:first-child){padding-top:9px;border-top:1px dotted #ccc;}#pager.jPaginate a,#pager.jPaginate .jPag-current{line-height:23px;height:auto;cursor:pointer;padding:2px 5px;margin:2px;float:left;color:black;}#pager.jPaginate a:hover{background-color:#2e6da4!important;}#pager.jPaginate .jPag-current{background:transparent;color:#444!important;}#pager.jPaginate button{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px;color:#fff;background-color:#337ab7;border-color:#2e6da4;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px;height:auto;color:#fff!important;float:none;margin-right:8px;}#pager.jPaginate div>a:hover,#pager.jPaginate div>button:hover{color:#fff;background-color:#286090;border-color:#204d74;}#pager span.jPag-sprevious,#pager span.jPag-snext{display:inline-block;float:none;line-height:19px;margin-left:15px;margin-right:15px;padding-top:1px;margin-top:5px;overflow:hidden;height:18px;margin-bottom:-4px;}.ui-autocomplete{box-shadow:0px 1px 4px #333;}ul.jPag-pages{height:30px;}#content_area{min-height:800px;box-sizing:content-box;width:960px;}body.sales #content_area{width:967px;margin:0 7px;padding:20px 10px 10px 10px;background:#FFFFFF;overflow:hidden;border-radius:4px;}form fieldset{border:1px dotted #ccc;border-top:none;}form fieldset:first-child{border-top:1px dotted #ccc;}fieldset div.field_row{margin:7px;font-size:14px;font-weight:bold;padding-bottom:7px;border-bottom:1px dotted #ccc;margin-right:21px;width:274px;}fieldset div.field_row label{width:240px;padding:5px;float:left;padding-left:0;}.my-row-3>*{width:29%!important;display:block;float:left!important;padding-right:1%!important;margin-left:0!important;margin-right:0!important;padding-left:2%!important;}.my-row-1>*{width:97%!important;display:block;}.my-promo-extra-fields{float:left;margin-left:30px;}.my-promo-fieldset label{width:100%!important;display:block;}.my-promo-fieldset .form_field{float:left;}.tablesorter th i{cursor:pointer;}.modal-body form{display:block;overflow:hidden;}#TB_ajaxContent .modal-header{display:none;}#TB_ajaxContent .modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5;}#TB_ajaxContent .submit_button{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px;background-color:#337ab7;border-color:#2e6da4;color:#fff;background-color:#337ab7;border-color:#2e6da4;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px;}#customer_info_filled{background:#bde1fd;border:1px solid #ccc;border-radius:5px;width:198px;height:auto;overflow:hidden;display:block;}#customer_edit a{color:#1f5b96;}#customer_remove a{color:#b5473f;}#customer_info_filled>div{display:block;width:100%;float:left;}#customer_info_filled #customer_edit,#customer_info_filled #customer_remove{width:40%;margin-right:2%;}.my-margin-bottom-remove{margin-bottom:0!important;}.required_fields_message{font-size:80%;margin-bottom:8px;font-style:italic;}form legend{font-size:110%;}a{color:#0a549e;}a:hover{color:#0c3258;}.my-extra-links{border-top:1px dotted #ccc;padding-top:14px;}body.reports #sortable_table{font-size:100%;}body.reports #sortable_table a{color:#3298da;background:transparent;padding:3px 4px;border-radius:4px;font-weight:bold;text-shadow:1px 0 2px #fff;font-size:110%;border:1px dotted;}body.reports #sortable_table a:hover,body.reports #sortable_table a:focus{box-shadow:0px 0 1px #111;background:#fff;text-decoration:none;}body.reports .summary_row{font-size:150%;padding-bottom:5px;}body.reports .summary_row:first-child{padding-top:15px;}body.reports #item_table td{background-color:rgba(233,233,233,0.48);}body.reports #item_table .innertable td{background-color:rgba(253,253,255,0.74);}#myModal input.quantity{width:60px;text-align:right;}#myModal #item_kit_items tr td{padding:0 4px 4px 4px;}form label{font-weight:normal;}body.reports #item_table .innertable th{background:#7a9dc1;height:26px;text-shadow:0px 0 2px #1e5a96;}body.reports #content_area{width:969px;}.my-key{text-decoration:underline;}#content_area{min-height:350px;}#content_area_wrapper{min-height:480px;}#payment_types{max-width:150px;}#make_payment #tender input{width:160px;}#add_payment_text{font-size:80%;padding-left:5px;line-height:95%;}.my-red{color:#de3225!important;}.my-text-align-right{text-align:right!important;}.my-text-align-center{text-align:center!important;}.my-text-align-left{text-align:left!important;}.stock_negative{font-weight:bold;color:#de3225;}table#register td input.my-input-warning[type='text']{background-color:rgba(255,0,50,0.81);color:white;border-color:#777;}#cart_contents tr.cart_item_row>td{text-indent:0;}#cart_contents tr.cart_item_row>td>span{display:block;padding-left:5px;}#cart_contents tr.cart_item_row>td.my-text-align-right>span,td.my-text-align-right span{padding-left:3px;padding-right:5px;}#cart_contents tr.cart_item_row>td.my-text-align-center>span,td.my-text-align-center span{padding-left:3px;padding-right:3px;}.my-is-kit,.my-is-service{font-size:70%;display:inline-block;margin-top:-5px;}#TB_window .well{padding:25px;}#TB_window #my-hotkey-list{font-size:110%;}#TB_window #my-hotkey-list h4{display:block;width:100%;font-weight:normal;text-transform:uppercase;margin-bottom:5px;}#TB_window dl{display:block;overflow:hidden;}#TB_window #my-hotkey-list dl>*{display:inline-block;float:left;display:block;}#TB_window #my-hotkey-list dt{font-weight:bold;clear:left;width:75px;text-align:right;padding-right:15px;}#TB_window #my-hotkey-list dd{max-width:600px;}#home_module_list{min-height:410px;}.my-div-button{background:#86a6c7;background-image:-webkit-linear-gradient(top,#86a6c7,#1a5794);background-image:-moz-linear-gradient(top,#86a6c7,#1a5794);background-image:-ms-linear-gradient(top,#86a6c7,#1a5794);background-image:-o-linear-gradient(top,#86a6c7,#1a5794);background-image:linear-gradient(to bottom,#86a6c7,#1a5794);border-radius:4px;height:30px;width:172px;cursor:pointer;}.my-strong{font-weight:bold!important;}.my-font{font-family:Impact,Charcoal,sans-serif;}#report_summary{padding-bottom:25px;}#demo_notice{text-align:center;width:80%;margin:auto;display:block;overflow:hidden;margin-bottom:15px;margin-top:-5px;}#my_title_bar h1{font-size:160%;}#my_title_bar img{width:24px;}body.sales button:disabled,body.receivings button:disabled{box-shadow:rgba(10,10,10,0.7) 0px 0px 100px inset;opacity:0.4;}fieldset div.field_row-3{width:100%;padding:8px;}fieldset div.field_row-2{width:63%;padding:8px;}fieldset div.field_row-3 label,fieldset div.field_row-2 label{width:100%;}
</style>
</head>
<body id="salescomplete" class="my-poscol sales">
<div id="content_area_wrapper">
<div id="content_area">

<style type="text/css">
    #receipt_wrapper {
        width: <?php echo $fac_tam; ?>cm;
        background: white;
    }
</style>

<div id="receipt_wrapper">
    <div id="receipt_header">
        <?php if ($logo == 'si') { ?>
            <div id="customer"><img src="../img/<?php echo $empresa; ?>.png" style="width: <?php echo $fac_tam; ?>cm;"></div>
        <?php } else { ?>
            <div id="company_name" class="my-font"><?php echo $emp_nombre; ?></div> 
        <?php } ?>
        <div id="company_nit"><strong>NIT: <?php echo $emp_nit; ?></strong></div>
        <div id="company_address"><?php echo $emp_direccion; ?></div>
        <div id="company_phone"><?php echo $emp_telefono; ?></div>
        <div id="regimen"><?php echo $emp_regimen; ?></div>
        <div id="sale_time"><?php echo $fecha_pedido; ?></div>
    </div>

    <hr/>

    <div id="receipt_general_info">
        <div id="sale_id" class="my-strong receipt-numero-factura">Pedido Nro.# <?php echo $pen_n; ?></div>
        <div id="customer">Cliente: <?php echo $cliente['clie_nombre']; ?></div>
        <div id="customer">Documento: <?php echo $cliente['clie_cc']; ?> - Tel: <?php echo $cliente['clie_telefono']; ?></div>
        <div id="customer">Dirección: <?php echo $cliente['clie_direccion']; ?></div>
        <div id="customer">Zona: <?php echo $zona['zon_nombre']; ?> - Mesa: <?php echo $mesa['mes_nombre']; ?></div>
        <div id="employee">Vendedor: <?php echo $vendedor['usu_nombre']; ?></div>
    </div>

    <!-- TABLA DETALLES -->
    <table id="receipt_items">
        <tbody>
            <tr><td colspan="3" class="receipt-cell-totals-cell-line"></td></tr>
            <tr>
                <th class="my-text-align-left"><strong>Artículo</strong></th>
                <th class="my-text-align-left"><strong>Cant</strong></th>
                <th class="my-text-align-right"><strong>Precio</strong></th>
            </tr>
            <tr><td colspan="3" class="receipt-cell-totals-cell-line"></td></tr>

<?php
// =========================
//  DETALLE PRODUCTOS
// =========================
$suma_sabor = 0;
$sumador_total = 0;

$sql = mysqli_query($con, "SELECT * FROM pedido_detalle WHERE pedido_pen_id='$pen_id' AND pend_estado='facturado'");
while ($row = mysqli_fetch_assoc($sql)) {
    $precio_total = $row['pend_precio'] * $row['pend_cantidad'];
    $sumador_total += $precio_total;

    $sabores = mysqli_query($con, "SELECT * FROM sabores_pedido_temp WHERE pend_id='{$row['pend_id']}'");
    $sabores_array = mysqli_fetch_all($sabores, MYSQLI_ASSOC);

    $tiene_precios = false;
    foreach ($sabores_array as $sab) {
        if ($sab['precio'] > 0) { $tiene_precios = true; break; }
    }

    if (!$tiene_precios) {
        echo "<tr class='receipt-item-row'  style='border-bottom: 1px dotted #ccc;'>
                <td>{$row['pend_nombre']} (" . implode('-', array_column($sabores_array, 'sabor')) . ")</td>
                <td>{$row['pend_cantidad']}</td>
                <td class='my-text-align-right'><strong>" . number_format($precio_total, 0) . "</strong></td>
              </tr>";
    } else {
        $suma = 0;
        echo "<tr class='receipt-item-row'  '><td>{$row['pend_nombre']}<br>";
        foreach ($sabores_array as $sab) {
            echo "<small>{$sab['sabor']}</small><br>";
        }
        echo "</td><td>{$row['pend_cantidad']}<br>";
        foreach ($sabores_array as $sab) {
            echo "<small>{$sab['cantidad']}</small><br>";
        }
        echo "</td><td class='my-text-align-right'>" . number_format($precio_total, 0). "";

        foreach ($sabores_array as $sab) {
            $precio_sab = $sab['precio'] * $sab['cantidad'] * $row['pend_cantidad'];
            $suma_sabor += $precio_sab;
            $suma += $precio_sab;
            echo "<br><small>" . number_format($precio_sab, 0) . "</small>";
        }
        echo "</td></tr>";

        echo "<tr class='receipt-item-row' style='border-bottom: 1px dotted #ccc;'><td colspan='3' class='my-text-align-right'>";
        $total_gen = $suma + $precio_total;
        if ($total_gen > 0 && $row['pend_tipo'] == 'producto') {
            echo "<strong>" . number_format($total_gen, 0) . "</strong>";
        }


        echo "</td></tr>";
    }
}

// =========================
//  DETALLE COMBOS
// =========================
$sumador_total2 = 0;
$sql = mysqli_query($con,"SELECT * FROM pedido_detalle_combo WHERE pedido_pen_id='$pen_id' AND pend_estado='facturado'");
while ($row = mysqli_fetch_assoc($sql)) {
    $precio = $row['pedcom_cantidad'] * $row['pedcom_precio'];
    $sumador_total2 += $precio;
    echo "<tr>
            <td>{$row['pedcom_nombre']}</td>        
            <td>{$row['pedcom_cantidad']}</td>
            <td class='my-text-align-right'>" . number_format($precio, 0) . "</td>
          </tr>";
}

// =========================
//  ABONOS
// =========================
$suma_abonos = 0;
$sql = mysqli_query($con, "SELECT * FROM pedido_abono_temp WHERE pedido_pen_id='$pen_id'");
while($res = mysqli_fetch_assoc($sql)) {
    $suma_abonos += $res["ped_abono"];
}

// =========================
//  TOTALES
// =========================
$subtotal       = $sumador_total + $sumador_total2 + $suma_sabor;
$total_propina  = $subtotal * ($propina/100);
$total_final    = ($propi == 'si') ? ($subtotal + $total_propina - $suma_abonos) : ($subtotal - $suma_abonos);
?>
            <tr><td colspan="3" class="receipt-cell-totals-cell-line"></td></tr>
            <tr><td>Subtotal</td><td colspan="2" class="my-text-align-right"><strong>$ <?php echo number_format($subtotal,0); ?></strong></td></tr>
            <?php if ($suma_abonos > 0) { ?>
                <tr><td>Abonos</td><td colspan="2" class="my-text-align-right"><strong>$ <?php echo number_format($suma_abonos,0); ?></strong></td></tr>
            <?php } ?>
            <?php if ($propi == 'si') { ?>
                <tr><td>Propina</td><td colspan="2" class="my-text-align-right"><strong>$ <?php echo number_format($total_propina,0); ?>/<strong></td></tr>
            <?php } ?>
            <tr><td>Total</td><td colspan="2" class="my-text-align-right"><strong>$ <?php echo number_format($total_final,0); ?></strong></td></tr>
            <tr><td colspan="3" class="receipt-cell-totals-cell-line"></td></tr>
        </tbody>
    </table>

    <div><strong>Observaciones</strong><br><pre><?php echo $pen_comentario; ?></pre></div>
    <div><small><?php echo $condiciones; ?></small></div>
    <div id="sale_return_policy"><strong><h3><?php echo $fac_msj; ?></h3></strong></div>
    <div id="signature">.........................<br>Impreso por | www.vicpos.com</div>

    <button class="oculto-impresion" onclick="cerrar()" style="background:red; border:none; color:white; padding:15px; font-size:16px; width:100%;">CERRAR</button>
</div>
</div>

<script>
window.print();
function cerrar(){ window.close(); }
</script>
</body>
