<style type="text/css">
    .issue-btn {
        background-color: #1ba !important;
        border-color: #1ba !important;
    }
    
    #issue-diag .inp-lbl {
        background: #1ba;
        border: none;
        color: #fff;
        letter-spacing: 2px;
        font-weight: bold;
    }
    
    #issued-logs {
        padding: 0px 40px;
    }
    
    #issued-logs tr {
        border-bottom: 1px dotted #607d8b;
    }
    
    #issued-logs th, #issued-logs td {
        padding: 5px;
        text-align: center;
    }
    
    #issued-logs th {
        background: #607d8b;
        color: #fff;
    }
    
    #issued-logs .btn {
        background: #607d8b;
        color: #fff;
        min-width: 100px;
    }
    
    #usage-alert {
        font-size: 12px;
        color: #f33;
        text-align: left;
        margin-top: 500px;
        letter-spacing: 1px;
        padding-left: 3%;
        border-top: 1px solid;
        padding-top: 10px;    
    }
</style>
<aside class="right-side">
    <section class="content-header">
        <div class="title_bar">
            <h1 class="major_txt_color">General Inventory List</h1>
            <div class="breadcrumb_container"><?php echo breadcrumb_links();?></div>
        </div>
    </section>
    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <!-- /.box -->
                <div class="box box-primary">
                    <div class="box-body table-responsive">
                    <?php if(!empty($success)) {?>
                        <div class="alert alert-success alert-dismissable">
                            <i class="fa fa-thumbs-o-up"></i>
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <h4><?php echo $success;?></h4>
                        </div>
                    <?php }
                    else if(!empty($error)) {?>
                        <div class="alert alert-danger alert-dismissable">
                            <i class="fa fa-thumbs-o-down"></i>
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <h4><?php echo $error;?></h4>
                        </div>
                    <?php }?>
                        <div class="row">
                            <div class="left-col action-left-col">
                                <?php if (in_array(2, $permission)) {?>
                                    <a href="<?php echo $add_link?>">
                                        <input type="button" class="btn btn-success btn-sm" value="<?php echo $add_btn?>" />
                                    </a>
                                <?php }?>
                            </div>
                        </div>      
                    </div>
                    <div class="box-body table-responsive">
                        <table class="table table-bordered table-striped data_table">
                            <thead>
                                <tr>
                                    <th width="10%">S.No</th>
                                    <th>Category Name</th>
                                    <th>Item Name</th>
                                    <th style="text-align:center;">Available Quantity</th>
                                    <th width="15%">Action</th>
                                </tr>
                            </thead>
                            <tbody>    
                                <?php
                                    //echo '<pre>'; print_r( $results ); die;
                                    foreach( $results as $k => $row ):
                                        $inv_item_id = $row['inv_item_id'];
                                ?>
                                    <tr>
                                        <td><?php echo ++$k; ?></td>
                                        <td><?php echo text( $row['category_name'] ); ?></td>
                                        <td><?php echo text( $row['item_name'] );?></td>
                                        <td align="center" class="td-avail-qty"><?php echo $row['now_avail_qty'];?></td>
                                        <td class="td_action" style="min-width: 240px;">
                                            <input type="hidden" name="auto_id" class="auto_id" value="<?php echo $row['id']; ?>" />
                                            <?php if( in_array(1, $permission)) : ?>
                                                <a class="label btn btn-warning view" href="<?php echo $view_link . $inv_item_id; ?>">
                                                    <span>View</span>
                                                </a>
                                            <?php endif; if( in_array(3, $permission)) : ?>
                                                <a class="label btn btn-primary edit" href="<?php echo $edit_link . $inv_item_id; ?>">
                                                    <span>Edit</span>
                                                </a>
                                            <?php endif; if (in_array(4, $permission)) : 
                                                        
                                                        if( !empty( $row['total_issued_qty'] ) ) :
                                                            ?>
                                                                <a class="label btn btn-danger" onclick="javascript: msgBox('Sorry, Unable to delete! <div>Some of the items are already issued!</div>', 6000); return false;" style="cursor: no-drop;"><span>Delete</span></a>
                                                            <?php
                                                        else :
                                                            ?>
                                                                <a class="label btn btn-danger pop_up_confirm delete delete_otp" data-confirm="Do you want to delete the General Inventory <b><?php echo $row['item_name']; ?></b>?" data-href="<?php echo $delete_link . $inv_item_id; ?>" data-otp-ids="<?php echo form_prep(serialize($service_menu_id));?>">
                                                                    <span>Delete</span>
                                                                </a>
                                                            <?php
                                                        endif;
                                                endif; ?>
                                                                
                                                <a class="label btn btn-primary issue-btn" data-id="<?php echo $row['id'].'`'.$row['inv_cat_id'].'`'.$inv_item_id.'`'.$row['item_name'].'`'.$row['total_issued_qty'].'`'.$row['archanai_item_id']; ?>" data-avail-qty="<?php echo $row['now_avail_qty']; ?>" onclick="issue_dialog(this);">
                                                    <span>Issue</span>
                                                </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div><!-- /.box-body -->
                </div><!-- /.box -->
            </div>
        </div>
        
        <!-- Start Modal -->
        <div class="modal fade" id="otp-dialog" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">

                    <div class="modal-header" style="background-color: #337AB7;">
                        <button type="button" class="close cancel_popup" data-dismiss="modal" style="color: #FFF;">x</button>
                        <h4 class="modal-title" style="color: #FFF;">OTP</h4>
                    </div>
                    <div class="modal-body col-xs-12" style="margin-bottom: 30px; border-bottom: 1px dotted #1ba;">
                        <form name="m">
                            <input type="hidden" class="hidden_id" />
                            <input type="hidden" class="edit_link" data-edit-link="<?php echo (!empty($edit_link)) ? $edit_link : '';?>" />
                            <ul class="error_container" style="display:block;padding-left: 50%;"></ul>
                            <div class="col-xs-12">
                                <div class="col-xs-3">&nbsp;</div>                        
                                <div class="col-xs-1">
                                    <label style="padding-top: 31%;">OTP</label>
                                </div>
                                <div class="col-xs-6">
                                    <input type="text" class="form-control otp_no" name="otp_no" value="" />
                                </div>
                                <div class="col-xs-3">&nbsp;</div>
                            </div>
                        </form>
                    </div>

                    <div class="modal-footer" style="padding-right: 30px;">
                        <button type="button" class="btn btn-primary otp_btn_cancel" data-dismiss="modal"><i class="fa fa-play-circle-o"></i> Later</button>
                        <button type="submit" id="sbmt-btn" class="btn btn-danger"><i class="fa fa-send"></i> Send</button>
                    </div>
                </div>   <!-- Modal Content -->     
            </div> 
        </div> <!-- OTP Dialog -->
        
        <!-- Start Modal -->
        <div class="modal fade" id="warning-dialog" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">

                    <div class="modal-header" style="background-color: #337AB7;">
                        <button type="button" class="close cancel_popup" data-dismiss="modal" style="color: #FFF;">x</button>
                        <h4 class="modal-title" style="color: #FFF;">Warning: Mis-match module is found</h4>
                    </div>
                    <div class="modal-body col-xs-12" style="margin-bottom: 30px; border-bottom: 1px dotted #1ba;">
                        <form name="m">
                            <input type="hidden" class="correct_url" name="correct_url" /> 
                            <div class="col-xs-12 warning_content"></div>
                        </form>
                    </div>

                    <div class="modal-footer" style="padding-right: 30px;">
                        <button type="submit" id="sbmt-btn" class="btn btn-danger"><i class="fa fa-history"></i> Redirect Now</button>
                        <button type="button" class="btn btn-primary redirect_btn_cancel" data-dismiss="modal"><i class="fa fa-play-circle-o"></i> Later</button>                        
                    </div>
                </div>   <!-- Modal Content -->     
            </div> 
        </div> <!-- Dialog -->
        
    </section><!-- /.content -->
