<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<div id="wrapper">
    <div class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="panel_s panel-table-full">
                    <div class="panel-body">
                        <div class="clearfix"></div>
                        <input type="hidden" id="lead_id" value=<?php echo $data['lead_id']; ?>>
                        <?php echo form_open((admin_url('leads/updatechecklist/' . $data['lead_id'] . '/' . $data['task_id'])), ['id' => 'checklist_form']); ?>
                        <input type="hidden" id="lead_url"
                            value="<?php echo admin_url('leads/updatechecklist/' . $data['lead_id'] . '/' . $data['task_id']); ?>"></input>
                        <div class="col-md-6">
                            <!--start render input comment -->
                            <!-- <?php echo render_input('name', 'ID Title'); ?> -->
                            <!-- End render input comment -->
                            <div class="form-group" app-field-wrapper="name">
                                <label for="name" class="control-label">ID Title & Description</label>
                                <input type="text" id="name" name="name" class="form-control"
                                    placeholder="Please Enter title ( ID back, Driving License )"
                                    value="<?php echo $data['name']; ?>">
                            </div>
                            <div style="display:none;">
                                <?php echo render_textarea('checklist_description', 'ID Description', $data['description'], array('placeholder' => 'Please enter the ID description')); ?>
                            </div>
                            <?php
                            // $imp_html = "<div class='form-group' app-field-wrapper='status'><label for='status' class='control-label'>Status</label>";
                            // $imp_html .= "<select name='status' id='status' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                            // $imp_html .= "<option value=''>Nothing selected</option>";
                            // $transaction = [1 => 'Pending Review', 2 => 'Outstanding', 3 => 'Rejected', 4 => 'Approved'];
                            
                            // foreach ($transaction as $key => $value) {
                            //     $selected = ($key == 2) ? 'selected' : '';
                            //     ;
                            //     $imp_html .= "<option value='$key' $selected>$value</option>";
                            // }
                            
                            // $imp_html .= "</select></div>";
                            // echo $imp_html;
                            ?>
                        </div>
                        <div class="col-md-6">
                            <?php
                            $imp_html = "<div style='display:none;' class='form-group' app-field-wrapper='doc_type'><label for='doc_type' class='control-label'>ID Doc Type</label>";
                            $imp_html .= "<select name='doc_type[]' id='doc_type' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98' multiple>";
                            $imp_html .= "<option value=''>Nothing selected</option>";
                            $doc_array = [1 => 'Png', 2 => 'Pdf', 3 => 'Jpeg', 4 => 'Zip', 5 => 'HEIC'];

                            $selectedOptions = $data['doc_type'];

                            foreach ($doc_array as $key => $value) {
                                $selected = in_array($key, $selectedOptions) ? 'selected' : '';
                                $imp_html .= "<option value='$value' $selected>$value</option>";
                            }

                            $imp_html .= "</select></div>";
                            echo $imp_html;
                            ?>
                            <!-- checklist item type -->
                            <div class="form-group" style="display:none;">
                                <label for="Item_name" class="control-label">ID Type</label>
                                <select name="Item_name[]" id="Item_name" class="form-control selectpicker" multiple
                                    data-width="100%" data-none-selected-text="Nothing selected" data-live-search="true"
                                    tabindex="-98">
                                    <option value="">Nothing selected</option>
                                    <?php
                                    if (!empty($get_item_name_id)) {
                                        $selectedOptions = $get_item_name_id;
                                    } else {
                                        $selectedOptions = [];
                                    }
                                    ?>
                                    <?php foreach ($checklist_item_type_data as $value): ?>
                                        <option value="<?php echo $value['id']; ?>" <?php echo in_array($value['id'], $selectedOptions) ? 'selected' : ''; ?>>
                                            <?php echo $value['Item_name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php echo form_error('Item_name[]', '<div class="text-danger">', '</div>'); ?>
                            </div>
                            <div style="display:none;">
                                <?php echo render_textarea('checklist_instruction', 'ID Instruction', $data['instruction'], array('placeholder' => 'Please enter the checklist instruction')); ?>
                            </div>
                            <?php echo render_textarea('ld_notes', 'LD Notes', $data['ld_notes'], array('placeholder' => 'Please enter the item notes.')); ?>
                        </div>
                        <?php if ($data['samegroup']) { ?>
                            <div class="clearfix"></div>
                            <div class="lead-edit">
                                <hr class="-tw-mx-4 tw-border-neutral-200" />
                                <button type="submit" class="btn btn-primary pull-right lead-save-btn"
                                    id="lead-form-submit">
                                    <?php echo _l('Update'); ?>
                                </button>
                                <button type=" button" class="btn btn-default pull-right mright5" id="reset_from_checklist"
                                    data-dismiss="modal">
                                    <?php echo _l('Reset'); ?>
                                </button>
                            </div>
                        <?php } ?>
                        <?php echo form_close(); ?>
                        <div class="clearfix"></div>
                        <hr class="-tw-mx-4 tw-border-neutral-200" />
                        <div id="data-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="statusChangeModal" tabindex="-1" role="dialog" aria-labelledby="statusChangeModalLabel"
    aria-hidden="true" style="width: 100%;background-color: #3831317a;overflow:hidden;">
    <div class="modal-dialog" role="document"
        style="display:flex;justify-content:center;align-items:center;height:100%">
        <div class="modal-content">
            <div class="modal-header">
                <div style="display: flex; justify-content:space-between;align-items:center;">
                    <h4>Please add the reason for rejection.</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <div class="modal-body">
                <form id="statusChangeForm">
                    <div class="form-group">
                        <label for="rejectionReason">Reason for Rejection:</label>
                        <textarea class="form-control" id="rejectionReason" name="reason" rows="4" required></textarea>
                        <div class="invalid-feedback" style="display:none; color:red;">Please provide a reason
                            for rejection.</div>
                    </div>
                    <button type="button" class="btn btn-primary" id="submitStatusChange">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php init_tail(); ?>
</body>
<script>
    $.ajax({
        url: "<?php echo admin_url('leads/checklist_details_by_id/' . $data['task_id']); ?>",
        type: "GET",
        dataType: "json",
        success: function (response) {
            console.warn('checklistrecord' + response);
            // Display the data in the #data-container div
            var sameGroup = <?php echo $data['samegroup'] ? 'true' : 'false'; ?>;
            if (response.length > 0) {
                var html = "<table class='table dt-table table-ticket-reports dt-inline dataTable no-footer'>";
                // html += "<thead><tr><th>ID Title</th><th>Description</th><th>ID Type</th><th>ID Instruction</th><th>Created at</th><th>Status</th><th>Documents</th><th>Action</th></tr></thead>";
                html += "<thead><tr><th>ID Title & Description</th>";
                // if(item.task_leads_status == 3){
                html += "<th>Notes</th>";
                // }
                html += "<th>Created at</th><th>Status</th><th>Documents</th><th>Action</th></tr></thead>";
                html += "<tbody id='checklist_table'>";
                $.each(response, function (index, item) {
                    var instructionLines = item.instruction.split("\n");
                    var instructionHtml = "<td><ul style='list-style-type: disc;'>";
                    $.each(instructionLines, function (index, line) {
                        // Trim the line to remove any leading or trailing spaces
                        var trimmedLine = $.trim(line);
                        // Skip empty lines
                        if (trimmedLine !== "") {
                            instructionHtml += "<li class='item-name'>" + trimmedLine + "</li>";
                        }
                    });
                    instructionHtml += "</ul></td>";
                    // show the ld notes in bullets points
                    var ld_notes_Lines = item.ld_notes ? item.ld_notes.split("\n") : [];
                    var ld_notes_Html = "<td><ul style='list-style-type: disc;'>";
                    $.each(ld_notes_Lines, function (index, line) {
                        // Trim the line to remove any leading or trailing spaces
                        var trimmedLine_ld_notes = $.trim(line);
                        // Skip empty lines
                        if (trimmedLine_ld_notes !== "") {
                            ld_notes_Html += "<li class='item-notes'>" + trimmedLine_ld_notes + "</li>";
                        }
                    });
                    ld_notes_Html += "</ul></td>";
                    var status;
                    switch (item.status) {
                        case '1':
                            status = 'Pending Review';
                            break;
                        case '2':
                            // status = 'Pending';
                            status = 'Outstanding';
                            break;
                        case '3':
                            status = 'Rejected';
                            break;
                        case '4':
                            status = 'Approved';
                            break;
                    }
                    html += "<tr id='delete_checklist" + item.id + "' style='background-color:#fbfbfb'>";
                    html += "<td> " + item.name + "</td>";
                    if (item.task_leads_status == 3) {
                        html += ld_notes_Html;
                    }
                    // html += "<td> " + item.description + "</td>";
                    // html += "<td> " + item.doc_type + "</td>";
                    // html += "<td> " + item.show_item_names + "</td>";
                    // html += instructionHtml;
                    html += "<td class='tw-text-neutral-900 tw-mt-1' style='width:100px;'><span data-toggle='tooltip' data-title='" + item.dt_new_dateadded + "' class='text-has-action' > " + item.new_dateadded + "</span></td>";
                    // html += "<td><select style='width: 145px;' class='status-select form-control' data-task-id='" + item.id + "'>" +
                    //     "<option value='1' " + (item.status === '1' ? 'selected' : '') + ">Pending Review</option>" +
                    //     "<option value='2' " + (item.status === '2' ? 'selected' : '') + ">Outstanding</option>" +
                    //     "<option value='3' " + (item.status === '3' ? 'selected' : '') + ">Rejected</option>" +
                    //     "<option value='4' " + (item.status === '4' ? 'selected' : '') + ">Approved</option>" +
                    //     "</select></td>";
                    // Check if $samegroup is true (1) or false (0)
                    if (sameGroup) {
                        html += "<td><select style='width: 145px;' class='status-select form-control' data-task-id='" + item.id + "'>" +
                            "<option value='1' " + (item.status === '1' ? 'selected' : '') + ">Pending Review</option>" +
                            "<option value='2' " + (item.status === '2' ? 'selected' : '') + ">Outstanding</option>" +
                            "<option value='3' " + (item.status === '3' ? 'selected' : '') + ">Rejected</option>" +
                            "<option value='4' " + (item.status === '4' ? 'selected' : '') + ">Approved</option>" +
                            "</select></td>";
                    } else {
                        html += "<td>" +
                            (item.status === '1' ? 'Pending Review' : '') +
                            (item.status === '2' ? 'Outstanding' : '') +
                            (item.status === '3' ? 'Rejected' : '') +
                            (item.status === '4' ? 'Approved' : '') +
                            "</td>";
                    }
                    // Check if file_data is present
                    if (item.file_data.length > 0) {
                        html += "<td> <div style='overflow-y: scroll; max-height: 150px; width:422px;'><div style='max-height: 150px;'>";
                        $.each(item.file_data, function (fileIndex, fileItem) {
                            var view_url = fileItem.file_url.replace("dl.dropboxusercontent.com", "www.dropbox.com");
                            if (fileItem.check_filetype == 'jpeg' || fileItem.check_filetype == 'png' || fileItem.check_filetype == 'jpg' || fileItem.check_filetype == 'HEIC' || fileItem.check_filetype == 'heic') {
                                html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a><a href='" + view_url + "' target='_blank'><i style='margin-left:5px;' class='fa fa-eye' aria-hidden='true'></i></a></div>";
                                html += "<a href='" + fileItem.file_url + "' target='_blank'><img loading='lazy' style='width:100%; margin: 7px;' src='" + fileItem.file_url + "'></a></div>";
                            } else if (fileItem.check_filetype == 'pdf') {
                                html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a><a href='" + view_url + "' target='_blank'><i style='margin-left:5px;' class='fa fa-eye' aria-hidden='true'></i></a></div>";
                                html += "<a href='" + fileItem.file_url + "' target='_blank'><img loading='lazy' style='width:125px; margin: 5px; height: 135px;' src='<?php echo base_url('assets/images/image.webp'); ?>'></a></div>";

                            } else if (fileItem.check_filetype === 'msword' || fileItem.check_filetype === 'vnd.openxmlformats-officedocument') {
                                html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a><a href='" + view_url + "' target='_blank'><i style='margin-left:5px;' class='fa fa-eye' aria-hidden='true'></i></a></div>";
                                html += "<a href='" + fileItem.file_url + "' target='_blank'><img loading='lazy' style='width:125px; margin: 5px; height: 135px;' src='<?php echo base_url('assets/images/msword_new.webp'); ?>'></a></div>";
                            } else {
                                html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a></div><a href='" + fileItem.dl_file_url + "'>";
                                html += "<img loading='lazy' style='width:125px; margin: 5px; height: 135px;' src='<?php echo base_url('assets/images/general.webp'); ?>'></a></div>";
                            }
                        });
                        html += "</div></div></td>";
                    } else {
                        html += "<td><div style='color: #31708f;'><span class='no-margin font-medium-xs bold' style='display: flex;justify-content: center;color: #1f7efabb;'>Not Avaiable yet</div></div></td>";
                    }
                    if (sameGroup) {
                        html += "<td><a href='#' class='delete-checklist-link' data-id='" + item.id + "'><i class='fa fa-trash' style='color:red;'></i></a></td>";

                    } else {
                        html += "<td>-</td>";
                    }
                    html += "</tr>";
                });

                html += "</tbody></table>";
                $("#data-container").html(html);
            } else {
                var html = "<table class='table dt-table table-ticket-reports dt-inline dataTable no-footer'>";
                html += "<thead><tr><th>Name</th><th>Description</th><th>Created at</th><th>Status</th><th>Documents</th></tr></thead>";
                html += "<tbody id='checklist_table'>";
                html += "</tbody>";
                html += "</table>";
                html += "<div id='no_checklist_record_found' class='alert alert-info' style='margin-top:10px;'><span class='no-margin font-medium-xs bold' style='display: flex;justify-content: center;'>No Checklist available</div></div>";
                $("#data-container").html(html);
            }
        },
        error: function (error) {
            console.log('Error:', error);
        }
    });
    // // Change the checklist status
    // $(document).off('change', '.status-select').on('change', '.status-select', function () {
    //     var task_id = $(this).data('task-id');
    //     var newStatus = $(this).val();
    //     var lead_id = $('#lead_id').val();
    //     if (confirm('Are you sure you want to change the status?')) {
    //         $.ajax({
    //             url: "<?php echo admin_url('leads/checklist_updateStatus'); ?>",
    //             type: 'POST',
    //             data: {
    //                 task_id: task_id,
    //                 lead_id: lead_id,
    //                 newStatus: newStatus
    //             },
    //             success: function (response) {
    //                 if (response == 1) {
    //                     alert_float('success', 'Checklist status updated successfully.');
    //                 }
    //             },
    //             error: function (error) {
    //                 alert('error');
    //                 console.error('Error updating status:', error);
    //             }
    //         });
    //     }
    // });
    // Change the status of checklist
    $(document).off('change', '.status-select').on('change', '.status-select', function () {
        var task_id = $(this).data('task-id');
        var newStatus = $(this).val();
        var lead_id = $('#lead_id').val();

        if (newStatus === '3') { // 'Rejected' option selected
            // Open the modal
            $('#statusChangeModal').modal('show');

            // Handle form submission
            $('#submitStatusChange').off('click').on('click', function () {
                if (document.getElementById('statusChangeForm').checkValidity()) {
                    var rejectionReason = $('#rejectionReason').val();

                    // Perform AJAX request
                    $.ajax({
                        url: "<?php echo admin_url('leads/checklist_updateStatus'); ?>",
                        type: 'POST',
                        data: {
                            task_id: task_id,
                            lead_id: lead_id,
                            newStatus: newStatus,
                            rejectionReason: rejectionReason
                        },
                        success: function (response) {
                            if (response == 1) {
                                alert_float('success', 'Checklist status updated successfully.');
                                // Close the modal after success
                                $('#statusChangeModal').modal('hide');
                            }
                        },
                        error: function (error) {
                            alert('error');
                            console.error('Error updating status:', error);
                        }
                    });
                } else {
                    $('.invalid-feedback').css('display', 'inline-block');
                }
            });
        } else {
            var task_id = $(this).data('task-id');
            var newStatus = $(this).val();
            var lead_id = $('#lead_id').val();
            if (confirm('Are you sure you want to change the status?')) {
                $.ajax({
                    url: "<?php echo admin_url('leads/checklist_updateStatus'); ?>",
                    type: 'POST',
                    data: {
                        task_id: task_id,
                        lead_id: lead_id,
                        newStatus: newStatus
                    },
                    success: function (response) {
                        if (response == 1) {
                            alert_float('success', 'Checklist status updated successfully.');
                        }
                    },
                    error: function (error) {
                        alert('error');
                        console.error('Error updating status:', error);
                    }
                });
            }
        }
    });
</script>
<!-- update the checklsit -->
<script>
    window.addEventListener('beforeunload', function (event) {
        event.stopImmediatePropagation();
    });
    $('#checklist_form').submit(function (e) {
        e.preventDefault();

        // Remove any existing error messages
        $('.error-message').remove();
        var url = $('#lead_url').val();
        // Serialize the form data
        var formData = $(this).serialize();
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    var sameGroup = <?php echo $data['samegroup'] ? 'true' : 'false'; ?>;
                    // Create a success alert and append it to the body 
                    alert_float('success', 'Checklist updated successfully.');
                    // Remove the success alert after a delay

                    window.location.reload();
                    $("#no_checklist_record_found").css("display", "none");
                    setTimeout(function () {
                        successAlert.remove();
                    }, 5000);
                    $('#checklist_form')[0].reset();
                    // append the checklist when we create the new one
                    $('#checklist_table').find('tr').remove();
                    $.each(response.data, function (index, item) {
                        // redirect to the case
                        var case_url = "<?php echo admin_url('cases/index/') ?>" + item.lead_id;
                        window.location.href = case_url;

                        var instructionLines = item.instruction.split("\n");
                        var instructionHtml = "<td><ul style='list-style-type: disc;'>";
                        $.each(instructionLines, function (index, line) {
                            // Trim the line to remove any leading or trailing spaces
                            var trimmedLine = $.trim(line);
                            // Skip empty lines
                            if (trimmedLine !== "") {
                                instructionHtml += "<li>" + trimmedLine + "</li>";
                            }
                        });
                        instructionHtml += "</ul></td>";
                        // show the ld notes in the table
                        var ld_notes_Lines = item.ld_notes.split("\n");
                        var ld_notes_Html = "<td><ul style='list-style-type: disc;'>";
                        $.each(ld_notes_Lines, function (index, line) {
                            // Trim the line to remove any leading or trailing spaces
                            var ld_notes_Line = $.trim(line);
                            // Skip empty lines
                            if (ld_notes_Line !== "") {
                                ld_notes_Html += "<li>" + ld_notes_Line + "</li>";
                            }
                        });
                        ld_notes_Html += "</ul></td>";
                        var status;
                        switch (item.status) {
                            case '1':
                                status = 'Pending Review';
                                break;
                            case '2':
                                // status = 'Pending';
                                status = 'Outstanding';
                                break;
                            case '3':
                                status = 'Rejected';
                                break;
                            case '4':
                                status = 'Approved';
                                break;
                        }

                        var html = "<tr  id='delete_checklist" + item.id + "' style='background-color:#fbfbfb'>";
                        html += "<td> " + item.name + "</td>";
                        html += "<td>" + ld_notes_Html + "</td>";
                        // html += "<td> " + item.description + "</td>";
                        // html += "<td> " + item.doc_type + "</td>";
                        // html += instructionHtml;
                        html += "<td class='tw-text-neutral-900 tw-mt-1' style='width:100px;'><span data-toggle='tooltip' data-title='" + item.dt_new_dateadded + "' class='text-has-action' > " + item.new_dateadded + "</span></td>";
                        html += "<td><select style='width: 145px;' class='status-select form-control' data-task-id='" + item.id + "'>" +
                            "<option value='1' " + (item.status === '1' ? 'selected' : '') + ">Pending Review</option>" +
                            "<option value='2' " + (item.status === '2' ? 'selected' : '') + ">Outstanding</option>" +
                            "<option value='3' " + (item.status === '3' ? 'selected' : '') + ">Rejected</option>" +
                            "<option value='4' " + (item.status === '4' ? 'selected' : '') + ">Approved</option>" +
                            "</select></td>";

                        // Check if file_data is present
                        if (item.file_data.length > 0) {
                            html += "<td> <div style='overflow-y: scroll; max-height: 150px; width:422px;'><div style='max-height: 150px;'>";
                            $.each(item.file_data, function (fileIndex, fileItem) {
                                if (fileItem.check_filetype == 'jpeg' || fileItem.check_filetype == 'png' || fileItem.check_filetype == 'jpg') {
                                    html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a><a href='" + fileItem.file_url + "' target='_blank'><i style='margin-left:5px;' class='fa fa-eye' aria-hidden='true'></i></a></div>";
                                    html += "<a href='" + fileItem.file_url + "' target='_blank'><img loading='lazy' style='width:100%; margin: 7px;' src='" + fileItem.file_url + "'></a></div>";
                                } else if (fileItem.check_filetype == 'pdf') {
                                    html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a><a href='" + fileItem.file_url + "' target='_blank'><i style='margin-left:5px;' class='fa fa-eye' aria-hidden='true'></i></a></div>";
                                    html += "<a href='" + fileItem.file_url + "' target='_blank'><img loading='lazy' style='width:125px; margin: 5px; height: 135px;' src='<?php echo base_url('assets/images/image.webp'); ?>'></a></div>";

                                } else {
                                    html += "<div class='col-md-6'><div style='display: flex;justify-content: center;align-items: center;'><a href='" + fileItem.dl_file_url + "'><i class='fa fa-download' aria-hidden='true'></i></a></div><a href='" + fileItem.dl_file_url + "'>";
                                    html += "<img loading='lazy' style='width:125px; margin: 5px; height: 135px;' src='https://img.freepik.com/premium-psd/3d-folder-data-file-storage-icon-illustration_148391-2771.jpg'></a></div>";
                                }
                            });
                            html += "</div></div></td>";
                        } else {
                            html += "<td><div style='color: #31708f;'><span class='no-margin font-medium-xs bold' style='display: flex;justify-content: center;color: #1f7efabb;'>Not Available yet</div></div></td>";
                        }
                        if (sameGroup) {
                            html += "<td><a href='#' class='delete-checklist-link' data-id='" + item.id + "'><i class='fa fa-trash' style='color:red;'></i></a></td>";

                        } else {
                            html += "<td>-</td>";
                        }
                        html += "</tr>";

                        $('#checklist_table').append(html);
                    });

                } else {
                    // Display validation errors
                    if (response.errors) {
                        $.each(response.errors, function (field, message) {
                            var errorDiv = $('<div class="error-message" style="color: red;">' + message + '</div>');
                            $('[name="' + field + '"]').parent().append(errorDiv);
                        });
                    } else {
                        alert_float('error', 'Validation failed. Please check the form.');
                    }
                }
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    });
    // Reset form
    $(document).ready(function () {
        $('#reset_from_checklist').on('click', function () {
            $('#checklist_form')[0].reset();
        });
        // checklist delete record show
        $(document).off('click', '.delete-checklist-link').on('click', '.delete-checklist-link', function (e) {
            e.preventDefault();
            var checklistId = $(this).data('id');
            var tdIdToRemove = 'delete_checklist' + checklistId;
            if ($(this).data('delete-in-progress')) {
                return;
            }
            $(this).data('delete-in-progress', true);
            var confirmationShown = false;
            if (!confirmationShown) {
                if (confirm('Are you sure you want to delete this checklist?')) {
                    confirmationShown = true; // Set confirmation flag
                } else {
                    $(this).data('delete-in-progress', false);
                    return;
                }
            }
            $.ajax({
                url: "<?php echo admin_url('leads/delete_checklist_details/'); ?>" + checklistId,
                type: "POST",
                success: function (response) {
                    // Handle success response
                    $('#lead-form-submit').prop('disabled', true);
                    alert_float('success', 'Checklist deleted successfully.');
                    _lead_init_data(response, response.id);
                    $('a[href="' + response.leads_status + '"]').tab('show');

                },
                error: function (error) {
                    $('#lead-form-submit').prop('disabled', false);
                    alert_float('error', 'Checklist not deleted.');
                },
                complete: function () {
                    $(this).data('delete-in-progress', false);
                }
            });
        });
    });

</script>

</html>