<?php use_helper( 'UrlFunctions' ); ?>
<?php use_helper( 'UtilFunctions' ); ?>
<?php use_helper( 'IncludePartial' ); ?>

<script type="text/javascript">
saveForm = function()
{
    x = confirm( "Esta seguro de guardar el formulario?" );
    if( x )
    {
        calcularSumaTotal();
        var strFormSerialize = $( 'form' ).serialize();
        //pr( strFormSerialize );
        //return false;
        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'item/guardarPromocion', "" ) ?>", 
            strFormSerialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                <?php if( $s_TipoProc == "nvo" ){ ?>
                location.href = "<?=buildUrl( 'item/listPromo', "TipoProc=upd&Id="  )?>" + o_json.id;
                <?php }else{ ?>
                parent.findControl();
                parent.closeWindow( 'dialog' );
                <?php } ?>
            } 
        );
    }
    return false;
}

despublicarPackPromo = function()
{
    x = confirm( "Esta seguro de quitar la publicacion?" );
    if( x )
    {
        var strFormSerialize = $( 'form' ).serialize();
        
        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'item/despublicarPackPromocion', "" ) ?>", 
            strFormSerialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                <?php if( $s_TipoProc == "nvo" ){ ?>
                location.href = "<?=buildUrl( 'item/listPromo', "TipoProc=upd&Id="  )?>" + o_json.id;
                <?php }else{ ?>
                parent.findControl();
                parent.closeWindow( 'dialog' );
                <?php } ?>
            } 
        );
    }
    return false;
}
    
</script>

<div class="shadow-sm p-3 mb-2 bg-white rounded card card-body">
    <div class="row">
        <div class="col mb-1">
            <h4 class="text-info text-nowrap mb-0"><?=$s_Titulo?></h4>
        </div>
    </div>
</div>

<div id="content_alert" style=""></div>

