{% extends "./template.html" %}
{% block content %}
{% load static %}


<script>
	function on_page_load() {
	    //Load AJAX components
        load_contact_history();
        load_email_history();

        load_document_tree_list({{ customer_id }},'customer');
    }
</script>
<body onload="on_page_load()">
    <div class="card mt-4">
        <div class="card-header">
            <h2>Customer Information</h2>
        </div>
        <div class="card-body">
            <form action="{% url 'customer_information' customer_results.customer_id %}" method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group text-center">
                    {% if profile_picture %}
                        <label for="id_update_profile_picture"><img src="{{ profile_picture }}" height="160px"></label><br/>
                        {{ organisation_information_form.update_profile_picture }}
                    {% else %}
                        <label for="id_update_profile_picture"><img src="{% static 'NearBeach/images/icons/star.svg' %}" height="160px"></label><br/>
                        {{ organisation_information_form.update_profile_picture }}
                    {% endif %}
                    {% if customer_permissions > 1 %}
                        <label>{{ customer_information_form.update_profile_picture }}</label>
                    {% endif %}
                    <div class="alert-danger" id="upload_errors"></div>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-2">
                        <label for="id_customer_title">Title</label>
                        {{ customer_information_form.customer_title }}
                    </div>
                    <div class="form-group col-md-5">
                        <label for="id_customer_first_name">Customer First Name</label>
                        {{ customer_information_form.customer_first_name }}
                    </div>
                    <div class="form-group col-md-5">
                        <label for="id_customer_last_name">Customer Last Name</label>
                        {{ customer_information_form.customer_last_name }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="id_customer_email">Customer Email</label>
                    {{ customer_information_form.customer_email }}
                </div>
                {% if not customer_results.organisation_id == Null %}
                    <div class="form-group">
                        <label>Organisation: <a href="{% url 'organisation_information' customer_results.organisation_id.organisation_id %}">{{ customer_results.organisation_id }}</a></label>
                    </div>
                {% endif %}
                {% if customer_permissions > 1 %}
                    <div class="form-row">
                        <input type="submit" name="update" value="Update Details" class="form-control btn btn-primary"/>
                    </div>
                {% endif %}
            </form>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h2>Campus Contact Information</h2>
        </div>
        <div class="card-body">
            {% if add_campus_results and assign_campus_to_customer_permission > 1 and customer_results.organisation_id %}
                <form id="customer_campus_form">
                    <div class="form-row">
                        <select name="add_campus_select" id="id_add_cammpus_select" onchange="enable_disable_add_campus()" class="form-control col-md-6">
                            <option value="---------"> ---------</option>
                            {% for row in add_campus_results %}
                                <option value="{{ row.campus_id }}">{{ row.campus_nickname }}</option>
                            {% endfor %}
                        </select>
                        <input type="submit" name="add_campus_submit" value="Add Campus" disabled id="id_add_cammpus_submit" class="btn btn-primary form-control col-md-6">
                    </div>
                </form>
            {% elif assign_campus_to_customer_permission > 1 and not customer_results.organisation_id %}
                <a href="{% url 'new_campus' customer_results.customer_id 'customer' %}">New Campus</a>
            {% endif %}
            {% if customer_campus_results %}
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <td>Campus nickname</td>
                            <td>Campus's Phone</td>
                            <td>Campus's Fax</td>
                            <td>Campus Suburb</td>
                            <td>Campus Region</td>
                            <td>Campus Country</td>
                            {% if customer_permissions == 4 or administration_permission %}
                                <td>Delete</td>
                            {% endif %}
                        </tr>
                    </thead>
                    {% for row in customer_campus_results %}
                        <tr>
                            <td><a href="{% url 'campus_information' row.campus_id %}">{{ row.campus_nickname }}</a></td>
                            <td>{{ row.campus_phone }}</td>
                            <td>{{ row.campus_fax }}</td>
                            <td>{{ row.campus_suburb }}</td>
                            <td>{{ row.campus_region_id }}</td>
                            <td>{{ row.campus_country_id }}</td>
                            {% if customer_permissions == 4 or administration_permission %}
                                <td>Delete</td>
                            {% endif %}
                        </tr>
                    {% endfor %}
                </table>

            {% elif campus_results %}
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <td>Campus nickname</td>
                            <td>Contact's Phone</td>
                            <td>Contact's Fax</td>
                            <td>Campus Suburb</td>
                            <td>Campus Region</td>
                            <td>Campus Country</td>
                            {% if customer_permissions == 4 or administration_permission %}
                                <td>Delete</td>
                            {% endif %}
                        </tr>
                    </thead>
                    {% for row in campus_results %}
                        <tr>
                            <td><a href="{% url 'customer_campus_information' row.customer_campus_id 'CUST' %}">{{ row.campus_id }}</a></td>
                            <td>{{ row.customer_phone }}</td>
                            <td>{{ row.customer_fax }}</td>
                            <td>{{ row.campus_id.campus_suburb }}</td>
                            <td>{{ row.campus_id.campus_region_id }}</td>
                            <td>{{ row.campus_id.campus_country_id }}</td>
                            {% if customer_permissions == 4 or administration_permission %}
                                <td><a href="{% url 'delete_campus_contact' row.customer_campus_id 'CUST' %}">Delete</a></td>
                            {% endif %}
                        </tr>
                    {% endfor %}
                </table>
            {% else %}
                <label>There are currently no campuses</label>
            {% endif %}
        </div>
    </div>



    <form method="post" class="customer_contact_history" id="customer_contact_history" enctype="multipart/form-data">
        <h2>Contact History</h2>
        Loading...
    </form>

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

    <div class="card mt-4">
        <div class="card-header">
            <h2>Document Uploads</h2>
        </div>
        <div class="card-body" id="document_tree_list">
            Loading...
        </div>
    </div>


    <div class="card mt-4">
        <div class="card-header">
            <h2>Customer Quotes</h2>
        </div>
        <div class="card-body">
            <a href="{% url 'new_quote' customer_id 'customer' %}">New Quote</a>
            {% if quote_results %}
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <td width="50%">Quote Title</td>
                            <td width="25%">Valid Till</td>
                            <td width="25%">Quote Stage</td>
                        </tr>
                    </thead>
                    {% for row in quote_results %}
                        <tr>
                            <td><a href="{% url 'quote_information' row.quote_id %}">{{ row.quote_title }}</a></td>
                            <td>{{ row.quote_valid_till }}</td>
                            <td>{{ row.quote_stage_id }}</td>
                        </tr>
                    {% endfor %}
                </table>
            {% endif %}
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h2>Associated Projects & Tasks</h2>
        </div>
        <div class="card-body">
            {% if customer_permissions > 1 %}
            <h4>Actions</h4>
            <div class="list-group">
                <a href="{% url 'new_project' customer_results.customer_id 'customer' %}">Create New Project</a>
                <a href="{% url 'new_task' customer_results.customer_id 'customer' %}">Create New Task</a>
                <a href="{% url 'assign_customer_project_task' customer_results.customer_id %}">Assign Existing Project or Task</a>
            </div>
            <br/>
            {% endif %}
            <h4>Assigned Projects</h4>
                {% if project_results %}
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <td>Project ID</td>
                                <td>Project Name</td>
                                <td>Project End Date</td>
                                <td>Project Status</td>
                            </tr>
                        </thead>
                        {% for row in project_results %}
                            <tr>
                                <td><a href="{% url 'project_information' row.project_id %}">PRO{{ row.project_id }}</a></td>
                                <td>{{ row.project_name }}</td>
                                <td>{{ row.project_end_date }}</td>
                                <td>{{ row.project_status }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                {% else %}
                    <p>Sorry. There are currently no projects for this customer</p>
                {% endif %}
            <br/>

            <h4>Assigned Tasks</h4>
                {% if task_results %}
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <td>Task ID</td>
                                <td>Task Name</td>
                                <td>Task End Date</td>
                                <td>Task Status</td>
                            </tr>
                        </thead>
                        {% for row in task_results %}
                            <tr>
                                <td><a href="{% url 'task_information' row.task_id %}">TASK{{ row.task_id }}</a></td>
                                <td>{{ row.task_short_description }}</td>
                                <td>{{ row.task_end_date }}</td>
                                <td>{{ row.task_status }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                {% else %}
                    <p>Sorry. There are currently no tasks for this customer.</p>
                {% endif %}

        </div>
    </div>

    {% if opportunity_results %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Customer Opportunities</h2>
            </div>
            <div class="card-body">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <td>Opportunity Name</td>
                            <td>Opportunity Stage</td>
                            <td>Opportunity End Date</td>
                            <td>Opportunity Stage</td>
                        </tr>
                    </thead>
                    {% for row in opportunity_results %}
                        <tr>
                            <td><a href="{% url 'opportunity_information' row.opportunity_id %}">{{ row.opportunity_name }}</a></td>
                            <td>{{ row.opportunity_stage_id }}</td>
                            <td>{{ row.opportunity_expected_close_date }}</td>
                            <td>{{ row.opportunity_stage_id }}</td>
                        </tr>
                    {% endfor %}
                </table>
            </div>
        </div>
    {% endif %}

    {% if customer_permissions == 4 %}
        <div class="card mt-4">
            <div class="card-header bg-danger">
                <h2>DANGER ZONE!</h2>
            </div>
            <div class="card-body">
                <a href="javascript:void(0)" onclick="confirm_delete_customer({{ customer_id }})" class="btn btn-warning col-md-12">Delete Customer</a>
            </div>
        </div>

        <!-- CONFIRM DELETION OF ORGANISATION -->
        <div class="modal" tabindex="-1" role="dialog" id="confirm_customer_delete">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <!-- HEADER -->
                    <div class="modal-header">
                        <h5 class="modal-title">Delete Customer?</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                    <!-- BODY -->
                    <div class="modal-body">
                        <p>
                            Are you sure you want to delete this customer? Deleting this customer will also delete;
                            <ul>
                                <li>Any <strong>projects</strong> connected to this customer</li>
                                <li>Any <strong>tasks</strong> connected to this customer</li>
                                <li>Any <strong>opportunity connections</strong> connected to this customer</li>
                            </ul>
                            <strong>This can not be reversed</strong>
                        </p>
                    </div>


                    <!-- FOOTER -->
                    <div class="modal-footer">
                        <button id="remove_customer_confirmed" disabled type="button" class="btn btn-danger btn-ok">Delete Customer</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            function confirm_delete_customer(customer_id) {
                /*
                First we have to confirm that the user wants to delete the group. This will bring up a modal
                and force them to wait 2 seconds before deleting. It also warns them about the dangers of doing this.

                Method
                ~~~~~~
                1. Bring up modal
                2. Change the remove permission button attribute to the correct function
                2. Wait 2 seconds
                3. Enable button
                 */
                $("#confirm_customer_delete").modal("show");

                //Change the attribute for the confirmation button
                $("#remove_customer_confirmed").attr('onclick',`delete_customer("${customer_id}");`);

                //Set the timeout of the button
                setTimeout(function() {
                    document.getElementById("remove_customer_confirmed").disabled = false;
                }, 2000);
            }

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

                $.ajax({
                    url: `/delete_customer/${customer_id}/`,
                    data: {},
                    dataType: "HTML",
                    type: "POST",
                    success: function(data) {
                        //Successfully deleted the customer. Send user to the dashboard
                        window.location.href = "/";
                    },
                    error: function() {
                        new_error("Sorry - but the organisation could not be deleted");
                    }
                });
            }
        </script>
    {% endif %}
</body>
<script>
    $("#customer_campus_form").on('submit', function(e) {
        e.preventDefault();

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

        var id_add_cammpus_select = document.getElementById("id_add_cammpus_select");

        $.ajax({
            type: "POST",
            data: {},
            url: '/add_campus_to_customer/{{ customer_id }}/' + id_add_cammpus_select.value + '/',
            success: function(data){

                $.each(data, function(index, element) {
                    window.location.href = "/customer_campus_information/" + element + "/CUST/";
                });
            },
            error: function () {
                new_error("Sorry, but adding that campus failed.")
            }
        })
    });

    $("#customer_contact_history").on('submit', function(e) {
        e.preventDefault();

        var form_data = new FormData(this);
        $.ajax({
            xhr: function() {
                    var xhr = new window.XMLHttpRequest();

                    // Upload progress
                    xhr.upload.addEventListener("progress", function(evt){
                        if (evt.lengthComputable) {
                            var percentComplete = evt.loaded / evt.total;
                            //Do something with upload progress
                            console.log(percentComplete);

                            $("#upload_percent_contact").html(parseFloat(percentComplete * 100).toFixed(2) + "%");
                            $("#upload_progress_contact").css(
                                'width', percentComplete * 100 + '%'
                            );
                        }
                   }, false);
                   return xhr;
            },
            type: 'POST',
            url: '/information_customer_contact_history/{{ customer_id }}/',
            data: form_data,
            processData: false,
            contentType: false,
            success: function() {
                //Reload the project history :)
                load_contact_history();
            },
            error: function() {
                new_error("Sorry, project history did not save. Please try again.");
            }
        })
    });



    $("#id_update_profile_picture").on("change",function(e){
        //Get the file
        var file = e.currentTarget.files,
            filesize = (file[0].size/1024/1024).toFixed(4);

        if (filesize >= 1.0) {
            //Sorry, the file is too big
            $("#id_update_profile_picture").val('');
            $("#upload_errors").html("Sorry - the file you tried uploading is too big.")
        } else {
            $("#upload_errors").html("")
        }
    });


    function load_contact_history() {
        //Load Project History
        $.ajax({
            url: '/information_customer_contact_history/{{ customer_id }}/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $('#customer_contact_history').html(data);

                //Make sure the datetime picker is activated
                $("#id_contact_date").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'
                    ]


                });

                tinyMCE.init({
                    selector: '.old_customer_contact_history',
                    readonly: true,
                    'toolbar': false,
                    'menubar': false,
                    'height': '300px',
                });
            },
            error: function() {
                $('#customer_contact_history').html('<h2>Contact History</h2>Sorry, contact history encounted an error and did not load.');
            }
        });
    };


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


    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }


    // 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');
</script>

{% endblock %}