</aside><!-- /.right-side -->
<div class="popup-dialg" id="issue-diag">
    <i class="fa fa-times popup-dialg-clse-btn"></i>
    <div class="popup-dialg-title">Issue Inventory</div>
    <div class="wrap">
        <div class="col-xs-12">
            
        </div>
        <div class="col-xs-12" style="margin-top: 1%;">
            <div class="col-md-6"> 
                <div class="form-group float-clear">
                    <label>Item Name</label>
                    <input type="text" class="form-control inp-lbl" name="issue_item_name" value="" readonly />
                </div>
                
                <div class="form-group float-clear">
                    <label>&nbsp;</label>
                    <button class="bttn primary" id="issue-edit-btn" style="display: none; background: #607d8b; width: 55%; padding: 5px; color: #fff; border: none;">Get Records</button>
                </div>
            </div>
            
            <div class="col-md-6"> 
                <div class="form-group float-clear">
                    <label>Avail. Quantity</label>
                    <input type="text" class="form-control inp-lbl" name="issue_avail_qty" value="" readonly />
                </div>
            
                <div class="form-group float-clear">
                    <label>Counter Usage</label>
                    <input type="text" class="form-control usage-type" name="issue_usage_1" value=""/>
                </div>
                
                <div class="form-group float-clear">
                    <label>Sanctum Usage</label>
                    <input type="text" class="form-control usage-type" name="issue_usage_2" value=""/>
                </div>
                
                <div class="form-group float-clear">
                    <label>Kitchen Usage</label>
                    <input type="text" class="form-control usage-type" name="issue_usage_3" value=""/>
                </div>
                
            </div>
            
        </div>
        
        <div class="col-xs-12 ctrls" style="display: none;">
            <div class="border-bottom: 2px dotted; margin-bottom: 20px;">
                
                <button class="bttn popup-dialg-clse-btn">Cancel</button>
                <button class="bttn primary sbmt-btn">Update</button>
            </div>
        </div>  
        <div id="issue-msg" style="width: 100%; text-align: center; margin: 20px 0px; color: #1ba;"></div>
        <div id="usage-alert">* Please note: Unable to issue this Item to <span style="font-size: 11px; font-weight: bold;">"Counter",</span> hence it is not added to Archanai. </div>
    </div>
