@extends('adminlte::page') @section('content')
@section('css')
<style>
    .contain {
        display: block;
        position: relative;
        padding-left: 35px;
        margin-bottom: 12px;
        cursor: pointer;
        font-size: 15px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }

    /* Hide the browser's default radio button */
    .contain input {
        position: absolute;
        opacity: 0;
        cursor: pointer;
    }

    /* Create a custom radio button */
    .checkmark {
        position: absolute;
        top: 0;
        left: 0;
        height: 17px !important;
        width: 17px !important;
        background-color: #eee;
        border-radius: 50%;
    }

    /* On mouse-over, add a grey background color */
    .contain:hover input~.checkmark {
        background-color: #ccc;
    }

    /* When the radio button is checked, add a blue background */
    .contain input:checked~.checkmark {
        background-color: #2196F3;
    }

    /* Create the indicator (the dot/circle - hidden when not checked) */
    .checkmark:after {
        content: "";
        position: absolute;
        display: none;
    }

    /* Show the indicator (dot/circle) when checked */
    .contain input:checked~.checkmark:after {
        display: block;
    }

    /* Style the indicator (dot/circle) */
    .contain .checkmark::after {
        top: 4px;
        left: 4px;
        width: 7px;
        height: 7px;
        border-radius: 50%;
        background:
            white;
    }

    .inven-name {
        min-height: 20px;
        color: orangered !important
    }
</style>
@stop
<?php

use Illuminate\Support\Facades\Session;

Fun::lang() ?>
<?php $total = 0 ?>
<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="#">Operation</a></li>
            <li><a href="#">POS</a></li>
            <li><a href="#">POS</a></li>
        </ul>
    </div>
