@extends('layouts.user')

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>


{{-- Web site Title --}}

{{-- Content --}}
@section('content')
<?php
   $php_variable = 'string'; //Define our PHP variable. You can of course get the value of this variable however you need.
   ?>

<form method="POST" action="{{ route('qoutation.insert') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}" />
    <div class="form-group row">




        <div class="col-xs-4">
            <label for="ex1">Customer ID NO</label>
            <input class="form-control" onfocusout="getCustomerInfo()" name="id_no" type="number" id="c_id" placeholder="Enter ID No" required>
        </div>

        <div class="col-xs-4">
            <label for="ex1">Customer Mobile</label>
            <input class="form-control" type="number" id="c_mobile" name="contact" placeholder="Enter Mobile Number" required>
        </div>


        <div class="col-xs-4">
            <label for="ex1">Customer Name</label>
            <input class="form-control" id="c_name" type="text" name="name" placeholder="Enter Customer Name">
        </div>




        <div class="form-group removeleft">
            <br>
            <div class="col-xs-6">
                <label for="name_en">Select Pckage</label>
                <select class="form-control form-select" aria-label=".form-select-lg example" id="package_id" name="package" onchange="choosePackage()" required>
                    <?php
                    //    foreach ($packages as $package) :
                    //        echo '<option value="' . $package->id . '">' . $package->name_en . '</option>'; //close your tags!!
                    //    endforeach;
                   
                   ?>
                </select>
            </div>
            <div class="col-xs-6">
                <label for="name_en">Event Date</label>

                <div class='input-group datetime' id='datetimepicker2'>
                    <input type='text' name="date" class="form-control" required />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>


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


    </div>

    <div class="form-group row">




        <div class="col-xs-12">
            <label for="ex2">Select Services</label>
            <select class="select-2" name="ex2[]" multiple id="ex2" onchange="selectNum()" required>
                <?php
                //    foreach ($services as $service) :
                //        echo '<option value="' . $service->id . '">' . $service->name_en . '</option>'; //close your tags!!
                //    endforeach;
                   ?>
            </select>
        </div>
    </div>


    <div class="form-group row">
        <div class="col-xs-12">
            <table id="itemList" class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <td>#.</td>

                        <td>Name</td>
                        <td>Price</td>
                        <td>Quantity</td>
                        <td>Sub Total</td>
                        <td> </td>
                        <td> </td>
                        <!-- <td>Action</td> -->
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <div class="form-group row">

        <div class="col-xs-4">
            <label for="name_en">Actual Price</label>
            <input type='number' name="a_price" value="0" id="t_price" class="form-control" readonly />
        </div>


        <div class="col-xs-4">
            <label for="name_en">Dicount %</label>
            <input type='number' name="discount" value="0" id="discount" oninput="updatePrices()" class="form-control" />
        </div>
        <div class="col-xs-4">
            <label for="name_en">Final Payment</label>
            <input type='text' name="f_amount" value="0" id="final_payment" class="form-control" oninput="setTwoNumberDecimal(this)" readonly />
        </div>
    </div>




    <div class="form-group row">

        <div class="col-xs-6">
            <label for="name_en">Vat</label>
            <input type='number' name="vat" value="0" id="vat" oninput="setTwoNumberDecimal(this)" class="form-control" readonly />
        </div>
        <div class="col-xs-6">
            <label for="name_en">Total Amount</label>
            <input type='text' name="g_t_price" value="0" id="total_amount" class="form-control" oninput="setTwoNumberDecimal(this)" />
        </div>
    </div>





    <div class="form-group row">
        <div class="col-xs-4">
            <label for="name_en">Paid Amount</label>
            <input type='number' step="0.01" name="paid" value="0" id="paid" oninput="updatePrices()" class="form-control" />
        </div>
        <div class="col-xs-4">
            <label for="name_en">Pending Amount</label>
            <input type='number' name="pending" value="0" id="pending" class="form-control" readonly oninput="setTwoNumberDecimal(this)" />
        </div>

        <div class="col-xs-4">
            <label for="name_en">Payment Status</label>
            <input type='text' name="status" value="Pending" id="status" class="form-control" readonly />
        </div>

    </div>







    <div class="form-group">
        <label for="description_ar">
            Description
        </label>
        <textarea class="form-control" name="note" id="note_ar" rows="3"></textarea>
    </div>


    <button type="submit" class="btn btn-primary">Create</button>
