 <?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="#">Construction</a></li>
                <li><a href="#">BOQ & Purchase Order</a></li>
                <li><a href="#">Purchase Order</a></li>
                <li><a href="#">Create</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>Make 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::open(array('route' => 'construction-make-purchase-order.store','method'=>'POST', 'enctype'=>'multipart/form-data')); ?>

                    <div class="row">
                        <div class="form-group col-sm-6 col-xs-12">
                            <label class="required">Work Group Type </label>
                            <?php echo Form::select('work_group_type_id', $work_group_types, null, ['class' => 'form-control select2','required']); ?>

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

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

                        </div>
                        <div class="form-group col-sm-6 col-xs-12">
                            <label>Task Group Category</label>
                            <?php echo Form::select('task_group_categories',[], null, array('placeholder' => 'Please Select','class' => 'form-control select2','id'=>'task_group_categories')); ?>

                        </div>
                        <div class="form-group col-sm-6 col-xs-12">
                            <label class="required">Project</label>
                            <?php echo Form::select('project',[], null, array('class' => 'form-control select2 project','required','onchange'=>'clear_datatable()')); ?>

                        </div>
                        <div class="form-group col-sm-6 col-xs-12">
                            <label class="required">Warehouse</label>
                            <?php echo Form::select('warehouse_id',[], null, array('class' => 'form-control select2 warehouse_id','required')); ?>

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

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

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

                        </div>
                        <div class="form-group col-sm-6 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-6 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','onchange'=>'clear_datatable()')); ?>

                        </div>
                        <div class="form-group col-sm-6 col-xs-12">
                            <label class="required">Purchase for using to</label>
                            <?php echo Form::select('using_to',["1"=>'Each Zone',"2"=>'All Zone'], null, array('class' => 'form-control select2','required','onchange'=>'using_tofun(this)')); ?>

                        </div>
                        <div class="form-group col-sm-6 col-xs-12">
                            <label class="required">Zone</label>
                            <?php echo Form::select('zone_id',$zones, null, array('class' => 'form-control select2','id'=>'zone_id')); ?>

                        </div>
                        <div id="setting-product-list"></div>
                        <div id="setting-product-list-subcategory"></div>
                        <div class="form-group col-sm-12 col-xs-12 table-responsive">
                            <table class="table boq_detail nowrap">
                                <thead>
                                <th>#</th>
                                <th>Item Name</th>
                                <th style="min-width: 100px;">Unit</th>
                                <th>Qty Balance</th>
                                <th>Qty</th>
                                <th>Retail</th>
                                <th style="min-width: 100px;">Total</th>
                                <th style="min-width: 200px;">Purpose and Location</th>
                                <th>Check All <input type="checkbox" class="check_all"></th>
                                </thead>
                                <tbody>
                                    
                                </tbody>
                            </table>
                        </div>

                        <div class="col-sm-12 col-xs-12">
                            <div class="form-group">
                                <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" 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 using_tofun(obj){
            let this_value = $(obj).val();
            if(this_value==1){
                $("#zone_id").closest("div").find("label").addClass("required");
                $("#zone_id").attr("required","required");
                $()
            }else{
                $("#zone_id").closest("div").find("label").removeClass("required");
                $("#zone_id").removeAttr("required");
            }
        }
        function clear_datatable(){
            if($("#purchase_type")==1){
                $('.boq_detail tbody').html("");
            }
        }
        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;
        }
        function check_corect_qty(obj){
            var qty = Number($(obj).val());
            var balance_qty = Number($(obj).closest('tr').find("td:eq(3)").text());
            if(qty>balance_qty){
                $.alert("Qty invalid value");
                $(obj).val(0);
            }
        }
        function loading_product_by_subcategory(sub_category_id){
            if($(".project").val()==""||$(".project").val()==null){
                $.alert("Please Select Project");
                return false;
            }
            else{
                var route = "<?php echo e(route('get_product_by_subcategory_to_purchase',':id')); ?>";
                route = route.replace(":id",sub_category_id);
                $("#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:0);
                            $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>${check_qty_limit(values.id,$(".project").val())}</td>
                                    <td><input type="text" class="number-only form-control qty_per_house" name="qty_per_house[`+values.id+`]" value="`+qty+`" onchange="check_corect_qty(this)"></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","#subcategory_for_purchase",function(params) {
            var sub_category_id = $(this).val();
            loading_product_by_subcategory(sub_category_id);
        });
        function loading_product_by_category(product_category){
            if($(".project").val()==""||$(".project").val()==null){
                $.alert("Please Select Project");
                return false;
            }
            else{
                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){
                        var opt = `<option value="">Please Select</option>`;
                        $.each(data['subcategories'],function(num,val) {
                            opt += `<option value="${val.sub_category_id}">${val.name}</option>`;
                        });
                        $("#setting-product-list-subcategory").html(`
                                <div class="form-group col-sm-4 col-xs-12">
                                    <label>Product Sub-Category for purchase</label>
                                    <select name = 'subcategory_for_purchase' class='form-control select2' id='subcategory_for_purchase'>
                                        ${opt}
                                    </select>
                                </div>
                            `);
                        $("#subcategory_for_purchase").select2();
                        let $table = '';
                        $.each(data['products'], function (i, values) {
                            var qty = 0;
                            qty = (qty?qty:0);
                            $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>${check_qty_limit()}</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","#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){
                    var opt = `<option value="">Please Select</option>`;
                    $.each(data['subcategories'],function(num,val) {
                        opt += `<option value="${val.sub_category_id}">${val.name}</option>`;
                    });
                    $("#setting-product-list-subcategory").html(`
                            <div class="form-group col-sm-6 col-xs-12">
                                <label>Product Sub-Category for purchase</label>
                                <select name = 'subcategory_for_purchase' class='form-control select2' id='subcategory_for_purchase'>
                                    ${opt}
                                </select>
                            </div>
                        `);
                    $("#subcategory_for_purchase").select2()
                },
                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");

                $(".qty-balance").hide();
                $("#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-6 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);
                        $(".select2").select2();
                    },
                    complete:function(){
                        $("#main-spinner").hide();
                    }
                });
            }
            else{
                $(".boq").attr("required",true);
                $(".qty-balance").show();
                $(".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("");
                $("#setting-product-list-subcategory").html("");
            }
        });
        function check_make_order()
        {
            var boq_id          = $(".boq").val();
            var row             = $(".boq_detail").find('tbody').find('tr');
            var status_error    = 0;
            var task_group_categories = $("#task_group_categories").val();
            $(row).each(function(index,value)
            {
                if($(this).closest('tr').find('td:eq(8)').find('input').prop('checked')==true){
                    var product_id      = $(this).closest('tr').find('td:eq(1)').data('product-id');
                    var product_qty_balance = Number($(this).closest('tr').find('td:eq(3)').find('input').val());
                    var product_qty     = Number($(this).closest('tr').find('td:eq(4)').find('input').val());
                    var route           = "<?php echo e(route('construction.check_product_qty_boq')); ?>";
                    var product_name    = $(this).closest('tr').find('td:eq(1)').text();
                    var unit_name       = $(this).closest('tr').find('td:eq(2)').data('unit_name');
                    if(product_qty>product_qty_balance){
                        status_error = 2;
                    }
                    if(product_qty<=0){
                        status_error=1;
                    }
                    $("#main-spinner").hide();
                    if(status_error==0){

                    }
                    else if(status_error==1){
                        $.alert({
                            title: '',
                            type: 'red ',
                            content :product_name+" isn't in BOQ .Please check again before submit !",
                            useBootstrap: false,
                            boxWidth: '20%',
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning',
                                }
                            }
                        });
                    }
                    else if(status_error==2)
                    {
                        $.alert({
                            title: '',
                            type: 'red ',
                            content :product_name+" is missing ( Balance : "+product_qty_balance+unit_name+" ).Please check again before submit !",
                            useBootstrap: false,
                            boxWidth: '20%',
                            theme: 'modern',
                            buttons: {
                                close: {
                                    text: 'close',
                                    btnClass: 'button_warning',
                                }
                            }
                        });
                    }
                    else{

                    }
                }
                if(status_error!=0) return false;
            });
            if(status_error==1){
                $("#main-spinner").hide();
                $.alert({
                    title: '',
                    type: 'red ',
                    content :"Please Select Product Before Submit !",
                    useBootstrap: false,
                    boxWidth: '20%',
                    theme: 'modern',
                    buttons: {
                        close: {
                            text: 'close',
                            btnClass: 'button_warning',
                        }
                    }
                });
            }
            return status_error;
        }
        function get_detail_boq(boq,task_group_categories){
            $.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 (i, values) {
                            html += ('<option value="' + i + '">' + values + '</option>');
                        });

                        let $table = '';
                        $.each(data.boq_detail, function (i, values) {
                            var qty = values.qty_product;
                            qty = (qty?qty:0);
                            $table += `
                                <tr>
                                    <td>`+(i+1)+`</td>
                                    <td data-product-id = '${values.product_id}'>`+values.item_name+`</td>
                                    <td data-unit_name = '${values.unit_name}'>`+values.unit_name+`<input type="hidden" name="unit_id[`+values.product_id+`]" value="`+values.unit_id+`"></td>
                                    <td><input type="text" readonly class="number-only form-control qty_balance" name="qty_balance[]" value="${qty - 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="`+qty+`"></td>
                                    <td><input type="text" class="number-only form-control retail" name="retail[`+values.product_id+`]" value="`+(values.retail==null?'':values.retail)+`"></td>
                                    <td>$ <span class="total_amount">`+(values.retail*qty).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]').html(html);
                        $('.boq_detail tbody').html($table);
                        $('.select2').select2();
                    },
                    complete:function(){
                        $("#main-spinner").hide();
                    }
                });
        }
        $(document).on("change","#task_group_categories,.boq",function(){
            let boq = $('select[name=boq]').val();
            let task_group_categories = $("#task_group_categories").val();
            get_detail_boq(boq,task_group_categories);
            $("#setting-product-list-subcategory").html("");
        });
        $(document).ready(function () {
            $('select[name=boq]').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 () {
                $("#main-spinner").show();
                var check_status = 0;
                if($("#purchase_type").val()==0){
                    check_status = check_make_order();
                }
                if(check_status==0){
                    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',
                                    }
                                }
                            });
                        },
                        complete:function()
                        {
                            $("#main-spinner").hide();
                        }
                    });
                }
            });
            $(document).on("change",".project",function(){
                let project_id = $(this).val();
                $("#main-spinner").show();
                let route = "<?php echo e(route('project.get_warehouse',':id')); ?>";
                route = route.replace(':id',project_id);
                $.ajax({
                    url:route,
                    type:"GET",
                    dataType:"JSON",
                    success:function(data){
                        let opt = `<option value="">Please Select</option>`;
                        $.each(data,function(index,value){
                            opt += `<option value="${value.id}">${value.name}</option>`;
                        });
                        $(".warehouse_id").html(opt);
                    },
                    complete:function(){
                        $("#main-spinner").hide();
                    }
                });
            });
        });
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('adminlte::page', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>