</div>
<div class="page">
    <div class="ajax-alert">
        @if ($message = Session::get('success'))
        <div class="alert-message alert-success">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <i class="fa fa-check"></i>
            <h3>Success</h3>
            <p>{{$message}}</p>
        </div>
        @endif
        @if ($message = Session::get('danger'))
        <div class="alert-message alert-danger">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <i class="fa fa-exclamation-triangle"></i>
            <h3>Errors</h3>
            <p>{{$message}}</p>
        </div>
        @endif

        @if ($message = Session::get('warning'))
        <div class="alert-message alert-warning">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <i class="fa fa-exclamation-triangle"></i>
            <h3>Warning</h3>
            <p>{{$message}}</p>
        </div>
        @endif
    </div>
    <div class="top-content">
        <div class="row pos">
            <div class="col-sm-12 col-xs-12">
                <div class="pull-left">
                    <h3>POS</h3>
                </div>
                <div class="pull-right">
                    <div class="button-pos">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="box-body">
        <div class="pos">
            <div class="row">
                <div class="col-sm-8">
                    <div class="pos-box">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="col-sm-6">
                                    <div class="col-sm-4">
                                        <label for="">Select Project</label>
                                    </div>
                                    <div class="col-sm-8">
                                        {!! Form::select('project_id', $projects, isset($project_id)?$project_id:null, ['class' => 'form-control select2','id'=>'project_id','multiple']) !!}
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <label for="" class="col-sm-4">Category</label>
                                    <div class="form-group col-sm-8">
                                        {!! Form::select('category_id',$category,isset($category_id)?$category_id:null,['class'=>'form-control select2','id'=>'category_id','multiple']) !!}
                                    </div>
                                </div>
                                <div class="col-sm-6" style="display: none;">
                                    <label for="" class="col-sm-4">Inventory</label>
                                    <div class="form-group col-sm-8">
                                        {!! Form::select('inventory_id',$inventory,isset($inventory_id)?$inventory_id:null,['class'=>'form-control select2','id'=>'inventory_id']) !!}
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="col-sm-4">
                                        <label for="">Item Name</label>
                                    </div>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" name="item" id="item_filter">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div id="item_list">
                            {{-- @include('administrator.pos.pre-result') --}}
                        </div>
                        <div id="form-pay" style="display: none;">
                            {!! Form::open(array('route' => 'pos.store','method'=>'POST','enctype'=>'multipart/form-data','id' => 'form_validate')) !!}
                            <div class="total">
                                <strong class="green" style="display:none" id="total_amount"></strong>
                            </div>
                            <div class="form-group">
                                <div class="new-customer-button">
                                    <button class="pull-right" type="button" id="add" class="btn btn-sm btn btn-warning" style="margin-bottom:5px">
                                        <span> New Customer </span>
                                        <i class="fa fa-plus"></i>
                                    </button>
                                </div>
                                <label class="required">Select Customer</label>

                                {!! Form::select('sale_clientid', $clients, null, ['class' => 'form-control select2','id'=>'client_id']) !!}

                            </div>
                            <div class="form-group">
                                <label for="required">Sale By</label>
                                {!! Form::select('sale_type_by', ['1'=>'Employee','2'=>'Agency'], null, ['class' => 'form-control select2','id'=>'sale-type-by']) !!}
                            </div>
                            <div id="append-sale">
                                <div class="form-group">
                                    <label for="required">Select Employee(Sale)</label>
                                    {!! Form::select('employees', $employees, Auth::user()->id, ['class' => 'form-control select2','required']) !!}
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="required">Deposit Date</label>
                                <input type="text" name="date_deposit" class="form-control number-only date_picker" value="{{date('d-m-Y')}}" autocomplete="off" placeholder="Date Deposit *" required id="date-deposit"/>
                            </div>
                            <div class="form-group" id="date-contract">
                                <label class="required">Contract Date</label>
                                <input type="text" name="date_contract" class="form-control number-only date_picker" autocomplete="off" placeholder="Date Contract *" required />
                            </div>
                            <div class="form-group">
                                <label>Discount Amount</label>
                                <input type="text" name="sale_discount_amount" class="form-control number-only" placeholder="Discount Amount ($)*" value="0" />
                            </div>
                            <div class="form-group" style="display: none;">
                                <label class="required">Deposit Amount</label>
                                <input type="text" name="sale_receive" class="form-control number-only remain-amount-deposit" placeholder="Deposit Amount ($)*" value="0" />
                            </div>
                            <div class="form-group">
                                <label>Promotion</label>
                                {!! Form::select('promotion',$promotion, null, ['class' => 'form-control select2','id'=>'promotion']) !!}
                            </div>
                            {{-- <div class="form-group" id="div-append-promotion-detail">
                                <label>Promotion Product</label>
                                <select name = 'promotion_detail[]' class="form-control select2" multiple>
                                    <option value="">Please Select</option>
                                </select>
                            </div> --}}
                            <table class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th colspan="4">Product Promotion</th>
                                    <th>
                                        <span class="pull-right button_primary btn-sm plus_ens fa fa-plus add-pos-promotion"></span>
                                    </th>
                                </tr>
                                </thead>
                                <tbody class="promotion-detail">
                                    <tr>
                                        <td width="15%">
                                            <label class="control-label" ><strong> Product Name : </strong></label>
                                        </td>
                                        <td>
                                            <select name = 'promotion_detail[]' class="form-control select2" class="product-detail-promotion">
                                                <option value="">Please Select</option>
                                            </select>
                                        </td>
                                        <td>
                                            <label class="control-label"><strong> Qty : </strong></label>
                                        </td>
                                        <td>
                                            <input type="text" name="product_qty[]" class="number-only form-control" placeholder="Product Qty">
                                        </td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="form-group">
                                <label for="required">Payment Policy</label>
                                {!! Form::select('payment_policy', $payment_policy, null, ['class' => 'form-control select2','id'=>'payment_policy']) !!}
                            </div>

                            <div class="form-group">
                                <label for="required">Payment Policy Detail</label>
                                <select name="payment_policy_detail" class="form-control select2" id="payment_policy_detail">
                                </select>
                            </div>

                            <table class="table table-striped table-bordered">
                                <thead>
                                <tr>
                                    <th colspan="8">Deposit Schedule</th>
                                    <th>
                                        <span class="pull-right button_primary btn-sm plus_ens fa fa-plus add"></span>
                                    </th>
                                </tr>
                                </thead>
                                <tbody class="resultbody">
                                <tr>
                                    <td width="7%">
                                        <label class="control-label"><strong> Step : </strong></label>
                                    </td>
                                    <td width="5%">
                                        <input type="text" class="form-control" name="payment_no[]" value="1" readonly="readonly">
                                    </td>
                                    <td width="15%">
                                        <label class="control-label" ><strong> Date : </strong></label>
                                    </td>
                                    <td>
                                        <input type="text" id="meng" class="form-control date-picker-a date_picker auto_date" value="{{date('d-m-Y')}}" name="itempro_date[]" >
                                    </td>
                                    <td width="15%">
                                        <label class="control-label"><strong> Amount : </strong></label>
                                    </td>
                                    <td>
                                        <input type="text" name="itempro_payamount[]" class="number-only form-control itempro_payamount meng_payment" placeholder="Pay Amount">
                                    </td>
                                    <td>
                                        <label class = "control-label">Type</label>
                                    </td>
                                    <td>
                                        <select name="type[]" class="select2">
                                            <option value="0">ប្រាក់កក់លើកដំបូង</option>
                                            <option value="1">ប្រាក់ត្រូវបង្គ្រប់ខែទី១</option>
                                            <option value="2">ប្រាក់ត្រូវបង់ខែទី១</option>
                                        </select>
                                    </td>
                                </tr>
                                </tbody>
                            </table>

                            <div class="form-group">
                                <label class="">Remark</label>
                                <textarea name="remark" id="" cols="30" rows="3" class="form-control"></textarea>
                            </div>
                            <div style="display: none;">
                                @if(session('cart')) @foreach(session('cart') as $id => $item_cart)
                                <span>
                                    <input type="hidden" name="saledetail_itemid[]" value="{{ $item_cart['item_id'] }}"><br>
                                    <input type="hidden" name="sale_item_code[]" value="{{ $item_cart['item_name'] }}"><br>
                                    <input type="hidden" name="saledetail_price[]" value="{{ $item_cart['item_price'] }}"><br>
                                    <input type="hidden" name="saledetail_cost[]" value="{{ $item_cart['item_cost'] }}"><br>
                                    <input type="hidden" name="project_type[]" value="1"><br>
                                    <input type="hidden" name="total_amount" class="form-control">
                                </span>
                                @endforeach @endif
                            </div>
                            <div class="form-group">
                                <div class="button-pos">
                                    <button type="submit" class="btn button_success pull-right">
                                        <i class="fa fa-credit-card-alt" aria-hidden="true"></i> Deposit</button>
                                </div>
                            </div>
                            {!! Form::close() !!}
                        </div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="pos-box" id="session-table">
                        <table id="cart" class="table table-hover table-condensed">
                            <thead>
                                <tr>
                                    <th width="10%">#</th>
                                    <th width="50%">Item Name</th>
                                    <th width="5%">Quantity</th>
                                    <th width="30%">Item Pirce</th>
                                    <th width="5%">Action</th>
                                </tr>
                            </thead>
                            <tbody id="tbody">


                                <?php $i = 0; ?>
                                @if(session('cart')) @foreach(session('cart') as $id => $item_cart)
                                <?php $i++ ?>
                                <?php $total += $item_cart['item_price'] * $item_cart['quantity'] ?>

                                <tr>
                                    <td data-th="#">
                                        {{ $i }}
                                    </td>
                                    <td data-th="Product">
                                        <div class="row">
                                            <div class="col-sm-12">
                                                {{ $item_cart['item_name'] }}
                                            </div>
                                        </div>
                                    </td>
                                    <td data-th="Quantity">
                                        {{ $item_cart['quantity'] }}
                                    </td>
                                    <td data-th="Price">${{ $item_cart['item_price'] }}</td>


                                    <td class="actions" data-th="">
                                        <button class="btn btn-danger btn-xs remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
                                    </td>
                                </tr>
                                @endforeach @endif

                            </tbody>
                            <tfoot>
                                <tr class="green">
                                    <td colspan="3" style="text-align:center">Total</td>
                                    <td id="total-amount">$ {{ $total }}</td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                        <!-- <div class="sum-footer">
                            <strong class="green pull-right">$ {{ $total }}</strong>
                        </div> -->
                        <input type="hidden" value="{{ $total }}" name="total" class="total">

                        <div class="col-sm-12 padding-0">
                            <div class="button-pos">
                                <button onclick="fun_back()" class="btn button_primary"><i class="fa fa-share icon-flipped"></i> Back</button>
                                <button onclick="fun_pay()" class="btn button_success"><i class="fa fa-shopping-cart"></i> Pay</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<div class="modal fade bs-modal-lg" id="addnew" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h3 class="modal-title">New Client</h3>
            </div>
            <br />
            <form action="{{route('add-new-client')}}" id="addForm">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-6 col-sm-6 col-md-6">
                            <div class="form-group">
                                <strong>First Name</strong>
                                <input type="text" name="first_name" class="form-control" placeholder="First Name" required="">
                            </div>
                            <div class="form-group">
                                <strong>Last Name</strong>
                                <input type="text" name="last_name" class="form-control" placeholder="First Name" required="">
                            </div>
                            <div class="form-group">
                                <strong>Gender</strong>
                                <select name="client_gender" id="" class="form-control select2">
                                    <option value="1">Male</option>
                                    <option value="2">Female</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <strong>Phone Number</strong>
                                <input type="text" name="client_phone1" class="form-control" placeholder="Phone Number" required="">
                            </div>
                            <div class="form-group">
                                <strong>Client Address</strong>
                                <input type="text" name="client_address" class="form-control" placeholder="Client Address" required="">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-danger"><i class="fa fa-close"></i> No</button>
                    <button type="submit" class="btn btn-success" data-toggle="modal"><i class="fa fa-save"></i> OK</button>
                </div>
            </form>
        </div>
    </div>
