{% extends "./template.html" %}
{% block content %}
{% load static %}
    <script type="text/javascript" src="{% static 'NearBeach/javascript/check_dates.js' %}"></script>
    <script type="text/javascript" src="{% static 'NearBeach/javascript/new_opportunity.js' %}"></script>
    <script type="text/javascript" src="{% static 'NearBeach/widgets/datetimepicker/jquery.datetimepicker.full.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'NearBeach/javascript/assigned_user_list.js' %}"></script>
    <link rel="stylesheet" href="{% static 'NearBeach/widgets/datetimepicker/jquery.datetimepicker.min.css' %}">
<script>
    function on_page_load() {
        //Load AJAX components
        reload_list_of_line_items();
        reload_new_line_item();
        reload_responsible_customer();
        load_email_history();

        load_assigned_group_list();
        load_assigned_group_add();
        load_assigned_user_list();
        load_assigned_user_add();

        //Setup the datetime widgets
        $("#id_quote_valid_till").datetimepicker({
            scrollInput: false,
            format:'Y-m-d H:i:00',
            allowTimes: [
                '00:00','00:05','00:10','00:15','00:20','00:25','00:30','00:35','00:40','00:45','00:50','00:55',
                '01:00','01:05','01:10','01:15','01:20','01:25','01:30','01:35','01:40','01:45','01:50','01:55',
                '02:00','02:05','02:10','02:15','02:20','02:25','02:30','02:35','02:40','02:45','02:50','02:55',
                '03:00','03:05','03:10','03:15','03:20','03:25','03:30','03:35','03:40','03:45','03:50','03:55',
                '04:00','04:05','04:10','04:15','04:20','04:25','04:30','04:35','04:40','04:45','04:50','04:55',
                '05:00','05:05','05:10','05:15','05:20','05:25','05:30','05:35','05:40','05:45','05:50','05:55',
                '06:00','06:05','06:10','06:15','06:20','06:25','06:30','06:35','06:40','06:45','06:50','06:55',
                '07:00','07:05','07:10','07:15','07:20','07:25','07:30','07:35','07:40','07:45','07:50','07:55',
                '08:00','08:05','08:10','08:15','08:20','08:25','08:30','08:35','08:40','08:45','08:50','08:55',
                '09:00','09:05','09:10','09:15','09:20','09:25','09:30','09:35','09:40','09:45','09:50','09:55',
                '10:00','10:05','10:10','10:15','10:20','10:25','10:30','10:35','10:40','10:45','10:50','10:55',
                '11:00','11:05','11:10','11:15','11:20','11:25','11:30','11:35','11:40','11:45','11:50','11:55',
                '12:00','12:05','12:10','12:15','12:20','12:25','12:30','12:35','12:40','12:45','12:50','12:55',
                '13:00','13:05','13:10','13:15','13:20','13:25','13:30','13:35','13:40','13:45','13:50','13:55',
                '14:00','14:05','14:10','14:15','14:20','14:25','14:30','14:35','14:40','14:45','14:50','14:55',
                '15:00','15:05','15:10','15:15','15:20','15:25','15:30','15:35','15:40','15:45','15:50','15:55',
                '16:00','16:05','16:10','16:15','16:20','16:25','16:30','16:35','16:40','16:45','16:50','16:55',
                '17:00','17:05','17:10','17:15','17:20','17:25','17:30','17:35','17:40','17:45','17:50','17:55',
                '18:00','18:05','18:10','18:15','18:20','18:25','18:30','18:35','18:40','18:45','18:50','18:55',
                '19:00','19:05','19:10','19:15','19:20','19:25','19:30','19:35','19:40','19:45','19:50','19:55',
                '20:00','20:05','20:10','20:15','20:20','20:25','20:30','20:35','20:40','20:45','20:50','20:55',
                '21:00','21:05','21:10','21:15','21:20','21:25','21:30','21:35','21:40','21:45','21:50','21:55',
                '22:00','22:05','22:10','22:15','22:20','22:25','22:30','22:35','22:40','22:45','22:50','22:55',
                '23:00','23:05','23:10','23:15','23:20','23:25','23:30','23:35','23:40','23:45','23:50','23:55'
            ]
        });
    }

    function reload_new_line_item() {
        $.ajax({
            url: '/quote_new_line_item/{{ quote_id }}/',
            data: {},
            dataType: 'HTML',
            type:'GET',
            success: function(data) {
                $('#new_line_item').html(data);
            },
            error: function(){
                new_error("Sorry - line item failed for some reason.");
            }
        });
    }

    function reload_list_of_line_items() {
        $.ajax({
            url: '/quote_list_of_line_items/{{ quote_id }}/',
            data: {},
            dataType: 'HTML',
            type:'GET',
            success: function(data) {
                $('#list_of_line_items').html(data);
            },
            error: function(){
                new_error("Sorry - list of line item failed for some reason.");
            }
        });
    }


    function reload_responsible_customer() {
        $.ajax({
            url: '/quote_responsible_customer/{{ quote_id }}/',
            data: {},
            dataType: 'HTML',
            type:'GET',
            success: function(data) {
                $('#list_of_responsible_customers').html(data);
            },
            error: function(){
                alert("Sorry - loading responsible customers failed.");
            }
        });
    }

    function delete_line_item(line_item) {
        $.ajax({
            url: '/quote_delete_line_item/' + line_item + '/',
            data: {},
            dataType: 'HTML',
            type:'GET',
            success: function(data) {
                reload_list_of_line_items();
            },
            error: function(){
                new_error("Sorry - list of line item failed for some reason.");
            }
        });
    }

    function responsible_customer_changed() {
        customer_id = $("#responsible_customer").val()

        $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                url: '/quote_responsible_customer/{{ quote_id }}/' + customer_id + '/',
                data: {},
                dataType: 'HTML',
                type: 'POST',
                success: function (data) {
                    //RELOAD STUFF
                    $('#list_of_responsible_customers').html(data);
                },
                error: function() {
                    new_error("Sorry, could not add a new responsible customer. Please try again soon.")
                }
            })
    }