<div class="card">
    
    <form class="was-validated" name="form1" id="form1" method="POST" action="" onsubmit="return saveForm();">
        <input type="hidden" name="Id" id="Id" value="<?=$s_Id?>">
        <input type="hidden" name="TipoProc" id="TipoProc" value="<?=$s_TipoProc?>">
        <input type="hidden" name="IdAlmacen" id="IdAlmacen" value="ALM00002">

        <div class="form-row mx-0">
            <div class="col-md-6 mb-1">
                <label class="col-form-label" for="IdItemTipo">Tipo</label>
                <select class="form-control" name="IdItemTipo" id="IdItemTipo" onchange="configuracionImputs(this);" required>
                    <option value=""> - Seleccione - </option>
                    <?php foreach( ALM_ItemTipoFN::selectActivos( array( "IngenieriaFlag"=>1 ) )  as $o_ALM_ItemTipoBN ){ ?>
                        <option value="<?=$o_ALM_ItemTipoBN->getIdItemTipo()?>" <?php if( $o_ObjectBN->getIdItemTipo() == $o_ALM_ItemTipoBN->getIdItemTipo() ){ echo "SELECTED"; } ?> > <?=$o_ALM_ItemTipoBN->getDescripcionLocal()?> </option>
                    <?php } ?>
                </select>
            </div>
            <div class="col-md-6 mb-1">
                &nbsp;
            </div>
        </div>

        <div class="form-row mx-0">
            <div class="col-md-4 mb-1">
                <label class="col-form-label" for="DescripcionPromo">Descripci&oacute;n</label>
                <input type="text" class="form-control" name="DescripcionPromo" id="DescripcionPromo" placeholder="" value="<?=$o_ObjectBN->getDescripcionPromo()?>" required>
            </div>
            <div class="col-md-4 mb-1">
                <label class="col-form-label" for="FechaInicio">Fecha Desde</label>
                <div class="input-group mb-2">
                    <div class="input-group-prepend">
                        <div class="input-group-text"><?=addImgButton( "calendar.png", array( "class"=>"", "height"=>24 ) )?></div>
                    </div>
                    <input type="text" class="form-control text-center" id="FechaInicio" name="FechaInicio" placeholder="Fecha Desde" value="<?=$o_ObjectBN->getFechaInicio()?>">
                    <script type="text/javascript">
                    $( "#FechaInicio" ).datepicker( { dateFormat: "yy-mm-dd", changeYear:true, yearRange: "-0:+1", changeMonth: true, onClose: function (){ this.focus(); } } );
                    </script>
                </div>
            </div>
            <div class="col-md-4 mb-1">
                <label class="col-form-label" for="FechaFin">Fecha Hasta</label>
                <div class="input-group mb-2">
                    <div class="input-group-prepend">
                        <div class="input-group-text"><?=addImgButton( "calendar.png", array( "class"=>"", "height"=>24 ) )?></div>
                    </div>
                    <input type="text" class="form-control text-center" id="FechaFin" name="FechaFin" placeholder="Fecha Desde" value="<?=$o_ObjectBN->getFechaFin()?>">
                    <script type="text/javascript">
                    $( "#FechaFin" ).datepicker( { dateFormat: "yy-mm-dd", changeYear:true, yearRange: "-0:+1", changeMonth: true, onClose: function (){ this.focus(); } } );
                    </script>
                </div>
            </div>
        </div>

        <div class="form-row mx-0">
            <div class="col-md-6 mb-1">
                <label class="col-form-label" for="CantidadPromo">Cantidad</label>
                <input type="text" class="form-control" name="CantidadPromo" id="CantidadPromo" placeholder="" value="<?=$o_ObjectBN->getCantidadPromo()?>" onblur="" required>
            </div>
            <div class="col-md-6 mb-1">
                <label class="col-form-label" for="PrecioPromo">Precio Inc IGV</label>
                <input type="text" class="form-control" name="PrecioPromo" id="PrecioPromo" placeholder="" value="<?=$o_ObjectBN->getPrecioConIGVPromo()?>" required>
            </div>
        </div>

        <?php if( $o_ObjectBN->getIdPromoCab() ){ ?>

            <div class="dropdown-divider" style="border-top: 1px solid #8c8b8b;"></div>

            <div class="form-row mx-0">            
                <div class="col-md-6 mb-1">
                    <label class="col-form-label" for="EstadoPromo">Estado Promocion</label>
                    <select class="form-control" name="EstadoPromo" id="EstadoPromo">
                        <option value=""> Seleccione </option>
                        <option value="PE" <?php if( $o_ObjectBN->getEstadoPromo()=="PE" ){ echo "SELECTED"; } ?> > PENDIENTE </option>
                        <option value="PU" <?php if( $o_ObjectBN->getEstadoPromo()=="PU" ){ echo "SELECTED"; } ?> > PUBLICAR PROMOCION </option>
                        <option value="CA" <?php if( $o_ObjectBN->getEstadoPromo()=="CA" ){ echo "SELECTED"; } ?> > CANCELAR PROMOCION </option>
                    </select>
                </div>
            </div>

        <?php } ?>

        <div class="dropdown-divider" style="border-top: 1px solid #8c8b8b;"></div>

        <?php if( $s_TipoProc != "shw" ){ ?>
        <div class="col mb-1 text-right">
            <button id="btnAgregarCom" type="button" class="btn btn-primary">Agregar Comentario</button>
            <button id="btnAgregar" type="button" class="btn btn-primary">Agregar Item</button>
        </div>
        <?php } ?>

        <script type="text/javascript">
        $( "#btnAgregarCom" )
        .click
        (
            function()
            {
                $( "#content_nvo" ).append( $( "#content_copy_nvo" ).html() );
                //$( "#content_nvo tr:last input:first" ).focus();

                $( "#content_nvo tr:last" ).find( "input[name='IdItem[]']" ).prop( 'readonly', true );
                $( "#content_nvo tr:last" ).find( "input[name='Descripcion[]']" ).prop( 'readonly', false );
                $( "#content_nvo tr:last" ).find( "input[name='Descripcion[]']" ).keypress( function( ){ return true; } );

                $( "#content_nvo tr:last" ).find( "input[name='Descripcion[]']" ).focus();
            }
        );
        $( "#btnAgregar" )
        .click
        (
            function()
            {
                openPopup();
                //$( "#content_nvo" ).append( $( "#content_copy_nvo" ).html() );
                //$( "#content_nvo tr:last input:first" ).focus();
            }
        );
        </script>
        
        <div class="table-responsive" id="content_grid">
            <table class="table table-bordered table-hover"> <!-- table-sm -->
                <thead>
                    <tr>
                        <th scope="col" class="text-center table-primary">Cod Item</th>
                        <th scope="col" class="text-center table-primary">Descripcion</th>
                        <th scope="col" class="text-center table-primary">Costo</th>
                        <th scope="col" class="text-center table-primary">Cantidad</th>
                        <th scope="col" class="text-center table-primary">Precio Uni</th>
                        <th scope="col" class=" table-primary"></th>
                    </tr>
                </thead>
                <tbody id="content_nvo">
                    <?php $f_SumaPromocion = 0; ?>
                    <?php if( $o_ObjectBN->getIdPromoCab() ){ ?>
                        <?php if( $o_ObjectBN->getCantRegItemPromocion() ){ ?>
                            
                            <?php foreach ( $o_ObjectBN->getArrayItemPromocion() as $key => $o_MKT_ItemPromocionBN ) { ?>
                                <?php
                                $s_ReadOnlyIdItem      = 'readonly=""';
                                $s_ReadOnlyDescripcion = 'readonly=""';
                                $s_ReadOnlyCosto       = 'readonly=""';
                                $s_ReadOnlyPrecio      = 'readonly=""';
                                if( $o_MKT_ItemPromocionBN->getTipoDetalle() == "C" )
                                {
                                    $s_ReadOnlyDescripcion = '';
                                }
                                ?>
                            <tr>
                                <td><input type="text" class="form-control" name="IdItem[]" id="IdItem_<?=$key?>" value="<?=$o_MKT_ItemPromocionBN->getIdItem()?>" <?=$s_ReadOnlyIdItem?> ></td>
                                <td class="text-center"><input type="text" class="form-control" name="Descripcion[]" id="Descripcion_<?=$key?>" value="<?=$o_MKT_ItemPromocionBN->getDescripcionItem()?>" <?=$s_ReadOnlyDescripcion?> ></td>

                                <td class="text-center"><input type="text" class="form-control text-right" name="CostoConIGV[]" id="CostoConIGV_<?=$key?>" value="<?=$o_MKT_ItemPromocionBN->getCostoConIGV()?>" <?=$s_ReadOnlyCosto?> ></td>
                                <td class="text-center"><input type="text" class="form-control text-right" name="Cantidad[]" id="Cantidad_<?=$key?>" value="<?=$o_MKT_ItemPromocionBN->getCantidad()?>" onfocus="this.select()" ></td>
                                <td class="text-center"><input type="text" class="form-control text-right" name="PrecioConIGV[]" id="PrecioConIGV_<?=$key?>" value="<?=$o_MKT_ItemPromocionBN->getPrecioConIGV()?>" <?=$s_ReadOnlyPrecio?> ></td>

                                <td style="vertical-align: middle; text-align: center;">
                                    <?php if( $s_TipoProc != "shw" ){ ?>
                                    <input type="hidden" name="CostoSinIGV[]" value="<?=$o_MKT_ItemPromocionBN->getCostoSinIGV()?>">
                                    <input type="hidden" name="CostoConIGV[]" value="<?=$o_MKT_ItemPromocionBN->getCostoConIGV()?>">

                                    <input type="hidden" name="PrecioSinIGV[]" value="<?=$o_MKT_ItemPromocionBN->getPrecioSinIGV()?>">
                                    <input type="hidden" name="MontoIGV[]" value="<?=$o_MKT_ItemPromocionBN->getMontoIGV()?>">

                                    <button class="btn" title="" onclick="eliminarLinea( this );"> <img src="<?=getUrlImage( "btnDelete.gif" )?>" title="Eliminar" onclick="" style="cursor:pointer"> </button>
                                    <?php } ?>
                                </td>
                            </tr>
                                <?php $f_SumaPromocion = $f_SumaPromocion + $o_MKT_ItemPromocionBN->getPrecioConIGV() ?>
                            <?php } ?>
                        <?php } ?>
                    <?php } ?>
                </tbody>

                <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td style="text-align: right;"><b>TOTAL:</b></td>
                        <td  class="text-center">
                            <input type="hidden" name="SumaMontoSubTotal" id="SumaMontoSubTotal" value="<?=$o_ObjectBN->getPrecioSinIGVPromo()?>">
                            <input type="hidden" name="SumaMontoIGV" id="SumaMontoIGV" value="<?=$o_ObjectBN->getMontoIGVPromo()?>">
                            <input type="text" class="form-control text-right" name="SumaMontoTotal" id="SumaMontoTotal" value="<?=$f_SumaPromocion?>" readonly="">
                        </td>
                        <td style=""></td>
                    </tr>
                </tbody>
            </table>
        </div>        

        <div class="dropdown-divider" style="border-top: 1px solid #8c8b8b;"></div>

        <div class="form-group col-14"><hr style="border-top: 1px solid #8c8b8b;"></div>

        <div class="form-row mx-0" >
            <div class="col-md-6 mb-1">
                <?php if( $s_TipoProc == "nvo" ){ ?>
                <button type="button" class="btn btn-primary btn-lg btn-block" onclick="location.href='<?php echo buildUrl( 'item/listPromo', '' ) ?>'">CANCELAR</button>
            <?php }else{ ?>
                <button type="button" class="btn btn-primary btn-lg btn-block" onclick="parent.closeWindow('dialog');">CANCELAR</button>
            <?php } ?>
            </div>
            <?php if( $s_TipoProc != "shw" ){ ?>
            <div class="col-md-6 mb-1">
                <button type="submit" class="btn btn-primary btn-lg btn-block" onclick="">GRABAR Y SALIR</button>
            </div>
            <?php } ?>
            <?php if( $s_TipoProc != "upd" ){ ?>
                <?php if( $o_ObjectBN->getEstadoPromo() == "PU" ){ ?>
            <div class="col-md-6 mb-1">
                <button type="button" class="btn btn-primary btn-lg btn-block" onclick="despublicarPackPromo();">DESPUBLICAR</button>
            </div>
                <?php } ?>
            <?php } ?>
        </div>
    </form>