</form>
@stop
<script>
    var t;
    services = JSON.parse('<?php echo  $services; ?>');
    var s_services = [];
    $(document).ready(function() {
        t = $('#itemList').DataTable({
            bFilter: false,
            bInfo: false,
            bPaginate: false,
        });
        //  var t = $('#itemList').DataTable({
        //      bFilter: false,
        //      bInfo: false,
        //      bPaginate: false,
        //  });
        //  $('#itemList').DataTable();
        // This will output the value selected.
    });

    function getCustomerInfo() {
        //  alert('works');
        $.ajax({

            // Our sample url to make request 
            url: "{{ route('customer.info') }}?id_no=" + document.getElementById("c_id").value,

            // Type of Request
            type: "GET",

            // Function to call when to
            // request is ok 
            success: function(data) {
                if (data.contact)
                    document.getElementById("c_mobile").value = data.contact;
                if (data.name)
                    document.getElementById("c_name").value = data.name;

            },

            // Error handling 
            error: function(error) {
                //  console.log(`Error ${error}`);
                alert('JSON.stringify(error)')
            }
        });

    }

    function RemoveRow(j) {
        //  t.row('.selected').remove().draw(false);
        var data = document.getElementById("qty" + j).value;
        //  alert(data);

    }

    function handleValueChange(j) {
        var data = document.getElementById("qty" + j).value;
        document.getElementById("g_total" + j).value = services[j].price * data;

        updateQtyInTable(j);
        updatePrices();
    }

    function updateQtyInTable(j) {
        var tempArr = [];
        //  alert(document.getElementById("id0").value);
        s_services.forEach((obj, i) => {
            if (obj.id == document.getElementById("id" + j).value) {
                tempArr.push({
                    ...obj,
                    qty: document.getElementById("qty" + j).value
                });
            } else {
                tempArr.push(obj);

            }

        });
        //  alert(JSON.stringify(tempArr))
        s_services = tempArr;

    }

    function updatePrices() {
        setTwoNumberDecimal(this);
        //  alert('jkhj');
        //  document.getElementById("g_total" + j).value = services[j].price * data;
        var price = 0;
        //  alert(price); 
        var i = 0;
        for (var option of document.getElementById('ex2').options) {
            if (option.selected) {
                //  t_price 
                //  selected.push(option.value);

                price = price + (document.getElementById("price" + i).value * document.getElementById("qty" + i).value);
                i = i + 1;
            }

        }
        //  alert(price);

        document.getElementById("t_price").value = price;
        document.getElementById("vat").value = (price / 100) * 5;
        document.getElementById("final_payment").value = price - document.getElementById("discount").value;
        document.getElementById("total_amount").value = price - document.getElementById("discount").value + (price / 100) * 5;
        document.getElementById("pending").value = document.getElementById("total_amount").value - document.getElementById("paid").value;
        if (document.getElementById("paid").value === document.getElementById("total_amount").value || document.getElementById("pending").value < 0)
            document.getElementById("status").value = 'Paid';
        else if (document.getElementById("pending").value === document.getElementById("total_amount").value)

            document.getElementById("status").value = 'Pending';
        else

            document.getElementById("status").value = 'Partially Paid';




    }

    function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(3);
    };

    function choosePackage() {
        //  $('#ex2').select2(); 
        $.ajax({

            // Our sample url to make request 
            url: "{{ route('packages.get_details') }}?id=" + document.getElementById("package_id").value,

            // Type of Request
            type: "GET",

            // Function to call when to
            // request is ok 
            success: function(data) {
                var tempArr = [];

                document.getElementById("discount").value = 0;
                data.forEach((obj, i) => {
                    document.getElementById("discount").value = obj.discount;
                    tempArr.push(obj.services_id);

                })


                $('#ex2').val(tempArr);
                $('#ex2').select2();


                t.clear().draw();
                selectNum();

            },

            // Error handling 
            error: function(error) {
                //  console.log(`Error ${error}`);
                alert(JSON.stringify(error))
            }
        });

    }

    function selectNum() {
        //  var strUser = document.getElementById("ex1").value;
        //  alert('sjkhk');


        //  alert(JSON.stringify(services));
        var selected = [];
        for (var option of document.getElementById('ex2').options) {
            if (option.selected) {

                selected.push(option.value);
            }

        }

        t.clear();
        var tempArr = [];
        selected.forEach((obj, i) => {
            var isAdded = false;
            s_services.forEach((obj_inner, i_inner) => {


                if (obj == obj_inner.id) {
                    services.forEach((obj_inner2, i_inner2) => {


                        if (obj_inner2.id == obj_inner.id) {

                            isAdded = true;
                            tempArr.push({
                                ...services[i_inner2],
                                qty: obj_inner.qty
                            })
                        }
                    });

                }
            });
            if (!isAdded) {
                services.forEach((obj_inner, i_inner) => {


                    if (obj == obj_inner.id) {

                        tempArr.push({
                            ...services[i_inner],
                            qty: 1
                        })
                    }
                });
            }

        });
        //  alert(JSON.stringify(tempArr))
        t.clear().draw();
        s_services = tempArr;
        s_services.forEach((obj, i) => {
            t.row.add([i + 1,
                obj.name_en,

                '<input class="form-control" name="price[]" type="number" id="price' + i + '"   placeholder="" value="' + obj.price + '"   required readonly>',
                '<input class="form-control" name="qty[]" type="number" min="0" id="qty' + i + '"   placeholder="" value="' + obj.qty + '" oninput="handleValueChange(' + i + ')" required>',
                '<input class="form-control" name="s_total[]" type="number" id="g_total' + i + '"   placeholder="" value="' + obj.price + '"  readonly>',
                '<input type="hidden"  class="form-control"  name="id[]"  id="id' + i + '"   placeholder="" value= "' + obj.id + '"  readonly>',
                '<input type="hidden"  class="form-control"  name="names[]"  id="name' + i + '"   placeholder="" value= "' + obj.name_en + '"  readonly>',

            ]).draw(true);
        });
        updatePrices();

        id(!selected)
        t.clear().draw();

    }
</script>