</div>

<!-- ./wrapper -->
<script type="text/javascript">
    $(document).on('ready', function(){
        $('.usage-type').on('keyup', function(){
            var $this   = $(this)
            ,   availQty = $('[name="issue_avail_qty"]').val() || 0;
            
            if( availQty > 0 ) {
                var total = 0;
                $('.usage-type').each(function(){
                    total += parseFloat($(this).val()) || 0;
                })
                
                if( total > availQty ) {
                    $this.val('');
                    msgBox('Sum of quantity must be less than available!');
                    return false;
                }else {
                    msgBox();
                    $('#issue-diag .ctrls').fadeIn('slow');
                }
                
            }else {
                $('.usage-type').val('');
                msgBox('Available quantity is not enough.');
                $('#issue-diag .ctrls').fadeOut('slow');
                return false;
            }
            
        })
        
        $('#issue-diag .sbmt-btn').on('click', function(){
            var data = {
                act   : 'usage',  
                ids    : $('#issue-diag').attr('data-id') || "",
                usage1: $('[name="issue_usage_1"]').val(),
                usage2: $('[name="issue_usage_2"]').val(),
                usage3: $('[name="issue_usage_3"]').val(),
            };
            
            if( data.usage1 == '' && data.usage2 == '' && data.usage3 == '' ) {
                msgBox("Nothing to update in here!");
                return false;
            }
            
            $('#issue-diag .ctrls').fadeOut('slow', function(){
                $('#issue-msg').html('Please wait ...').fadeIn('slow', function(){
                    $.post( baseURL + controller + '/ajax/', data, function(res){
                        res = JSON.parse(res) || "";
                        if( res != '' ) {
                            var $actIssue = $('.issue-btn.active')
                            ,   availQty  = $actIssue.attr('data-avail-qty') || 0;
                            availQty -=  res.total;
                            
                            $('.usage-type').val('');
                            $('[name="issue_avail_qty"]').val(availQty);
                            $('.issue-btn.active').attr('data-avail-qty', availQty);
                            $actIssue.parent().closest('tr').find('.td-avail-qty').text(availQty);
                            
                            $('#issue-msg').html('Information is updated');
                            setTimeout(function(){
                                if( availQty > 0 ) {
                                    $('#issue-msg').fadeOut('slow', function(){
                                        $('#issue-diag .ctrls').fadeIn('slow', function(){    

                                        });
                                    });
                                }else {
                                    $('#issue-msg').html('Right now, all are issued!');
                                }
                            }, 3500);
                        }
                    });
                });
            });
            
            
            
        });
        
        $('#issue-edit-btn').on('click', function(){
            var ids = $('#issue-diag').attr('data-id') || "";
            
            if( ids != '' ) {
                var s = ids.split('`');
                var data = {
                    act   : 'get_usage',  
                    invItemId  : s[2],
                };

                $('#issue-diag .ctrls').fadeOut();
                $('#issue-msg').fadeIn('slow', function(){
                    $(this).html('Getting results ...');
                    
                    $.post(baseURL + controller + '/ajax/', data, function(results){
                        results = JSON.parse(results); 
                        var html = '';
                        
                        $('#issue-msg').fadeOut('slow');
                        if( $('#issued-logs').length == 0 ) {
                            html += '<div id="issued-logs">';
                            html +=     '<table style="width: 100%;"><thead>';
                            html +=         '<tr><th>S.No</th><th>Issued Date</th><th>Usage Type</th><th>Issued Quantity</th><th>Sold Quantity</th><th>Action</th></tr>';
                            html +=     '</thead><tbody></tbody></table>';
                            html += '</div>';
                            
                            $('#issue-diag .ctrls').after( html );
                        }
                        
                        var html = ''
                        ,   i    = 0;
                        Object.keys(results).map(function(k, v){
                            html += '<tr data-id="'+ results[k]['id'] +'">';
                            html +=     '<td>'+ (++i) +'</td><td>'+ results[k]['date'] +'</td><td style="text-align: left;">'+( results[k]['usage_type'] == '1' ? 'Counter' : ( results[k]['usage_type'] == '2' ? 'Sanctum' : 'Kitchen' ) )+'</td><td>'+ results[k]['total_issued_qty'] +'</td><td>'+ results[k]['total_sold_qty'] +'</td><td>'+ (results[k]['total_sold_qty'] > 0 ? '<button class="btn sold-btn" style="background: #FF9800;">Sold</button>' : '<button class="btn delete">Delete</button>') +'</button></td>';
                            html += '</tr>';
                        });
                        
                        $('#issued-logs table tbody').html(html);
                        $('#issue-diag .ctrls, #issued-logs').fadeIn();
                    });

                });
            }
            
            
        });
        
        $(document).on('click', '#issued-logs .btn', function(){
            var $this = $(this);
            
            if( $this.hasClass('sold-btn') ) {
                // Already sold
                msgBox("Sorry, Unable to delete.<div>Some of the items are already sold!</div>");
            }else {
                
                if( window.confirm("Are you sure about to delete this record..?") ) {
                    // Delete
                    var $parent = $this.parent().closest('tr')
                    ,   data = {
                        act : 'rm_usage',
                        id  : $parent.attr('data-id')
                    };
                    
                    $('#issue-msg').fadeOut('slow', function(){
                        $(this).html('Please wait ...');
                        
                        $.post(baseURL + controller + '/ajax/', data, function(results){
                            $parent.remove();
                            
                            // Update S. No
                            
                            $('#issued-logs tbody tr').each(function(i, v){
                                $(this).find('td:first').html(i+1);
                            });
                        });
                    });
                    
                }
                
                return false;
            }
            
        })
    })
    
    function issue_dialog(_this) {
        var availQty    = $(_this).attr('data-avail-qty') || 0
        ,   dataId      = $(_this).attr('data-id'); 
        
        $(_this).addClass('active');
        $('.issue-btn').not(_this).removeClass('active');
        
        $('.over-lay').fadeIn('slow');
        $('.usage-type').val('');
        $('#issued-logs').fadeOut().find('tbody').html('');
        
        var s = dataId.split('`');
        if( s[5] == '' ) {
            // Inv. Item is not available in "Item Master"
            $('[name="issue_usage_1"]').attr('readonly', 'readonly').addClass('readonly');
            $('#usage-alert').show();
        }else {
            $('[name="issue_usage_1"]').removeAttr('readonly').removeClass('readonly');
            $('#usage-alert').hide();
        }
        
        $('#issue-diag').fadeIn('slow', function(){ 
            $(this).attr('data-id', dataId);
            $('[name="issue_item_name"]').val(s[3]);
            $('[name="issue_avail_qty"]').val(availQty);
            
            if( parseInt(s[4]) > 0 ) {
                $('#issue-edit-btn').fadeIn('slow');
            }else {
                $('#issue-edit-btn').fadeOut();
            }
            
        })
    }
    
</script>