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

{% block title %} Edit Job{% endblock %}

{% block stylesheets %}
    <style type="text/css">

    .alert-info {
        border-color: #17a2b8;
        border-left: 5px solid #17a2b8;
        background-color: #cfe2ff;
        color: #888;
    }

    @media (min-width: 768px) {
        .alert {
            border-radius: 6px;
            display: table;
            width: 100%;
            padding-left: 78px;
            position: relative;
            padding-right: 60px;
            border: 1px solid #17a2b8;
        }

        .alert .close {
            color: #888;
            opacity: 1;
            float: none;
            position: absolute;
            right: 18px;
            top: 50%;
            margin-top: -12px;
            font-size: 25px;
        }

        .alert .icon {
            text-align: center;
            width: 58px;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            border: 1px solid #17a2b8;
            padding-top: 15px;
            border-radius: 6px 0 0 6px;
        }

        .alert .icon i {
            font-size: 20px;
            color: #fff;
            left: 21px;
            margin-top: -10px;
            position: absolute;
            top: 50%;
        }

        .alert .icon img {
            font-size: 20px;
            color: #fff;
            left: 18px;
            margin-top: -10px;
            position: absolute;
            top: 50%;
        }
        /*============ colors ========*/

        .alert.alert-info .icon,
        .alert.alert-info .icon:after {
            border-color: none;
            background: #00b3c8;
        }
    }

    #job_status_container {
        display: flex;
        flex-wrap: nowrap;
        gap: 10px;
        justify-content: center;
        align-items: center;
    }
    #job_status_container > div {
        flex: 0 0 auto;
        width: auto;
    }
    .status_divider {
        display: flex;
        align-items: center;
        font-size: 1.5rem;
    }

    </style>
{% 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 Job ({{ job.id }})
                        {% if job.type == "JOB" %}
                            <span class='badge bg-primary'>JOB</span>
                        {% elseif job.type == "REWORK" %}
                            <span class='badge bg-warning'>REWORK</span>
                        {% endif %}

                        {% if job.urgentDate %}
                            <span class='badge bg-warning' style="color: #000000;">URGENT</span>
                        {% endif %}

                        {% if job.printStatus %}
                            <span class='badge bg-secondary'>Job Sheet Printed</span>
                        {% else %}
                            <span class='badge bg-info'>Job Sheet Not Printed</span>
                        {% endif %}
                    </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_job_index') }}">Jobs</a></li>
                        <li class="breadcrumb-item active">Edit Job</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

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

                                <div class="row flex-nowrap" id="job_status_container">
                                    {% for jobStatus in jobStatuses %}

                                        {% set disabled = true %}
                                        {% for jobPhase in jobPhases %}
                                            {% if jobPhase.status == jobStatus %}
                                                {% set disabled = false %}

                                                <div class="position-fixed top-0 end-0 p-3" style="z-index: 1050;">
                                                    <div id="toast{{ jobStatus|lower }}" class="toast toast-info fade hide" role="alert" aria-live="assertive" aria-atomic="true">
                                                                <div class="toast-header">
                                                                    <i class="bi bi-circle me-2"></i>
                                                                    <strong class="me-auto">{{ jobStatus }}</strong>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                                                                </div>
                                                                <div class="toast-body">Job {{ jobStatus }} on {{ jobPhase.createdOn|date('Y-m-d') }} by {{ jobPhase.createdBy.fullName }}</div>
                                                            </div>
                                                </div>
                                            {% endif %}
                                        {% endfor %}

                                        <div class="job_status_{{ jobStatus|lower }}_container d-inline-block">
                                            <button type="button" data-bs-toggle="toast" data-bs-target="toast{{ jobStatus|lower }}" class="job-status-btn btn btn-primary btn-lg" {% if disabled %}disabled{% endif %} >{{ jobStatus }}</button>
                                        </div>
                                            {% if not loop.last %}
                                        <div class="status_divider">
                                            <i class="bi bi-caret-right-fill"></i>
                                        </div>
                                        {% endif %}
                                    {% endfor %}
                                </div>

                                <form class="form-horizontal" action="javascript:void(0)" style="margin-top: 50px;">

                                    <div class="form-group row mb-3">
                                        <div class="col-sm-6">
                                            <label for="job_date_create" class="col-sm-6 control-label">Job Date <span class="compulsory">*</span></label>
                                            <div class="col-sm-12">
                                                <input type="text" class="form-control datepicker_fields" id="job_date" placeholder="Job Date" autocomplete="off" value="{{ job.date|date('Y-m-d') }}">
                                            </div>
                                        </div>
                                        <div class="col-sm-6">
                                            <label for="job_color" class="col-sm-6 control-label">Color<span class="compulsory">*</span></label>
                                            <div class="col-sm-12" id="job_color_container">
                                                <select class="form-control select2_fields" id="job_color">
                                                    {% for colour in colours %}
                                                        <option value="{{ colour.id }}"
                                                            {% if colour.id == job.colour %}selected{% endif %}
                                                        >{{ colour.color_name}} ({{ colour.color_no }})</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group row mb-3">
                                        <label for="job_address" class="col-sm-2 col-form-label">Job Address <span class="compulsory">*</span></label>
                                        <div class="col-sm-10">
                                            <input type="text" class="form-control" id="job_address" placeholder="Job Address" value="{{ job.address }}">
                                        </div>
                                    </div>

                                    <div class="form-group row mb-3">
                                        <label for="job_callup" class="col-sm-2 col-form-label">Call Up Details <span class="compulsory">*</span></label>
                                        <div class="col-sm-10">
                                            <textarea class="form-control" rows="5" id="job_callup" placeholder="Call Up Details">{{ job.callupDetails }}</textarea>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="job_project" class="col-sm-3 control-label">Project<span class="compulsory">*</span></label>
                                                <div class="col-sm-12" id="job_project_container">
                                                    <select class="form-control select2_fields" id="job_project">
                                                        <option value="">Select Project</option>
                                                        {% for project in projects %}
                                                            <option value="{{ project.id }}"
                                                                {% if project.id == job.project.id %}selected{% endif %}
                                                            >{{ project.name }}</option>
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="job_supervisor" class="col-sm-3 control-label">{{ 'Supervisor'|trans }}<span class="compulsory">*</span></label>
                                                <div class="col-sm-12" id="job_supervisor_container">
                                                    <select class="form-control select2_fields" id="job_supervisor">
                                                        <option value="">Select {{ 'Supervisor'|trans }}</option>
                                                        {% for supervisor in supervisors %}
                                                            <option value="{{ supervisor.id }}"
                                                                {% if supervisor.id == job.supervisor.id %}selected{% endif %}
                                                            >{{ supervisor.name }} -> <i>{{ supervisor.customer.companyName }}</i></option>
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                                {% if job and job.supervisor %}
                                                    {% set bankrupt = (job.supervisor.customer.bankrupt)? true : false  %}
                                                    {% set flagged = (job.supervisor.customer.flagged)? true : false %}
                                                    {% set overdueInvoices = settingService.overdueInvoicesByCustomer(job.supervisor.customer) %}

                                                    {% if bankrupt or flagged or overdueInvoices > 0 %}
                                                        <div class="alert alert-danger" role="alert" style="padding-left: 15px; padding-right: 15px; margin-top: 10px; border: 1px solid;">
                                                            <ul style="margin-bottom: 0px;">
                                                                {% if flagged %}<li>{{ 'Customer'|trans }} is Flagged.</li>{% endif %}
                                                                {% if bankrupt %}<li>{{ 'Customer'|trans }} is Bankrupt.</li>{% endif %}
                                                                {% if overdueInvoices > 0 %}<li>{{ 'Customer'|trans }} has {{ overdueInvoices }} overdue invoices.</li>{% endif %}
                                                            </ul>
                                                        </div>
                                                    {% endif %}
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="urgent_job" class="col-sm-3 control-label">Urgent</label>
                                                <div class="col-sm-12">
                                                    <input type="text" class="form-control datepicker_fields" id="urgent_job" placeholder="Urgent" autocomplete="off" value="{{ job.urgentDate|date('Y-m-d') }}">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="order_number" class="col-sm-6 control-label">Order Number</label>
                                                <div class="col-sm-12">
                                                    <input type="text" class="form-control" id="order_number" placeholder="Order Number" value="{{ job.etsNumber }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="area_number" class="col-sm-12 col-form-label">Area Number</label>
                                                <div class="col-sm-10">
                                                    <input type="text" class="form-control" id="area_number" placeholder="Area Number" value="{{ job.areaNumber }}">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6"></div>
                                    </div>

                                    <div class="form-group row mb-3">
                                        <label for="job_comment" class="col-sm-2 col-form-label">Comment</label>
                                        <div class="col-sm-10">
                                            <textarea class="form-control" rows="5" id="job_comment" placeholder="Comment">{{ job.comment }}</textarea>
                                        </div>
                                    </div>

                                    <div class="form-group row mb-3">
                                        <label for="work_performed" class="col-sm-2 col-form-label">Work Performed</label>
                                        <div class="col-sm-10">
                                            <textarea class="form-control" rows="5" id="work_performed" placeholder="Work Performed">{{ job.workPerformed }}</textarea>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="work_hours" class="col-sm-3 control-label">Work Hours</label>
                                                <div class="col-sm-12">
                                                    <input type="number" class="form-control" id="work_hours" placeholder="Work Hours" autocomplete="off" value="{{ job.workHours }}">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="job_cost" class="col-sm-6 control-label">Cost</label>
                                                <div class="col-sm-12">
                                                    <div class="input-group flex-nowrap">
                                                        <span class="input-group-text" id="addon-wrapping">$</span>
                                                        <input type="text" class="form-control" id="job_cost" placeholder="Cost" disabled="disabled" value="{{ cost }}" aria-label="Cost" aria-describedby="addon-wrapping">
                                                    </div>
                                                </div>


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

                                    <div class="alert alert-info">
                                        <div class="icon hidden-xs">
                                            <i class="fa fa-info-circle"></i>
                                        </div>
                                        <strong>Pricing Structure</strong>
                                        <br/>
                                        {% if (job.supervisor.customer.pricingStructure.standard_flashing != "") %}
                                            <span style="margin-right: 15px;">Standard Flashing : {{ job.supervisor.customer.pricingStructure.standard_flashing }}</span>
                                        {% endif %}
                                        {% if (job.supervisor.customer.pricingStructure.cover_plate != "") %}
                                            <span style="margin-right: 15px;">Cover Plate : {{ job.supervisor.customer.pricingStructure.cover_plate }}</span>
                                        {% endif %}
                                        {% if (job.supervisor.customer.pricingStructure.custom1 != "") %}
                                            <span style="margin-right: 15px;">Custom 1 : {{ job.supervisor.customer.pricingStructure.custom1 }}</span>
                                        {% endif %}
                                        {% if (job.supervisor.customer.pricingStructure.custom2 != "") %}
                                            <span style="margin-right: 15px;">Custom 2 : {{ job.supervisor.customer.pricingStructure.custom2 }}</span>
                                        {% endif %}
                                        {% if (job.supervisor.customer.pricingStructure.custom3 != "") %}
                                            <span style="margin-right: 15px;">Custom 3 : {{ job.supervisor.customer.pricingStructure.custom3 }}</span>
                                        {% endif %}
                                    </div>


                                    <table class="table table-bordered" id="job_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 jobDetail in job.jobItems %}
                                        <tr class="after-add-more">
                                            <td class="text-center">
                                                <div class="input-group">
                                                    <input type="hidden" class="item_id" value="{{ jobDetail.id }}"/>
                                                    <input type="number" class="form-control item_qty job_detail_row" placeholder="Qty" value="{{ jobDetail.quantity }}"/>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="input-group">
                                                    <input type="text" class="form-control item_description" placeholder="Description" value="{{ jobDetail.description }}"/>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="input-group">
                                                    <input type="text" class="form-control unit_price job_detail_row" placeholder="Unit Price" value="{{ jobDetail.unitPrice }}"/>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="input-group">
                                                    {% set total = jobDetail.quantity * jobDetail.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 job_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 job_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="updateJobBtn" style="float: right;">Update Job</button>

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


    {% include '@Job/jobs/partials/job-notes-modal.twig' %}
    {% include '@Invoice/invoices/partials/create-invoice-modal.html.twig' %}
    {% include '@Job/jobs/partials/job-status-modal.twig' %}
    {% include '@Job/jobs/partials/rework-job-modal.twig' %}

{% endblock %}

{% block javascripts %}

    <script type="text/javascript">

    $( document ).ready(function() {
        $('#job_color').select2({
            theme: 'bootstrap-5'
        });
        $('#job_project').select2({
            theme: 'bootstrap-5'
        });
        $('#job_supervisor').select2({
            theme: 'bootstrap-5'
        });

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


        $('.job-status-btn').on('click', function(event) {
            event.preventDefault();

            var targetId = $(this).attr('data-bs-target');
            var toastEle = $('#'+targetId)[0];
            if (toastEle) {
                var toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastEle);
                toastBootstrap.show();
            }
        });

      });


    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
        });

    //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();
        $('#job_detail_table tr:first').after("<tr>"+html+"</tr>")
            $(".job_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
        });
    });

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

    //function to calculate row total
    $(".job_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);
    });

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

        var button = $(this);
        var job_date = $.trim($("#job_date").val());
        var job_comment = $.trim($("#job_comment").val());
        var job_address = $.trim($("#job_address").val());
        var job_color = $.trim($("#job_color").val());
        var job_supervisor = $.trim($("#job_supervisor").val());
        var job_project = $.trim($("#job_project").val());
        var urgent_job = $.trim($("#urgent_job").val());
        var work_performed = $.trim($("#work_performed").val());
        var order_number = $.trim($("#order_number").val());
        var job_callup = $.trim($("#job_callup").val());
        var work_hours = $.trim($("#work_hours").val());
        var area_number = $.trim($("#area_number").val());

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

        if (
            validateInput(job_date, "Job Date") &&
            validateInput(job_address, "Address") &&
            validateInput(job_color, "Colour") &&
            validateInput(job_supervisor, "{{ 'Supervisor'|trans }}") &&
            validateInput(job_project, "Project") &&
            validateInput(job_callup, "Call Up Details")
        )
       {

            for(var i = 0; i < item_qty.length; i++) {

                var qty = ($.trim($(item_qty[i]).val())==null)? 0 : $.trim($(item_qty[i]).val());

                var sub_array = {
                        "quantity": qty,
                        "description": $(item_description[i]).val(),
                        "unitPrice": $(unit_price[i]).val(),
                        "id": $(item_id[i]).val(),
                    };

                job_detail_array.push(sub_array);
            }

           button.attr('disabled', true);

            $.ajax({
                type: 'post',
                url: '{{ path('api_job_edit') }}',
                datatype: 'json',
                data: {
                    id : {{ job.id }},
                    date : job_date,
                    comment : job_comment,
                    address : job_address,
                    color : job_color,
                    supervisor : job_supervisor,
                    project : job_project,
                    work_performed : work_performed,
                    ets_number : order_number,
                    callup : job_callup,
                    urgent: urgent_job,
                    work_hours: work_hours,
                    areaNumber: area_number,
                    job_detail_data:JSON.stringify(job_detail_array)
                }
            })
            .done(function (data) {
                Swal.fire(
                    'Success!',
                    'Job Updated Successfully!',
                    'success'
                );

                setTimeout(function(){ location.reload(); }, 2500);
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                button.attr('disabled', false);
                toastr.options.progressBar = true;
                toastr.error('Failed to Update Job!', 'Error!');
            });
        }
    });

</script>

{% endblock %}
