{% extends 'back.html.twig' %}

{% block title %} Quotations - Edit Quotation{% endblock %}

{% block body %}

        <div class="app-content-header">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-6"><h3 class="mb-0">Edit Quotation ({{ quotation.referenceNumber }})</h3></div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-end">
                            <li class="breadcrumb-item"><a href="{{ path('app_admin_dashboard') }}">Home</a></li>
                            <li class="breadcrumb-item"><a href="{{ path('admin_quotation_index') }}">Quotations</a></li>
                            <li class="breadcrumb-item active">Edit Quotation</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <div class="app-content">
            <div class="container-fluid">
                <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header with-border" style="padding-bottom: 0px;">
                                    {% include '@Quotation/quotation/partials/quotation-header-links.html.twig' %}
                                </div>
                                <div class="card-body">

                                    <form class="form-horizontal" action="javascript:void(0)">

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="quotation_date" class="col-sm-12 control-label">Quotation Date <span class="compulsory">*</span></label>
                                                    <div class="col-sm-12">
                                                        <input type="text" class="form-control datepicker_fields" id="quotation_date" placeholder="Quotation Date"
                                                               autocomplete="off" value="{{ quotation.date | date('Y-m-d') }}">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="expiry_date" class="col-sm-12 control-label">Expiry Date</label>
                                                    <div class="col-sm-12">
                                                        <input type="text" class="form-control datepicker_fields" id="expiry_date" placeholder="Expiry Date"
                                                               autocomplete="off" value="{{ quotation.expiry | date('Y-m-d') }}">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="quotation_customer" class="col-sm-12 control-label">{{ 'Customer'|trans }} <span class="compulsory">*</span></label>
                                                    <div class="col-sm-12">
                                                        <select class="form-control select2_fields" id="quotation_customer">
                                                            {% for customer in customers %}
                                                                <option value="{{ customer.id }}"
                                                                    {% if quotation.customer.id == customer.id %} selected="selected" {% endif %}
                                                                >{{ customer.companyName }}</option>
                                                            {% endfor %}
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">

                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-8">
                                                <div class="form-group">
                                                    <label for="quotation_address" class="col-sm-12 control-label">Address<span class="compulsory">*</span></label>
                                                    <div class="col-sm-12">
                                                        <input type="text" class="form-control" id="quotation_address" placeholder="Address" value="{{ quotation.address }}">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="discount_percentage" class="col-sm-12 control-label">Discount Percentage(%)</label>
                                                    <div class="col-sm-12">
                                                        <input type="number" class="form-control" id="discount_percentage" placeholder="Discount Percentage" value="{{ quotation.discount }}">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="deposit_needed" class="col-sm-12 control-label">Deposit Needed</label>
                                                    <div class="col-sm-12">
                                                        <input type="checkbox" class="form-control form-check-input" id="deposit_needed"
                                                                {% if quotation.depositNeeded %} checked="checked" {% endif %}>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="deposit_percentage" class="col-sm-12 control-label">Deposit Percentage </label>
                                                    <div class="col-sm-12">
                                                        <input type="number" class="form-control" id="deposit_percentage" placeholder="Deposit Percentage"
                                                               name="deposit_percentage" {% if quotation.depositNeeded == false %} disabled {% endif %} value="{{ quotation.depositPercentage }}">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <table class="table table-bordered" id="quotation_detail_table" style="background-color: #d5dcd8;">
                                            <thead>
                                            <tr>
                                                <td class="text-center"><strong>Qty</strong></td>
                                                <td class="text-center"><strong>Description</strong></td>
                                                <td class="text-center"><strong>Unit Price</strong></td>
                                                <td class="text-center"><strong>Total</strong></td>
                                                <td><button class="btn btn-success add-more" type="button"><i class="glyphicon glyphicon-plus"></i> New</button></td>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            {% for quotationDetail in quotation.quotationDetails %}
                                                <tr class="after-add-more">
                                                    <td class="text-center">
                                                        <div class="input-group">
                                                            <input type="hidden" class="item_id" value="{{ quotationDetail.id }}"/>
                                                            <input type="number" class="form-control item_qty quotation_detail_row" placeholder="Qty" value="{{ quotationDetail.quantity }}"/>
                                                        </div>
                                                    </td>
                                                    <td class="text-center">
                                                        <div class="input-group">
                                                            <input type="text" class="form-control item_description" placeholder="Description" value="{{ quotationDetail.description }}"/>
                                                        </div>
                                                    </td>
                                                    <td class="text-center">
                                                        <div class="input-group">
                                                            <input type="text" class="form-control unit_price quotation_detail_row" placeholder="Unit Price" value="{{ quotationDetail.unitPrice }}"/>
                                                        </div>
                                                    </td>
                                                    <td class="text-center">
                                                        <div class="input-group">
                                                            {% set total = quotationDetail.quantity * quotationDetail.unitPrice %}
                                                            <input type="text" class="form-control item_total" placeholder="Total" readonly="true" value="{{ total | number_format(2) }}"/>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="input-group-btn">
                                                            <button class="btn btn-danger remove" type="button"><i class="bi bi-trash"></i></button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            {% endfor %}
                                            <tr class="copy-fields d-none">
                                                <td class="text-center">
                                                    <div class="input-group">
                                                        <input type="hidden" class="item_id" value=""/>
                                                        <input type="number" class="form-control item_qty quotation_detail_row" placeholder="Qty"/>
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <div class="input-group">
                                                        <input type="text" class="form-control item_description" placeholder="Description"/>
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <div class="input-group">
                                                        <input type="text" class="form-control unit_price quotation_detail_row" placeholder="Unit Price"/>
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <div class="input-group">
                                                        <input type="text" class="form-control item_total" placeholder="Total" readonly="true"/>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="input-group-btn">
                                                        <button class="btn btn-danger remove" type="button"><i class="bi bi-trash"></i></button>
                                                    </div>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>

                                        <button type="button" class="btn btn-primary" id="updateQuotationBtn" style="float: right;">Update Quotation</button>

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

