{% csrf_token %}
{{ new_line_item_form.media.css }}
{{ new_line_item_form.media.js }}
{% load static %}
{% if quote_permission > 1 %}

    <div class="card mt-4">
        <div class="card-header">
            <h2>New Line Item</h2>
        </div>
        <div class="card-body">
            {% if not product_and_service_results %}
                <div class="alert alert-danger">
                    Please note - there are no products or services. Please set these options up, or if you do not have access, request your administrator to do so.
                </div>
            {% endif %}
            <!--Select the product or service-->
            <div class="form-row">
                <div class="form-group col-md2">
                    <label for="id_product_price">Product Price</label>
                    {{ new_line_item_form.product_price }}
                </div>
                <div class="form-group col-md-2">
                    <label for="id_quantity">Quantity</label>
                    {{ new_line_item_form.quantity }}
                </div>
                <div class="form-group col-md-6">
                    <label for="id_product_and_service">Product and Services</label>
                    {{ new_line_item_form.product_and_service }}
                </div>
            </div>

            <div style="display:none;" id="tax_table">
                <div class="form-group col-md-12" id="product_description_div">
                    <label for="id_product_description">Product Description</label>
                    {{ new_line_item_form.product_description }}
                </div>

                <!-- Fine tune it's price/Discount price -->
                <div class="form-row mt-4">
                    <div class="form-group col-md-3">
                        <label  for="id_discount_choice">Discount Type</label>
                        {{ new_line_item_form.discount_choice }}
                    </div>
                    <div class="form-group col-md-3">
                        <label  for="id_discount_percent">Discount Percentage</label>
                        {{ new_line_item_form.discount_percent }}
                    </div>
                    <div class="form-group col-md-3">
                        <label  for="id_discount_amount">Discount Amount</label>
                        {{ new_line_item_form.discount_amount }}
                    </div>
                    <div class="form-group col-md-3">
                        <label  for="id_sales_price">Sales Price</label>
                        {{ new_line_item_form.sales_price }}
                    </div>
                </div>

                <!-- Tax amount -->
                <div class="form-row mt-4">
                    <div class="form-group col-md-2">
                        <label for="">Tax Percent</label>
                        {{ new_line_item_form.tax }}
                    </div>
                    <div class="form-group col-md-2">
                        <label for="">Tax Amount</label>
                        {{ new_line_item_form.tax_amount }}
                    </div>
                    <div class="form-group col-md-3">
                        <label for="">Total</label>
                        {{ new_line_item_form.total}}
                    </div>
                </div>

                <!-- Product note -->
                <div class="form-row">
                    {{ new_line_item_form.product_note }}
                </div>

                <!-- Save button -->
                <div class="form-row mt-4">
                    <input type="submit" value="Submit Line Item" class="btn btn-primary form-control">
                </div>
            </div>
        </div>
    </div>
{% endif %}


<script>
    /*
    Method
    ~~~~~~
    1.) When the user changes the product/service the system will determine which one it is
    2.) It will apply the default values and hide unwanted fields
    3.) If it is a product, it will extract the base values from the database
     */
    $("#id_product_and_service").on('change', function (evt, params) {
        var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
        var product_id = $(this.options[this.selectedIndex]).val();

        //If user selects the first option
        if (product_id == "------") {
            //Reset values
            $("#discount_table").css("display","none");
            $("#tax_table").css("display","none");
            $("#id_product_price").val("");
            $("#id_quantity").val("1");

            //Exit
            return;
        }

        //Unhide tables
        $("#discount_table").css("display","");
        $("#tax_table").css("display","");


        // Obtain the product/service information
        $.getJSON('/lookup_product/' + product_id, function (data) {
           /*
           We are now looking up the product information from the JSON function.
           We now have to look into each element of the JSON (even though there
           is only one), to extract the values inside.
           */
            $.each(data, function (i,f) {
                /*
                Now we can extract the required information using the following
                code f.fields.product_or_service
                 */
                $("#id_product_cost").val(f.fields.product_cost);
                $("#id_product_description").val(f.fields.product_description);
                $("#id_product_price").val(f.fields.product_price);


                //Clear the discount and tax amounts
                $("#id_discount_choice").val($("#id_discount_choice option:first").val());
                $("#id_discount_percent").val("0");
                $("#id_discount_amount").val("0");

                $("#id_tax").val($("#id_tax option:first").val());



                //Hide the product description IF THERE IS NONE
                if (f.fields.product_description == "") {
                    $("#product_description_div").css("display","none");
                } else {
                    $("#product_description_div").css("display","");
                }
            });
            //Update the total :)
            update_total();
        });
    });


    function discount_type_change() {
        /*
        If the discount type is a percentage then the following occurs;
        -- Discount Percentage is read write
        -- Discount Amount is read only - automatically updated in update_total() function

        If the discount type is a discount then the following occurs;
        -- Discount Percentage is read only and zero'ed off
        -- Discount Amount is read write
         */
        if ($("#id_discount_choice").val() == "Percentage") {
            //Discount Percentage is read write
            $("#id_discount_percent").prop('readonly', false);
            $("#id_discount_percent").css("background-color", "");
            $("#id_discount_percent").val('0');

            //Discount Amount is read only - automatically updated in update_total() function
            $("#id_discount_amount").prop("readonly", true);
            $("#id_discount_amount").css("background-color", "aliceblue");
            $("#id_discount_amount").val('0');
        } else {
            //Discount Percentage is read only and zero'ed off
            $("#id_discount_percent").prop('readonly', true);
            $("#id_discount_percent").css("background-color", "aliceblue");
            $("#id_discount_percent").val('0');

            //Discount Amount is read write
            $("#id_discount_amount").prop("readonly", false);
            $("#id_discount_amount").css("background-color", "");
            $("#id_discount_amount").val('0');
        }

        update_total();

    }


    function update_total() {
        //Get variables
        var product_price = parseFloat($("#id_product_price").val());
        var quantity = $("#id_quantity").val(); //Will always be an int

        //Check to make sure quantity is an INT
        if (quantity != parseFloat($("#id_quantity").val())) {
            $("#id_quantity").val(quantity);
        }

        /*
        If the discount type is nothing, we only need to extract the discount amount value.
        HOWEVER if it is a percentage, then we need to calculate that percentage, and apply
        it to the discount amount field (which we will then extract).
         */
        if ($("#id_discount_choice").val() == "Percentage") {
            //We need to calculate that percentage
            var discount_percent = parseFloat($("#id_discount_percent").val());
            var discount_amount = parseFloat(product_price * quantity * parseFloat(discount_percent / 100));

            //We will add the discount amount to the page
            $("#id_discount_amount").val(discount_amount.toFixed(2));
        }

        //Extract the discount amount
        var discount_amount = $("#id_discount_amount").val();

        //Calculate the sales price and populate it
        var sales_price = parseFloat(quantity * product_price - discount_amount);
        $("#id_sales_price").val(sales_price.toFixed(2));


        //Tax is calculated OFF sales price
        tax_amount = 0;
        if ($("#id_tax").val() == "") {
            //There is no tax applied. ZERO
            $("#id_tax_amount").val(0);
        } else {
            //There is a tax amount.
            tax_percentage = parseFloat($("#id_tax").children("option").filter(":selected").text()/100);
            tax_amount = parseFloat(tax_percentage * sales_price);
            $("#id_tax_amount").val(tax_amount.toFixed(2));
        }


        //Total is the sales price + tax
        var total = parseFloat(sales_price + tax_amount)
        $("#id_total").val(total.toFixed(2));
    }
</script>