</div>

<div style="display: none;">
    <table>
        <tbody id="content_copy_nvo">
            <tr>
                <td><input type="text" class="form-control" name="IdItem[]" onfocus="this.select()" onblur="buscarInfoItem( this );" ></td>
                <td><input type="text" class="form-control text-left" name="Descripcion[]" title="" onkeypress="" readonly=""></td>
                <td><input type="text" class="form-control text-right" name="CostoConIGV[]" onkeypress="return false;" readonly=""></td>
                <td><input type="text" class="form-control text-center" name="Cantidad[]" value="1" onkeypress="" min="1" data-bind="value:replyNumber" onblur="actualizarPrecio( this );" onfocus="this.select()"></td>
                <td><input type="text" class="form-control text-right" name="PrecioConIGV[]" onkeypress="return false;" readonly=""></td>
                <td style="vertical-align: middle; text-align: center;">
                    <input type="hidden" name="CostoSinIGV[]" value="">
                    <input type="hidden" name="PrecioSinIGV[]" value="">
                    <input type="hidden" name="MontoIGV[]" value="">
                    <button class="btn" title="" onclick="eliminarLinea( this );"> <img src="<?=getUrlImage( "btnDelete.gif" )?>" title="Eliminar" onclick="" style="cursor:pointer"> </button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<?=crearFuentePopupIframe( array( "div_id"=>"dialog", "iframe_id"=>"myIframe", "popup_title"=>"Buscar Item", "popup_width"=>"700", "popup_height"=>"400", "modal"=>true ) )?>

