 <?php $__env->startSection('content'); ?>
    <?php Fun::lang() ?>
    <div class="title-page">
        <div class="page-bar">
            <ul class="page-breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> Dashboard</a></li>
                <li><a href="#">Purchase Order</a></li>
                <li><a href="#">Edit</a></li>
            </ul>
        </div>
    </div>
    <div class="page">
        <div class="top-content">
            <div class="row">
                <div class="col-sm-12 col-xs-12">
                    <div class="title-page">
                        <div class="pull-left">
                            <h3>Edit Purchase</h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12 col-xs-12">

                <div class="form-wrapper">
                    <?php echo Form::model($purchase, ['method' => 'PATCH','route' => ['construction-make-purchase-order.update', $purchase->id],'enctype'=>'multipart/form-data']); ?>

                    <div class="row">
                        <div class="form-group col-sm-4 col-xs-12" style="display: none;">
                            <label class="required">Type of purchase</label>
                            <?php echo Form::select('purchase_type',['0'=>"Need BOQ","1"=>"Don't need BOQ"], $purchase->purchase_type, array('class' => 'form-control select2','required','id'=>'purchase_type')); ?>

                        </div>
                        <?php if($purchase->purchase_type==1): ?>
                        <div class="form-group col-sm-4 col-xs-12" style="display: none;">
                            <label class="required">BOQ Request</label>
                            <?php echo Form::select('boq_id',$boq, null, array('placeholder' => 'Please Select','class' => 'form-control select2 boq')); ?>

                        </div>
                        <?php else: ?>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">BOQ Request</label>
                            <?php echo Form::select('boq_id',$boq, null, array('placeholder' => 'Please Select','class' => 'form-control select2 boq','required')); ?>

                        </div>
                        <?php endif; ?>

                        <?php if($purchase->purchase_type==1): ?>
                        <div class="form-group col-sm-4 col-xs-12" style="display: none;">
                            <label class="required">Task Group Category</label>
                            <?php echo Form::select('task_group_categories',$data_title, null, array('placeholder' => 'Please Select','class' => 'form-control select2','id'=>'task_group_categories')); ?>

                        </div>
                        <?php else: ?>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">Task Group Category</label>
                            <?php echo Form::select('task_group_categories',$data_title, $purchase->task_group_work_title, array('placeholder' => 'Please Select','class' => 'form-control select2','id'=>'task_group_categories','required')); ?>

                        </div>
                        <?php endif; ?>
                        
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">Project</label>
                            <?php echo Form::select('project_id',$projects, null, array('class' => 'form-control select2 project','required')); ?>

                        </div>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">Request By</label>
                            <?php echo Form::text('request_by', null, array('placeholder' => 'Please Select','class' => 'form-control ','required')); ?>

                        </div>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">Stock Position</label>
                            <?php echo Form::text('stock_position', null, array('placeholder' => 'Please Select','class' => 'form-control ','required')); ?>

                        </div>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="required">Supply Company</label>
                            <?php echo Form::select('supplier_id',$supplier, null, array('placeholder' => 'Please Select','class' => 'form-control select2')); ?>

                        </div>
                        <div class="form-group col-sm-4 col-xs-12" style="display:none;">
                            <label class="">Phone Number</label>
                            <?php echo Form::text('phone_number', null, array('placeholder' => 'Please Select','class' => 'form-control ')); ?>

                        </div>
                        <div class="form-group col-sm-4 col-xs-12">
                            <label class="">Date</label>
                            <?php echo Form::text('date', date('d-m-Y'), array('placeholder' => 'Date','class' => 'form-control date_picker','autocomplete'=>'off')); ?>

                        </div>

                        <div class="form-group col-sm-12 col-xs-12">
                            <table class="table boq_detail">
                                <thead>
                                    <th>#</th>
                                    <th>Item Name</th>
                                    <th>Unit</th>
                                    <th>Qty Balance</th>
                                    <th>Qty</th>
                                    <th>Retail</th>
                                    <th>Total</th>
                                    <th>Purpose and Location</th>
                                    <th>Check All <input type="checkbox" class="check_all"></th>
                                </thead>
                                <tbody >
                                    <?php
                                        $tbody = "";
                                        foreach($detail as $key=>$values){
                                            $tbody .='<tr product-id="'.$values->product_id.'">
                                                <td>'.($key+1).'</td>
                                                <td>'.$values->product_name.'</td>
                                                <td>'.$values->unit_name.'<input type="hidden" name="unit_id['.$values->product_id.']" value="'.$values->unit_id.'"></td>
                                                <td><input type="text" class="number-only form-control qty_blance" name="qty_blance[]" value="'.$product_boq_purchased_qty_balance[$key].'"></td>
                                                <td><input type="text" class="number-only form-control qty_per_house" name="qty_per_house['.$values->product_id.']" value="'.$values->qty.'"></td>
                                                <td><input type="text" class="number-only form-control retail" name="retail['.$values->product_id.']" value="'.$values->price.'"></td>
                                                <td>$ <span class="total_amount">'.$values->qty*$values->price.'</span></td>
                                                <td><textarea name="pur_location['.$values->product_id.']" id="" class="form-control" rows="2" style="resize: none;">'.$values->purpose_and_location.'</textarea></td>
                                                <td>
                                                    <input type="checkbox" name="checkbox[]" class="check_here" checked value="'.$values->product_id.'">
                                                    <button type="button" class="btn btn-danger btn_remove" style="display: none"><span class="fa fa-times"></span></button>
                                                </td>
                                            </tr>';
                                        }
                                     ?>
                                    <?php echo $tbody; ?>

                                </tbody>
                            </table>
                        </div>

                        <div class="col-sm-12 col-xs-12">
                            <div class="form-group">
                                <button type="submit" class="button_sm button_success pull-right" id="btn-edit-submit"><span
                                    class="fa fa-chevron-circle-right"></span> Submit
                                </button>
                                <button type="button" class="button_sm button_success pull-right btn_submit" data-type="order"><span
                                            class="fa fa-chevron-circle-right"></span> Make Order
                                </button>
                                <button type="button" class="button_sm button_primary pull-right btn_submit"  data-type="request"><span
                                            class="fa fa-reply"></span> Request Order
                                </button>
                                <button type="button" onClick="javascript:history.go(-1)"
                                        class="button_sm button_warning pull-right">
                                    <span class=" fa fa-arrow-circle-left"></span> Back
                                </button>
                                
                            </div>
                        </div>
                    </div>

                    <?php echo Form::close(); ?>

                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('js'); ?>
    <script type="text/javascript">
        function check_qty_limit(product_id,project_id){
            var qty = "";
            $.ajax({
                url:"<?php echo e(route('construction-purchase.check_qty_limit')); ?>",
                type:"POST",
                dataType:"JSON",
                async:false,
                data:{
                    "_token":"<?php echo e(csrf_token()); ?>",
                    product_id:product_id,
                    project_id:project_id
                },
                success:function(data){
                    qty = data;
                },
                complete:function(){

                }
            });
            return qty;
        }
        $(document).ready(function(){
            if($("#purchase_type").val()==1){
                var project_id = $(".project").val();
                $("table.boq_detail tbody tr").each(function(index,value){
                    var product_id = $(value).attr('product-id');
                    $(value).find("td:eq(3)").find('input').val(check_qty_limit(product_id,project_id));
                });
            }
        });
        function get_detail_boq(boq,task_group_categories){
            var boq_orin_id = "<?php echo e($purchase->boq_id); ?>";
            $.ajax({
                url: '<?php echo e(route("construction-get-boq-detail")); ?>',
                dataType: 'json',
                data: {
                    boq: boq,
                    task_group_categories:task_group_categories
                },
                success: function (data) {
                    let html = ('<option value="">Please Select</option>');
                    $.each(data.project, function boq_id(i, values) {
                        html += ('<option value="' + i + '">' + values + '</option>');
                    });

                    let $table = '';

                    if(Number(boq)==Number(boq_orin_id)){
                        $("#btn-edit-submit").show();
                        $(".btn_submit").hide();
                    }else{
                        
                        $("#btn-edit-submit").hide();
                        $(".btn_submit").show();
                        $.each(data.boq_detail, function (i, values) {
                            $table += `
                                <tr>
                                    <td>`+(i+1)+`</td>
                                    <td>`+values.item_name+`</td>
                                    <td>`+values.unit_name+`<input type="hidden" name="unit_id[`+values.product_id+`]" value="`+values.unit_id+`"></td>
                                    <td><input type="text" class="number-only form-control qty_balance_purchased" name="qty_balance_purchased" value="${(values.qty_product==null?0:values.qty_product) - data.product_boq_purchased_qty[i]}"></td>
                                    <td><input type="text" class="number-only form-control qty_per_house" name="qty_per_house[`+values.product_id+`]" value="`+(values.qty_product==null?0:values.qty_product)+`"></td>
                                    <td><input type="text" class="number-only form-control retail" name="retail[`+values.product_id+`]" value="`+values.retail+`"></td>
                                    <td>$ <span class="total_amount">`+(values.retail*(values.qty_product==null?0:values.qty_product)).toFixed(2)+`</span></td>
                                    <td><textarea name="pur_location[`+values.product_id+`]" id="" class="form-control" rows="2" style="resize: none;"></textarea></td>
                                    <td>
                                        <input type="checkbox" name="checkbox[]" class="check_here" value="`+values.product_id+`">
                                        <button type="button" class="btn btn-danger btn_remove" style="display: none"><span class="fa fa-times"></span></button>
                                    </td>
                                </tr>
                            `;
                        });
                    }
                    $('select[name=project_id]').html(html);
                    $('.boq_detail tbody').html($table);
                    $('.select2').select2();
                }
            });
        }
        $(document).on("change","#task_group_categories",function(){
            let boq = $('select[name=boq_id]').val();
            get_detail_boq(boq,$(this).val());
        });
        var tbody = <?php echo json_encode($tbody); ?>;
        $(document).on("change","#category_for_purchase",function()
        {
            var product_category = $(this).val();
            var route = "<?php echo e(route('get_product_by_category_to_purchase',':id')); ?>";
            route = route.replace(":id",product_category);
            $("#main-spinner").show();
            $('.boq_detail tbody').html("");
            $.ajax({
                url:route,
                type:"GET",
                dataType:"JSON",
                success:function(data){
                    let $table = '';
                    $.each(data, function (i, values) {
                        var qty = 0;
                        qty = (qty?qty:'');
                        $table += `
                            <tr>
                                <td>`+(i+1)+`</td>
                                <td data-product-id = '${values.id}'>`+values.name+`</td>
                                <td data-unit_name = '${values.unit_name}'>`+values.unit_name+`<input type="hidden" name="unit_id[`+values.id+`]" value="`+values.unit_id+`"></td>
                                <td><input type="text" class="number-only form-control qty_per_house" name="qty_per_house[`+values.id+`]" value="`+qty+`"></td>
                                <td><input type="text" class="number-only form-control retail" name="retail[`+values.id+`]" value="`+(values.current_price==null?'':values.current_price)+`"></td>
                                <td>$ <span class="total_amount">`+(values.current_price*qty).toFixed(2)+`</span></td>
                                <td><textarea name="pur_location[`+values.id+`]" id="" class="form-control" rows="2" style="resize: none;"></textarea></td>
                                <td>
                                    <input type="checkbox" name="checkbox[]" class="check_here" value="`+values.id+`">
                                    <button type="button" class="btn btn-danger btn_remove" style="display: none"><span class="fa fa-times"></span></button>
                                </td>
                            </tr>
                        `;
                    });
                    $('.boq_detail tbody').html($table);
                },
                complete:function(){
                    $("#main-spinner").hide();
                }
            });
        });
        $(document).on("change","#purchase_type",function()
        {
            if($(this).val()==1)
            {
                $(".boq").removeAttr("required");
                $(".boq").closest("div").hide();
                $(".boq").closest("div").find("label").removeClass("required");

                $("#task_group_categories").removeAttr("required");
                $("#task_group_categories").closest("div").hide();
                $("#task_group_categories").closest("div").find("label").removeClass("required");
                var route = "<?php echo e(route('construction-purchase.get_product_purchase_no_boq',':id')); ?>";
                route = route.replace(":id",$(this).val());
                $("#main-spinner").show();
                $.ajax({
                    url:route,
                    type:"GET",
                    dataType:"JSON",
                    success:function(data){
                        var opt="<option value=''>Please Select</option>";
                        $.each(data['product'],function(index,value)
                        {
                            opt += `<option value = ${value.id}>${value.name}</option>`;
                        });
                        $("#setting-product-list").html(`
                            <div class="form-group col-sm-4 col-xs-12">
                                <label class="required">Product Category for purchase</label>
                                <select name = 'category_for_purchase' class='form-control select2' id='category_for_purchase'>
                                    ${opt}
                                </select>
                            </div>
                        `);
                        $(".select2").select2();
                        var project_opt = "<option value=''>Please Select</option>";
                        $.each(data['projects'],function(index,value)
                        {
                            project_opt += `<option value='${value.id}'>${value.project_name}</option>`;
                        });
                        $(".project").html(project_opt);
                    },
                    complete:function(){
                        $("#main-spinner").hide();
                    }
                });
            }
            else{
                $(".boq").attr("required",true);
                $(".boq").closest("div").find("label").addClass("required");
                $(".boq").closest("div").show();

                $("#task_group_categories").attr("required");
                $("#task_group_categories").closest("div").show();
                $("#task_group_categories").closest("div").find("label").addClass("required");
                $("#setting-product-list").html("");
            }
        });
        $(document).ready(function () {
            $(".btn_submit").hide();
            $('select[name=boq_id]').on('change', function () {
                $("#main-spinner").show();
                let boq = $(this).val();
                var route = "<?php echo e(route('get_bog_title_work_group',':id')); ?>";
                route = route.replace(":id",boq);
                $.ajax({
                    url:route,
                    type:"GET",
                    dataType:"JSON",
                    success:function(data)
                    {
                        var opt = `<option value=''>Please Select</option>`;
                        $.each(data,function(index,value)
                        {
                            opt +=`
                            <option value ='${value.title}'>
                                ${value.title}
                            </option>`;
                        });
                        $("#task_group_categories").html(opt);
                    },
                    complete:function()
                    {
                        $("#main-spinner").hide();
                    }
                });
            });
            
            $(document).on('click','.btn_remove',function () {
                $(this).closest('tr').remove();
            });
            $(document).on('click','.check_all',function () {
                let check_all = $(this).prop('checked');
                $(document).find('.check_here').attr('checked',check_all);
            });
            $(document).on('keyup','.number-only',function () {

                let qty = $(this).closest('tr').find('.qty_per_house').val();
                let price = $(this).closest('tr').find('.retail').val();
                let total = parseFloat(price?price:0)*parseFloat(qty?qty:0);
                $(this).closest('tr').find('.total_amount').text(total.toFixed(2));
            });
            $('.btn_submit').on('click',function () {
                let form = $('form').serializeArray();
                let type = $(this).data('type');
                form.push({name: 'type', value: type});
                $.ajax({
                    url:'<?php echo e(route("construction-make-purchase-order.store")); ?>',
                    method:'post',
                    dataType:'json',
                    data:form,
                    success:function (row) {
                        if(row.status==='success'){
                            window.location.replace(row.route);
                        }
                    },
                    error:function (xhr, textStatus, errorThrown) {
                        let error = xhr.responseJSON.errors;
                        let text_err = '<ul class="text-left">';
                        $.each(error, function (i, val) {
                            let string = val[0].replace('The', '');
                            let fletter = string.substr(1, 1);
                            let store = string.replace(fletter, fletter.toUpperCase());
                            text_err += '<li><span class="fa fa-caret-right text-danger"></span> The ' + store + '</li>';
                        });
                        text_err += '</ul>';
                        $.alert({
                            icon:'fa fa-exclamation-triangle',
                            title: 'Warning',
                            type: 'orange',
                            content: text_err,
                            useBootstrap: false,
                            boxWidth: '25%',
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: '<?php echo e(__('administrator.close')); ?>',
                                    btnClass: 'button_warning',
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('adminlte::page', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>