
{% 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/check_dates.js' %}"></script>
<script type="text/javascript" src="{% static 'NearBeach/javascript/autoscale_textarea.js' %}"></script>
<script type="text/javascript" src="{% static 'NearBeach/widgets/datetimepicker/jquery.datetimepicker.full.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'NearBeach/widgets/datetimepicker/jquery.datetimepicker.min.css' %}">
<script type="text/javascript" src="{% static 'NearBeach/javascript/document_upload.js' %}"></script>


<body onload="on_page_load()">
    <div class="card mt-4">
        <div class="card-header">
            <h2>{{ organisation_results.organisation_name }}</h2>
        </div>
        <div class="card-body">
            <form action="{% url 'organisation_information' organisation_results.organisation_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/>
                        {% if organisation_permissions > 1 %}
                            {{ organisation_information_form.update_profile_picture }}
                        {% endif %}
                        <div class="alert-danger" id="upload_errors"></div>
                    {% else %}
                        <label for="id_update_profile_picture"><img src="{% static 'NearBeach/images/icons/star.svg' %}" height="160px"></label><br/>
                        {% if organisation_permissions > 1 %}
                            {{ organisation_information_form.update_profile_picture }}
                        {% endif %}
                    {% endif %}
                </div>

                <div class="form-group">
                    <label for="id_organisation_name">Organisation Name</label>
                    {{ organisation_information_form.organisation_name }}
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="id_organisation_website">Organisation Website</label>
                        {{ organisation_information_form.organisation_website }}
                    </div>
                    <div class="form-group col-md-6">
                        <label for="id_organisation_email">Organisation Email</label>
                        {{ organisation_information_form.organisation_email }}
                    </div>
                </div>
                {% if organisation_permissions > 1 %}
                    <div class="form-group">
                        <input type="submit" name="submit_contact" value="Update" class="btn btn-primary form-control"/>
                    </div>
                {% endif %}
            </form>
        </div>
    </div>

    {% if organisation_campus_permissions > 0 %}
    <div class="card mt-4">
        <div class="card-header">
            <h2>Organisation Campus'</h2>
        </div>
        <div class="card-body">
            {% if organisation_campus_permissions > 1 %}
                <a href="{% url 'new_campus' organisation_id 'organisation' %}">New Campus</a>
            {% endif %}
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <td>Campus Nickname</td>
                        <td>Campus Location</td>
                        <td>Campus Address</td>
                    </tr>
                </thead>
                {% for campus in campus_results %}
                    <tr>
                        <td><a href="{% url 'campus_information' campus.pk %}">{{ campus.campus_nickname }}</a></td>
                        <td>{{ campus.campus_country_id }} - {{ campus.campus_region_id }}</td>
                        <td>{{ campus.campus_address1 }}<br />{{ campus.campus_address2 }}<br />{{ campus.campus_address3 }}{{ campus.campus_suburb }}</td>
                    </tr>
                {% endfor %}
            </table>
        </div>
    </div>
    {% endif %}

    {% if customer_permissions > 0 %}
        <div class="card mt-4">
            <div class="card-header">
                <h2>Organisation Contacts</h2>
            </div>
            <div class="card-body">
                {% if customer_permissions > 1 %}
                    <a href="{% url 'new_customer' organisation_results.organisation_id%}">New Customer</a>
                {% endif %}
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <td>Name</td>
                            <td>Email</td>
                        </tr>
                    </thead>
                    {% for customer in customer_results %}
                        <tr>
                            <td><a href="{% url 'customer_information' customer.customer_id %}">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</a></td>
                            <td>{{ customer.customer_email }}</td>
                        </tr>
                    {% endfor %}
                </table>
            </div>
        </div>
    {% endif %}


    <form method="post" class="organisation_contact_history" id="organisation_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>Organisation Quotes</h2>
        </div>
        <div class="card-body">
            <a href="{% url 'new_quote' organisation_results.organisation_id 'organisation' %}">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 organisation_permissions > 1 %}
            <h4>Actions</h4>
            <div class="list-group">
                <a href="{% url 'new_project' organisation_results.organisation_id 'organisation' %}">Create New Project</a>
                <a href="{% url 'new_task' organisation_results.organisation_id 'organisation' %}">Create New 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>Organisation Opportunities</h2>
            </div>
            <div class="card-body">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <td>Opportunity Name</td>
                            <td>Customer</td>
                            <td>Opportunity Stage</td>
                            <td>Opportunity End Date</td>
                        </tr>
                    </thead>
                    {% for row in opportunity_results %}
                        <tr>
                            <td>
                                <a href="{% url 'opportunity_information' row.opportunity_id %}">{{ row.opportunity_name }}</a>
                            </td>
                            {% if row.customer_id.customer_id %}
                                <td>
                                    <a href="{% url 'customer_information' row.customer_id.customer_id %}">{{ row.customer_id }}</a>
                                </td>
                            {% else %}
                                <td> - </td>
                            {%  endif %}
                            <td>{{ row.opportunity_stage_id }}</td>
                            <td>{{ row.opportunity_expected_close_date }}</td>
                        </tr>
                    {% endfor %}
                </table>
            </div>
        </div>
    {% endif %}

    {% if organisation_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_organisation({{ organisation_id }})" class="btn btn-warning col-md-12">Delete Organisation</a>
            </div>
        </div>

        <!-- CONFIRM DELETION OF ORGANISATION -->
        <div class="modal" tabindex="-1" role="dialog" id="confirm_organisation_delete">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <!-- HEADER -->
                    <div class="modal-header">
                        <h5 class="modal-title">Delete Organisation?</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 organisation? Deleting this organisation will also delete;
                            <ul>
                                <li>Any <strong>customers</strong> connected to this organisation</li>
                                <li>Any <strong>projects</strong> connected to this organisation</li>
                                <li>Any <strong>tasks</strong> connected to this organisation</li>
                                <li>Any <strong>opportunity connections</strong> connected to this organisation</li>
                            </ul>
                            <strong>This can not be reversed</strong>
                        </p>
                    </div>


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

        <script>
            function confirm_delete_organisation(organisation_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_organisation_delete").modal("show");

                //Change the attribute for the confirmation button
                $("#remove_organisation_confirmed").attr('onclick',`delete_organisation("${organisation_id}");`);

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

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

                $.ajax({
                    url: `/delete_organisation/${organisation_id}/`,
                    data: {},
                    dataType: "HTML",
                    type: "POST",
                    success: function(data) {
                        //Successfully deleted the organisation. Send user to the dashboard
                        window.location.href = "/";
                    },
                    error: function() {
                        new_error("Sorry - but the organisation could not be deleted");
                    }
                });
            }
        </script>
    {% endif %}

<script>

    $("#organisation_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").html(parseFloat(percentComplete * 100).toFixed(2) + "%");
                            $("#upload_progress").css(
                                'width', percentComplete * 100 + '%'
                            );
                        }
                   }, false);
                   return xhr;
            },
            type: 'POST',
            url: '/information_organisation_contact_history/{{ organisation_results.organisation_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_organisation_contact_history/{{ organisation_results.organisation_id }}/',
            data: {},
            dataType: 'HTML',
            type: 'GET',
            success: function(data) {
                $('#organisation_contact_history').html(data);

                tinyMCE.init({
                    selector: '.old_organisation_contact_history',
                    readonly: true,
                    'toolbar': false,
                    'menubar': false,
                    'height': '300px',
                });
            },
            error: function() {
                $('#organisation_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/{{ organisation_results.organisation_id }}/organisation',
            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');

	function on_page_load() {
	    //Load AJAX components
        load_contact_history();
        load_document_tree_list({{ organisation_id }},'organisation');
        load_email_history();

        //Setup the user permissions
	}


</script>
</body>
{% endblock %}