<script type="text/javascript">
actualizarPrecio = function( elm_sel )
{
    var cantidad = parseInt( elm_sel.value );
    var costo    = parseFloat( $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='CostoConIGV[]']" ).val() );


    pr( cantidad * costo );
}

configuracionImputs = function( elm )
{
    if( $( elm ).val() == "06" )
    {
        $( "#FechaInicio" ).prop( "disabled", true );
        $( "#FechaFin" ).prop( "disabled", true );
    }
    if( $( elm ).val() == "05" )
    {
        $( "#FechaInicio" ).prop( "disabled", false );
        $( "#FechaFin" ).prop( "disabled", false );
    }
}  

openPopup = function()
{
    var s_param = "empresa/" + $( "#IdCompania" ).val() + "/IdAlmacen/" + $( "#IdAlmacen" ).val() + "/type/0";
    $( '#myIframe' ).attr( 'src', '<?=buildUrlComplet( 'alm.php/transacciones/listItem' )?>' + s_param );
    $( '#dialog' ).dialog( 'open' );
}

eliminarLinea = function( elm )
{
    //pr( "ingresa para eliminar linea" );
    $( $( elm ).closest( 'tr' ) ).remove();
    calcularSumaTotal();
}

asignarItem = function( id_item, descripcion_item, unidad_item )
{
    $( "#content_nvo" ).append( $( "#content_copy_nvo" ).html() );
    //$( "#content_nvo tr:last input:first" ).focus();
    $( "#content_nvo tr:last input:first" ).val( id_item );
    $( "#content_nvo tr:last input:first" ).trigger( 'blur' );

    closeWindow();
}