</div>
<div id="block-period" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Block Item</h4>
            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div class="row col-sm-12">
                            <div class="form-group main-block-option">
                                <label id="hour"></label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-warning btn-submit-block-period">Ok</button>
            </div>
        </div>

    </div>
</div>
<style>
    .thumbnail {
        display: block;
        padding: 0px !important;
        margin-bottom: 15px !important;
        line-height: 1.42857143;
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 4px;
        -webkit-transition: border .2s ease-in-out;
        -o-transition: border .2s ease-in-out;
        transition: border .2s ease-in-out;
    }

    .h4,
    .h5,
    .h6,
    h4,
    h5,
    h6 {
        margin-top: 0px !important;
        margin-bottom: 0px !important;
    }

    .btn-block-item-,
    .btn-unblock-item- {
        margin-top: 2px !important;
    }
</style>
@endsection @section('js')
<script type="text/javascript">
    var opt = '';
    $(document).on("click",".add-pos-promotion",function()
    {
        $(".promotion-detail").append(`<tr>
                                            <td width="15%">
                                                <label class="control-label" ><strong> Product Name : </strong></label>
                                            </td>
                                            <td>
                                                <select name = 'promotion_detail[]' class="form-control select2">
                                                    ${opt}
                                                </select>
                                            </td>
                                            <td>
                                                <label class="control-label"><strong> Qty : </strong></label>
                                            </td>
                                            <td>
                                                <input type="text" name="product_qty[]" class="number-only form-control" placeholder="Product Qty">
                                            </td>
                                            <td><span class="pull-right btn-sm button_danger delete fa fa-minus" onclick="$(this).closest('tr').remove()"></span></td>
                                        </tr>`
        );
        $(".select2").select2();
    });
    $(document).on("change","#date-deposit",function()
    {
        var deposit_date = $(this).val();
        $("#main-spinner").show();
        var route = "{{ route('get_promotion_by_deposit_date') }}";
        $.ajax({
            url:route,
            type:"POST",
            dataType:"JSON",
            data:{
                "_token":"{{ csrf_token() }}",
                "deposit_date":deposit_date
            },
            success:function(data)
            {
                var option = `<option value="">Please Select</option>`;
                $.each(data,function(index,value){
                    option += `<option value="${value.id}">${value.name}</option>`;
                });
                $("#promotion").html(option);
            },
            complete:function()
            {
                $("#main-spinner").hide();
            }
        });
    });
    $(document).on("change","#payment_policy",function()
    {
        var route = "{{route('get_policy_detail',':id')}}";
        route = route.replace(":id",$(this).val());
        $("#main-spinner").show();
        $.ajax({
            url:route,
            dataType:"JSON",
            type:"GET",
            success:function(data){
                var opt = `<option value="">Please Select</option>`;
                $.each(data,function(index,val){
                    opt+=`<option value="${val.id}">${val.name}</option>`;
                    console.log(val);
                });
                $("#policy_detail").show();
                $("#payment_policy_detail").empty();
                $("#payment_policy_detail").append(opt);
                $("#payment_policy_detail").attr("required");
                if(data == ""){
                    $("#policy_detail").hide();
                    $("#payment_policy_detail").removeAttr("required");
                }
            },
            error:function(){

            },
            complete:function()
            {
                $("#main-spinner").hide();
            }
        });
    });
    $(document).on("change","#sale-type-by",function()
    {
        $("#append-sale").empty();
        if($(this).val()==1)
        {
            $("#append-sale").append(`<div class="form-group">
                                    <label for="required">Select Employee(Sale)</label>
                                    {!! Form::select('employees[]', $employees, Auth::user()->id, ['class' => 'form-control select2','required']) !!}
                                </div>`);
             $(".select2").select2();
        }
        else{
            $("#append-sale").append(`
                            <div class="form-group">
                                <label for="required">Select Agency</label>
                                {!! Form::select('agency_id', $agencies, null, ['class' => 'form-control select2','id'=>'agency_id']) !!}
                            </div>

                            <div class="form-group">
                                <label for="required">Close Sale</label>
                                {!! Form::select('close_sale_id', $closesale, null, ['class' => 'form-control select2','id'=>'close_sale_id']) !!}
                            </div>`);
            $(".select2").select2();
        }
    });
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            } else {
                getData(page);
            }
        }
    });
    $(document).ready(function() {
        $(document).on('click', '.pagination a', function(event) {
            event.preventDefault();
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
            var myurl = $(this).attr('href');
            var page = $(this).attr('href').split('page=')[1];
            getData(page);
        });
    });

    function getData(page) {
        $('#main-spinner').show();
        $.ajax({
            url: '?page=' + page,
            type: "get",
            datatype: "html"
        }).done(function(data) {
            $('#main-spinner').hide();
            $("#item_list").empty().html(data);
            location.hash = page;
        }).fail(function(jqXHR, ajaxOptions, thrownError) {
            alert('No response from server');
        });
    }

    $(document).on('click', '.btn-block-item', function() {
        var e = $(this);
        var id = e.data('id');
        var hour = e.data('hour');

        var route = "{{route('block.item-stock')}}";
        if (hour) {
            $.confirm({
                title: 'Confirm!',
                content: 'This Item will be blocked for ' + hour + ' hours',
                buttons: {
                    confirm: function() {
                        $('#main-spinner').show();
                        $.ajax({
                            type: 'POST',
                            url: route,
                            data: {
                                _token: '{{ csrf_token() }}',
                                id: id,
                                hour: hour
                            },
                            dataType: 'json',
                            success: function(data) {
                                $('#main-spinner').hide();
                                if (data.success == true) {
                                    get_cart();
                                    var page = window.location.hash.replace('#', '');
                                    if (page == Number.NaN || page <= 0) {
                                        page = 1;
                                    }
                                    getData(page);
                                } else {
                                    $.alert(data.data);
                                }
                            }
                        });
                    },
                    cancel: function() {

                    }
                }
            });
        } else {
            $.alert("This item can not be blocked");
        }
    });


    $(document).ready(function() {
        $("#down_pay").hide();
        $("#policy_detail").hide();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $('#add').click(function() {
            $('#addnew').modal('show');
            $('#addForm')[0].reset();
        });
        $('#addForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this).serialize();
            var url = $(this).attr('action');
            $.ajax({
                type: 'POST',
                url: url,
                data: form,
                dataType: 'json',
                success: function() {
                    $('#addnew').modal('hide');
                    get_new_client();
                }
            });
        });
    });

    function get_new_client() {
        $('#client_id').empty();
        $('#main-spinner').show();
        $.ajax({
            type: 'GET',
            url: "{{route('pos-get-new-client')}}",
            dataType: 'json',
            success: function(data) {
                $('#main-spinner').hide();
                $.each(data, function(index, element) {
                    $("#client_id").append('<option value="' + element.id + '">' + element.client_firstname+' '+element.client_lastname + '</option>');
                });
            }
        });
    }

    function fun_pay() {
        $("#item_list").hide();
        $("#form-pay").show();

        var total = $("input[name=total]").val();
        $("input[name=total_amount]").val(total);
        document.getElementById('total_amount').innerHTML = total;

    }

    function fun_back() {
        $("#item_list").show();
        $("#form-pay").hide();
    }
    $(document).on('click', '.remove-from-cart', function(e) {
        e.preventDefault();
        var ele = $(this);
        var id = $(this).data('id');
        $.confirm({
            title: 'Confirm!',
            content: 'This Item will be remove from Cart!',
            buttons: {
                confirm: function() {
                    $('#main-spinner').show();
                    $.ajax({
                        url: "{{route('pos-remove-cart')}}",
                        method: "DELETE",
                        data: {
                            _token: '{{ csrf_token() }}',
                            id: ele.attr("data-id")
                        },
                        success: function(response) {
                            $('#main-spinner').hide();
                            if (response.success == true) {
                                get_cart();
                                var page = window.location.hash.replace('#', '');
                                if (page == Number.NaN || page <= 0) {
                                    page = 1;
                                }
                                getData(page);
                            }else{
                                $.alert("Something went wrong");
                            }
                        }
                    });
                },
                cancel: function() {},
            }
        });
    });
    $(document).on('change', '#project_id,#category_id,#inventory_id', function() {
        var project_id = $('#project_id').val();
        var item_name = $('#item_filter').val();
        var category_id = $('#category_id').val();
        var inventory_id = $('#inventory_id').find(':selected').val();
        project_id = (!project_id) ? null : project_id;
        category_id = (!category_id) ? null : category_id;
        inventory_id = (!inventory_id) ? null : inventory_id;
        item_name = (!item_name) ? null : item_name;
        var route = "{{route('create-pos')}}";
        var index_route = "{{route('create-pos')}}";
        var div = "";

        $('#item_list').empty();
        $('#main-spinner').show();
        $.ajax({
            type: "POST",
            url: route,
            dataType: 'html',
            data: {
                project_id: project_id,
                category_id:category_id,
                item_name:item_name,
                inventory_id:inventory_id,
                _token: '{{ csrf_token() }}',
            },
            success: function(response) {
                $('#item_list').html(response);
                $('#main-spinner').hide();
            },
            error: function() {
                $('#main-spinner').hide();  
                alert('Error');

            }
        });
    });
    $(document).on('change', '#promotion', function() {
        var promotion_id = $(this).val();
        $("#main-spinner").show();
        $.ajax({
            type: 'GET',
            url: '/realty/get-promotion-detail',
            dataType:'json',
            async:false,
            data: {
                'promotion_id': promotion_id
            },
            success: function(data){
                $("#main-spinner").hide();
                opt = `<option value="">Please Select</option>`;
                $.each(data,function(index,value)
                {
                    opt += `<option value = '${value.id}'>${value.promotion_detail+(value.product_unit_cost==null?"":"($"+value.product_unit_cost+")")}</option>`;
                });
                $("tbody.promotion-detail").find("tr").find("td:eq(1)").each(function(){
                    $(this).find("select").html(opt);
                });
                $(".select2").select2();
            }
        });
    });
    $(document).on('click', '.btn-add-to-cart', function() {
        var e = $(this);
        var id = $(this).data('id');
        var button = `<p class="btn-holder"><a href="#" data-id = "${id}" class="btn btn-danger btn-block text-center btn-remove-added-cart" role="button">Added To Cart</a> </p>`;
        var route = "{{route('add-to-cart',':id')}}";
        route = route.replace(":id", id);
        $('#main-spinner').show();
        $.ajax({
            type: 'GET',
            url: route,
            dataType: 'json',
            data: {
                'id': id
            },
            success: function(data) {
                $('#main-spinner').hide();
                if (data == 'error') {
                    alert("Item was Already Added!");
                } else if (data == 'success') {
                    get_cart();
                    var page = window.location.hash.replace('#', '');
                    if (page == Number.NaN || page <= 0) {
                        page = 1;
                    }
                    getData(page);
                } else {
                    alert('Not found');
                }
            }
        });
    });
    $(document).on('keyup', '#item_filter', function() {
        var item_name = $(this).val();
        var project_id = $('#project_id').find(":selected").val();
        var category_id = $('#category_id').find(':selected').val();
        var inventory_id = $('#inventory_id').find(':selected').val();
        var route = "{{route('pos-filter-by-name')}}";
        $('#main-spinner').show();
        if (item_name != "") {
            $.ajax({
                type: "POST",
                url: route,
                dataType: 'text',
                data: {
                    item_name: item_name,
                    project_id: project_id,
                    category_id: category_id,
                    inventory_id: inventory_id,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                    $('#main-spinner').hide();
                    $('#item_list').html(response);
                    var bg_img = $('.caption').data('url');
                    $(".caption").css("background-image", "url(" + bg_img + ")").addClass('bg-class');
                }
            });
        } else {
            window.location.reload();
        }
    });

    function get_cart() {
        $('#main-spinner').show();
        var route = "{{route('get-session-cart')}}";
        var table = "";
        var i = 1;
        var total = 0;
        $.ajax({
            type: 'GET',
            url: route,
            dataType: 'json',
            data: {
                _token: '{{ csrf_token() }}',
            },
            success: function(data) {
                $('#main-spinner').hide();
                $('#tbody').empty();
                $.each(data, function(index, val) {
                    total += val.item_price;
                    table += `<tr>
                                <td>${(i++)}</td>
                                <td>${val.item_name}</td>
                                <td>${val.quantity}</td>
                                <td>${val.item_price}</td>
                                <td><span data-id="${val.item_id}" class="btn btn-xs btn-danger fa fa-trash remove-from-cart"></span></td>
                            </tr>`;
                });
                $('#total-amount').text(total);
                $('#tbody').append(table);
            }
        });
    }

    var num_of_month = 0;
    var nso = 0;
    var num_of_row = 0;
    var first_month_pay = 0;
    $(document).on('click', '.add', function () {
        nso++;
        var date = lastdateST();
        var newDate = Loan_date_generator(date);
        var n = ($('.resultbody tr').length - 0);
        n++;
        var tr = '<tr>' +
            '<td width="7%">' +
            '<label class="control-label"><strong> Step : </strong></label>' +
            '</td>' +
            '<td width="5%">' +
            '<input type="text" class="form-control" name="payment_no[]" value="' + n + '" readonly="readonly">' +
            '</td>' +
            '<td width="15%">' +
            '<label class="control-label"><strong> Date : </strong></label>' +
            '</td>' +
            '<td>' +
            '<input type="text" id="meng_' + nso + '" class="form-control date-picker date_picker num_of_month auto_date" name="itempro_date[]" value="'+newDate+'" required="true">' +
            '</td>' +
            '<td width="15%">' +
            '<label class="control-label"><strong> Amount : </strong></label>' +
            '</td>' +
            '<td>' +
            '<input type="text" name="itempro_payamount[]" class="number-only form-control itempro_payamount meng_payment" placeholder="Pay Amount" required="true">' +
            '</td>' +
            '<td>'+
                '<label class = "control-label">Type</label>'+
            '</td>'+
            '<td>'+
                '<select name="type[]" class="select2">'+
                    '<option value="0">ប្រាក់កក់លើកដំបូង</option>'+
                    '<option value="1">ប្រាក់ត្រូវបង្គ្រប់ខែទី១</option>'+
                    '<option value="2">ប្រាក់ត្រូវបង់ខែទី១</option>'+
                +'</select>'+
            '</td>'+
            '<td>' +
            '<span class="pull-right btn-sm button_danger delete fa fa-minus"></span>' +
            '</td>' +
            '</tr>';
        $('.resultbody').append(tr);
        $(".select2").select2();
        autoPaymentDate();
        $('.date_picker').datepicker({
            yearRange: "-100:+0",
            dateFormat: "dd-mm-yy",
            changeMonth: true,
            changeYear: true
        });
    });
    function autoPaymentDate(){
        var index = 0;
        var date  = '';
        $('.auto_date').each(function(){
            if(index == 0){
                date = $(this).val();
            }else{
                date = Loan_date_generator(date);
                $(this).val(date);
            }
            index++;
        });
    }
    function lastdateST() {
        var date = '';
        $('.resultbody .date_picker').each(function () {
            date = $(this).val();
        });
        return date;
    }
    function Loan_date_generator(date) {
        var next_date = date;
        var next_date = next_date.split('-');
        var str_date = next_date[2] + '-' + next_date[1] + '-' + next_date[0];
        var next_date = new Date(str_date);
        next_date.setMonth(next_date.getMonth() + 1);
        var new_next_date = new Date(next_date);
        var dd = new_next_date.getDate();
        var mm = new_next_date.getMonth() + 1;

        var yyyy = new_next_date.getFullYear();
        if (dd < 10) {
            dd = '0' + dd;
        }
        if (mm < 10) {
            mm = '0' + mm;
        }
        return new_next_date = dd + '-' + mm + '-' + yyyy;
    }
    $(document).on('click', '.delete', function () {
        $(this).closest('tr').remove();
        autoPaymentDate();
    });
</script>
@endsection