</script>

<body onload="on_page_load()">
    <div class="card mt-4">
        <div class="card-header">
            <h2><span class="quote_or_invoice">{{ quote_or_invoice }}</span>{{ quotes_results.quote_id }}</h2>
        </div>
        <div class="card-body">
            <form action={% url 'quote_information' quote_id %} method="post" class="new_quote">
                {% csrf_token %}
                {{ quote_information_form.media }}
                {{ quote_information_form.media.css }}
                {{ quote_information_form.media.js }}
                <div class="form-group">
                    <label for="id_quote_title">Quote Title: </label>
                    {{ quote_information_form.quote_title }}
                </div>
                <div class="form-group">
                    <label for="id_quote_terms">Quote Terms: </label>
                    {{ quote_information_form.quote_terms }}
                </div>

                <div class="form-group">
                    <label>Time zone: {{ timezone }}</label>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="id_quote_stage_id"><span class="quote_or_invoice">{{ quote_or_invoice }}</span> Stage:</label>
                        {{ quote_information_form.quote_stage_id }}
                    </div>

                    <div class="form-group col-md-6">
                        <label for="id_quote_valid_till"><span class="quote_or_invoice">{{ quote_or_invoice }}</span> Valid To:</label>
                        {{ quote_information_form.quote_valid_till }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="id_customer_notes">Customer Notes: </label>
                    {{ quote_information_form.customer_notes }}
                </div>
                <div class="form-group">
                    <label for="id_quote_billing_address">Quote Billing Address: </label>
                    {{ quote_information_form.quote_billing_address }}
                </div>

                <div class="form-row col-md-12">
                    <input type="submit" value="Update {{ quote_or_invoice }}" class="btn btn-primary col-md-6">
                    {% if quote_or_invoice == 'Quote' %}
                        <input type="submit" value="Create Invoice" name="create_invoice" id="create_invoice" class="btn btn-warning col-md-6">
                    {% else %}
                        <input type="submit" value="Revert to Quote" name="revert_quote" id="revert_quote" class="btn btn-warning col-md-6">
                    {% endif %}
                </div>
            </form>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h2>Quote Links</h2>
        </div>
        <div class="card-body">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <td>Link</td>
                        <td>Description</td>
                    </tr>
                </thead>
                {% if quotes_results.project_id %}
                    <tr>
                        <td><a href="{% url 'project_information' quotes_results.project_id.project_id %}">PRO{{ quotes_results.project_id.project_id }}</a></td>
                        <td>{{ quotes_results.project_id }}</td>
                    </tr>
                {% endif %}
                {% if quotes_results.task_id %}
                    <tr>
                        <td><a href="{% url 'task_information' quotes_results.task_id.task_id %}">TASK{{ quotes_results.task_id.task_id }}</a></td>
                        <td>{{ quotes_results.task_id }}</td>
                    </tr>
                {% endif %}
                {% if quotes_results.organisation_id %}
                    <tr>
                        <td><a href="{% url 'organisation_information' quotes_results.organisation_id.organisation_id %}">ORG{{ quotes_results.organisation_id.organisation_id }}</a></td>
                        <td>{{ quotes_results.organisation_id }}</td>
                    </tr>
                {% endif %}
                {% if quotes_results.customer_id %}
                    <tr>
                        <td><a href="{% url 'customer_information' quotes_results.customer_id.customer_id %}">CUST{{ quotes_results.customer_id.customer_id }}</a></td>
                        <td>{{ quotes_results.customer_id }}</td>
                    </tr>
                {% endif %}
                {% if quotes_results.opportunity_id %}
                    <tr>
                        <td><a href="{% url 'opportunity_information' quotes_results.opportunity_id.opportunity_id %}">OPP{{ quotes_results.opportunity_id.opportunity_id }}</a></td>
                        <td>{{ quotes_results.opportunity_id.opportunity_name }}</td>
                    </tr>
                {% endif %}
            </table>

            {% if quotes_results.opportunity_id and cust_or_org_connected == False %}
                <hr>
                <h3>Quote Issue</h3>
                Please note - this current quote is not connected to either a customer or organisation. Please consider
                linking to either;
                <ul>
                    <li><a href="{% url 'new_quote_link' quotes_results.quote_id 'organisation' %}">Organisation</a></li>
                    <li><a href="{% url 'new_quote_link' quotes_results.quote_id 'customer' %}">Customer</a></li>
                </ul>
            {% endif %}
        </div>
    </div>

    {% if permission > 1 %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Responsible Customers</h2>
            </div>
            <div class="card-body">
                <form method="post" class="list_of_responsible_customers" id="list_of_responsible_customers"></form>
            </div>
        </div>
    {% endif %}

    <form method="POST" class="new_line_item" id="new_line_item"></form>

    <div class="card mt-4">
        <div class="card-header">
            <h2>Line Items</h2>
        </div>
        <div class="card-body">
            <form method="post" class="list_of_line_items" id="list_of_line_items"></form>
        </div>
    </div>



    <div class="card mt-4">
        <div class="card-header">
            <h2>Email History</h2>
        </div>
        <div class="card-body" id="email_history">
            Loading...
        </div>
    </div>


    {% if quote_template_results %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Quote Preview</h2>
            </div>
            <div class="card-body" id="quote_preview">
                <div class="form-row">
                    <select id="quote_template">
                        {% for row in quote_template_results %}
                            <option value="{{ row.quote_template_id }}">{{ row.quote_template_description }}</option>
                        {% endfor %}
                    </select>
                    <input type="button" value="Preview Quote" onclick="preview_quote()" class="btn-primary">
                    <input type="button" value="Download PDF" onclick="download_quote()" class="btn-secondary">
                </div>
            </div>
        </div>
    {% endif %}



    {% if permission >= 3 %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Assigned Users</h2>
            </div>
            <div class="card-body">
                <form method="post" class="assigned_users" id="assigned_users">
                    Loading...
                </form>
                <div id="assigned_user_list">Loading list...</div>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h2>Assigned Groups</h2>
            </div>
            <div class="card-body">
                <form method="post" class="assigned_groups" id="assigned_groups">
                    Loading...
                </form>
                <div id="assigned_group_list">Loading list...</div>
            </div>
        </div>
    {% endif %}


<script>
    $("#assigned_users").on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/assigned_user_add/{{ quote_id }}/quote/',
            data: $(this).serialize(),
            success: function() {
                load_assigned_user_list();
                load_assigned_user_add();
            },
            error: function() {
                new_error("Sorry, project assigned users did not save. Please try again.");
            }
        })
    });


    $("#assigned_groups").on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/assigned_group_add/{{ quote_id }}/quote/',
            data: $(this).serialize(),
            success: function() {
                load_assigned_group_add();
                load_assigned_group_list();
            },
            error: function() {
                new_error("Sorry, project assigned users did not save. Please try again.");
            }
        })
    });

    $("#new_line_item").on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/quote_new_line_item/{{ quote_id }}/',
            data: $(this).serialize(),
            success: function() {
                reload_new_line_item();
                reload_list_of_line_items();
            },
            error: function () {
                new_error("There has been an error submitting the new line item");
            }
        })
    });
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    function load_email_history() {
        $.ajax({
            url: '/email_history/{{ quote_id }}/quote',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $("#email_history").html(data);
            },
            error: function() {
                new_error("Sorry, the email history could not load");
            }
        })
    };

    // using jQuery to extract the CSRFToken
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function remove_responsible_customer(quote_id,customer_id) {
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        $.ajax({
            url: '/quote_delete_responsible_customer/' + quote_id + '/' + customer_id + '/',
            data: {},
            type: "POST",
            success: function() {
                reload_responsible_customer();
            },
            error: function() {
                new_error("Sorry, but could not remove resonsible customer");
            }
        })
    }

    function preview_quote() {
        //Get value of template selected
        var template_id = $("#quote_template").val();

        //Go to the preview page
        var new_tab = window.open("/preview_quote/{{ quotes_results.quote_uuid }}/" + template_id + "/","_blank")
        if (new_tab) {
            new_tab.focus();
        } else {
            //Append a link - do not worry about the error.
            $("#quote_preview").append("<a href='" + new_tab.url + "' target='_blank'>Quote Preview - click here</a>");
        }
    }

    function download_quote() {
        //Get value of template selected
        var template_id = $("#quote_template").val();

        //Go to the preview page
        var new_tab = window.open("/extract_quote/{{ quotes_results.quote_uuid }}/" + template_id + "/","_blank")
        if (new_tab) {
            new_tab.focus();
        } else {
            //Append a link - do not worry about the error.
            $("#quote_preview").append("<a href='" + new_tab.url + "' target='_blank'>Quote Preview - click here</a>");
        }
    }


    function load_assigned_user_add() {
        $.ajax({
            url: '/assigned_user_add/{{ quote_id }}/quote/',
            data:  {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $("#assigned_users").html(data);
            },
            error: function() {
                $("#assigned_users").html("<h2>Assigned Users</h2>Sorry, users encounted an error and did not load");
            }
        })
    };

    function load_assigned_user_list() {
        $.ajax({
            url: '/assigned_user_list/{{ quote_id }}/quote/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $("#assigned_user_list").html(data);
            },
            error: function(data) {
                $("#assigned_user_list").html("<p>User list failed to load</p>")
            }
        })
    };

    function delete_group_item(group_item) {
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        $.ajax({
            url: '/assigned_group_delete/' + group_item + '/',
            data: {},
            dataType: 'HTML',
            type: 'POST',
            success: function(data) {
                load_assigned_group_add();
                load_assigned_group_list();
            },
            error: function() {
                new_error("Sorry, there was an issue deleting the Assigned Group")
            }
        });
    };


    function load_assigned_group_add() {
        $.ajax({
            url: '/assigned_group_add/{{ quote_id }}/quote/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $('#assigned_groups').html(data);
            },
            error: function() {
                $('#assigned_groups').html('<h2>Assigned Groups</h2>Sorry, assigned groups encounted an error and did not load.');
            }
        });
    };


    function load_assigned_group_list() {
        $.ajax({
            url: '/assigned_group_list/{{ quote_id }}/quote/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $('#assigned_group_list').html(data);
            },
            error: function() {
                $('#assigned_group_list').html('<h2>Assigned Group</h2>Sorry, project history encounted an error and did not load.');
            }
        });
    };
</script>
</body>
{% endblock %}