buscarInfoItem = function( elm_sel )
{

    var item_id   = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='IdItem[]']" ).val();

    var str_serialize = "TipoProc=info_item&IdItem=" + item_id;

    executeAjaxJson
    ( 
        "<?php echo buildUrl( 'item/request' ) ?>", 
        str_serialize,
        function( o_json )
        {
            //pr( o_json );
            if( o_json.error )
            {
                mostrarMensajeError( o_json.mensaje_error );
                return false;
            }
            
            //asignar la descripcion y el title
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='Descripcion[]']" ).val( o_json.DescripcionCompleta );
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='Descripcion[]']" ).attr( "title", o_json.DescripcionCompleta );
            
            //ahora asignamos el costo y el precio
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='CostoSinIGV[]']" ).val( o_json.Costo );
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='CostoConIGV[]']" ).val( o_json.CostoConIGV );
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='PrecioSinIGV[]']" ).val( o_json.Precio );
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='MontoIGV[]']" ).val( o_json.MontoIGV );
            $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='PrecioConIGV[]']" ).val( o_json.PrecioConIGV );
                
            //setTimeout( '$( $( global_elm ).closest( "tr" ) ).find( "input[name=\'Cantidad[]\']" ).focus();', 50 );
            setTimeout
            (
                function()
                {
                    calcularSumaTotal();
                },
                100
            );
            
        } 
    );
}