{% endblock %}

{% block javascripts %}

    <script type="text/javascript">

        $( document ).ready(function() {

            $('.datepicker_fields').datepicker({dateFormat: 'yy-mm-dd',todayHighlight: true});

            $("#deposit_needed").on("change", function () {
                if ($(this).prop('checked')) {
                    $("#deposit_percentage").prop("disabled", false);
                }
                else {
                    $("#deposit_percentage").prop("disabled", true);
                }
            });


            var availableTags = [
                "Supply & Install Alloy Infill - Window",
                "Supply & Install Alloy Infill - Door",
                "Supply & Install Alloy C/Plate - up to 1.0m",
                "Supply & Install Alloy C/Plate - from 1.1m to 2.4m",
                "Supply & Install Alloy C/Plate Flat Bar - up to 1.0m",
                "Supply & Install Alloy C/Plate Flat Bar - from 1.1m to 2.4m",
                "Supply Only Alloy Infill - Window",
                "Supply Only Alloy Infill - Door",
                "Supply Only Alloy C/Plate -  up to 1.0m",
                "Supply Only Alloy C/Plate - from 1.1m to 2.4m",
                "Supply Only Alloy C/Plate Flat Bar - up to 1.0m",
                "Supply Only Alloy C/Plate Flat Bar - from 1.1m to 2.4m"
            ];

            $( ".item_description" ).autocomplete({
                source: availableTags,
                minLength: 0
            })
            .focus(function() {
                $(this).autocomplete('search', $(this).val());
            });


            //here first get the contents of the div with name class copy-fields and add it to after "after-add-more" div class.
            $(".add-more").on("click",function() {
                var html = $(".copy-fields").html();
                $('#quotation_detail_table tr:first').after("<tr>"+html+"</tr>")
                $(".quotation_detail_row").on("keyup",function() {
                    var item_qty = $(this).closest('tr').find(".item_qty").val();
                    var unit_price = $(this).closest('tr').find(".unit_price").val();
                    var row_total = item_qty*unit_price;
                    $(this).closest('tr').find(".item_total").val(row_total);
                });

                $( ".item_description" ).autocomplete({
                    source: availableTags,
                    minLength: 0
                })
                .focus(function() {
                    $(this).autocomplete('search', $(this).val());
                });

            });


            $("body").on("click",".remove",function(){
                $(this).parents("tr").remove();
            });


            //function to calculate row total
            $(".quotation_detail_row").on("keyup",function() {
                var item_qty = $(this).closest('tr').find(".item_qty").val();
                var unit_price = $(this).closest('tr').find(".unit_price").val();
                var row_total = item_qty*unit_price;
                $(this).closest('tr').find(".item_total").val(row_total);
            });


            $("#updateQuotationBtn").on("click",function() {

                var id = {{ quotation.id }};
                var date = $.trim($("#quotation_date").val());
                var expiry = $.trim($("#expiry_date").val());
                var customer = $.trim($("#quotation_customer").val());
                var address = $.trim($("#quotation_address").val());
                var percentage = $.trim($("#discount_percentage").val());
                var depositNeeded = ($("#deposit_needed").prop("checked"))? 1 : 0;
                var depositPercentage = $.trim($("#deposit_percentage").val());

                var item_id = $(".item_id");
                var item_qty = $(".item_qty");
                var item_description = $(".item_description");
                var unit_price = $(".unit_price");
                var quotation_detail_array = [];

                if (
                    validateInput(date, "Quotation Date") &&
                    validateInput(customer, "Customer") &&
                    validateInput(address, "Address")
                )
                {

                    for (var i = 0; i < item_qty.length; i++) {
                        if ($.trim($(item_qty[i]).val()) == null) {
                            new Noty({
                                theme: 'metroui',
                                type: 'error',
                                text: "<strong>Error!</strong> Please Enter Job Quantity!",
                                timeout: 2000
                            }).show();
                        }
                        else {
                            var sub_array = {
                                "quantity": $(item_qty[i]).val(),
                                "description": $(item_description[i]).val(),
                                "unitPrice": $(unit_price[i]).val(),
                                "id": $(item_id[i]).val()
                            };
                        }

                        quotation_detail_array.push(sub_array);
                    }

                    $.ajax({
                        type: 'post',
                        url: '{{ path('api_quotation_edit') }}',
                        datatype: 'json',
                        data: {
                            id : id,
                            date : date,
                            expiry : expiry,
                            address : address,
                            customer : customer,
                            percentage : percentage,
                            depositNeeded : depositNeeded,
                            depositPercentage : depositPercentage,
                            quotation_details:JSON.stringify(quotation_detail_array)
                        }
                    })
                    .done(function (data) {
                        Swal.fire(
                            'Success!',
                            'Quotation Updated Successfully!',
                            'success'
                        );

                        setTimeout(function(){ location.reload(); }, 2500);
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        new Noty({
                            theme: 'metroui',
                            type: 'error',
                            text: "<strong>Error!</strong> Failed to Update Quotation!",
                            timeout: 2000
                        }).show();
                    });
                }
            });
        });
    </script>

{% endblock %}