calcularSumaTotal = function()
{
    /*
    pr( "ingresa 1" );
    var a_elms = $( "#content_grid" ).find( "input[name='PrecioConIGV[]']" );
    var SumaTotal = 0;
    a_elms.each
    (
        function( index, elements )
        {
            if( $( elements ).val() != "" )
            {
                var MontoTotal = parseFloat( $( elements ).val() );
                SumaTotal = SumaTotal + MontoTotal;
            }
        }
    );
    $( "#SumaMontoTotal" ).val( SumaTotal );
    $( "#PrecioPromo" ).val( SumaTotal );

    //pr( "ingresa 2" );
    var a_elms = $( "#content_grid" ).find( "input[name='PrecioSinIGV[]']" );
    var SumaSubTotal = 0;
    a_elms.each
    (
        function( index, elements )
        {
            if( $( elements ).val() != "" )
            {
                var MontoTotal = parseFloat( $( elements ).val() );
                SumaSubTotal = SumaSubTotal + MontoTotal;
            }
        }
    );
    $( "#SumaMontoSubTotal" ).val( SumaSubTotal );
    
    //pr( "ingresa 3" );
    var a_elms = $( "#content_grid" ).find( "input[name='MontoIGV[]']" );
    var SumaMontoIGV = 0;
    a_elms.each
    (
        function( index, elements )
        {
            if( $( elements ).val() != "" )
            {
                var MontoTotal = parseFloat( $( elements ).val() );
                SumaMontoIGV = SumaMontoIGV + MontoTotal;
            }
        }
    );
    $( "#SumaMontoIGV" ).val( SumaMontoIGV );
    */

    var PrecioPromo  = parseFloat( $( "#PrecioPromo" ).val() );
    var PrecioSinIGV = redondear( ( PrecioPromo / 1.18 ), 2 );
    var MontoIGV     = redondear( ( PrecioSinIGV * 0.18 ), 2 );

    $( "#SumaMontoSubTotal" ).val( PrecioSinIGV );
    $( "#SumaMontoIGV" ).val( MontoIGV );
}

closeWindow = function()
{
    $( '#dialog' ).dialog( 'close' );
}
</script>

<script type="text/javascript">
//ESCAPE, DETECTA EL F5, CTRL+F5
$( document ).bind
(
    'keyup', 
    function( e ) 
    {
        //console.log( e.which );
        if( e.which === 116 ) 
        {
           
        }
        if( e.which === 82 && e.ctrlKey ) 
        {
           
        }
        if( e.which === 107 ) //tecla +
        {
            //openPopup();
            $( "#btnAgregar" ).trigger( "click" );
        }
        if( e.which === 119 ) 
        {
           
        }
        if( e.which === 27 ) //ESCAPE
        {
            
        }
    }
);
</script>
<script type="text/javascript">
//aqui se elimina el autocomplete
$( "#form1 input:text, #form1 select, textarea" ).each
(
    function()
    {
        if( this.id )
        {
            var nodeName = $( "#" + this.id ).prop( 'nodeName' );
            var nodeType = $( "#" + this.id ).prop( 'type' );

            switch( nodeName )
            {
                case "SELECT":
                break;
                case "TEXTAREA":
                break;
                case "INPUT":
                    $( "#" + this.id ).autocomplete( { disabled: true } );
                break;
            }
        }
    }
);

convertirTextoTodosLosInputs = function()
{
    //$( "#form1 input, #form1 select" ).replaceWith
    $( "#form1 input:text, #form1 select, textarea" ).replaceWith
    (
        function () 
        {
            //$( this );
            if( this.id )
            {
                var nodeName = $( "#" + this.id ).prop( 'nodeName' );
                var nodeType = $( "#" + this.id ).prop( 'type' );

                switch( nodeName )
                {
                    case "SELECT":
                        return '<h5>' + $( "#" + this.id + " option:selected" ).text() + '</h5>';
                    break;
                    case "TEXTAREA":
                    case "INPUT":
                        switch( nodeType )
                        {
                            case "hidden":
                                pr( nodeType );
                                
                                return true;
                            break;
                            case "textarea":
                            case "text":
                                return '<h5>' + $( "#" + this.id ).val() + '</h5>';
                            break;
                            case "button":
                                $( "#" + this.id ).remove();
                            break;
                            case "checkbox":
                                if( $( "#" + this.id ).is( ':checked' ) )
                                {
                                    return "<input type='checkbox' checked disabled />";
                                }
                                else
                                {
                                    return "<input type='checkbox' disabled />";
                                }
                            break;
                        }
                    break;
                }
                return '<h5>&nbsp;</h5>';
            }
            else
            {                
                return '<h5>' + $( this ).val() + '</h5>';
            }
        }
    );
}
<?php if( $s_TipoProc == "shw" ){ ?>
convertirTextoTodosLosInputs();
<?php } ?>

<?php if( $s_TipoProc == "upd" ){ ?>
$( "#IdItemTipo" ).trigger( "change" );
<?php } ?>
</script>