@extends('template.app')

@section('meta') 
@endsection

@section('title')
    Tickets
@endsection

@section('styles')
<style>
     .highlight {
        background-color: #ffff99; 
    }
    #data-table td,
    #data-table th {
        padding: 10px 12px !important; 
        font-size: 15px;
        text-align: center;
        white-space: nowrap;
        min-width: 120px; 
    }
    .form-group .custom_color {
        background-color: lightgrey !important;
    }
    
    .modal-header {
        color: #000 !important;
    }
    
    .modal-header .btn-close {
        filter: none; 
    }
</style>
@endsection
@section('content')
<!-- Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<style>
     /* Label fix */
    .custom-label {
        color: #000 !important;
        font-weight: 600;
    }

    .highlight {
        background-color: #ffff99;
    }

    #data-table td,
    #data-table th {
        padding: 10px 12px !important;
        font-size: 15px;
        text-align: center;
        white-space: nowrap;
        min-width: 120px;
    }

    .form-group .custom_color {
        background-color: lightgrey !important;
    }

    .modal-header {
        color: #000 !important;
    }

    .modal-header .btn-close {
        filter: none;
    }

    .select2-container .select2-selection--single {
        height: 30px;
    }

    .mt-2 {
        font-size: 15px;
        margin-left: 15px;
    }

    .custom-select {
        width: 200px !important;
    }

    .custom-form-spacing {
        margin-bottom: -19px;
    }

    .table {
        min-height: 600px;
    }

</style>
<div class="page-breadcrumb">
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">Ticket Generated</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>

                        <li class="breadcrumb-item text-muted active" aria-current="page">List</li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="col-5 align-self-center">
            <div class="customize-input float-right">
                <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{ route('add_ticket') }}">Add New</a>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body table-responsive" id="datatable" style="text-align: center;">
                    <table class="table table-bordered data-table tables" id="data-table" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Ticket No</th>
                                <th>Title</th>
                                <th>Description</th>
                                <th>Contact</th>
                                <th>Email</th>
                                <th>Date</th>
                                <th>Date Of Completion</th>
                                <th>User</th>
                                <th>Status</th>
                                <th>Tech Team Remark</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Modal For Status Change -->
        <div class="modal fade" id="ticketModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <!-- Modal Header -->
                    <div class="modal-header">
                        <h3 class="modal-title" id="ticket_module_title">Support Tickets</h3>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
                    </div>
        
                    <!-- Modal Body -->
                    <div class="modal-body">
                        <form id="ticketForm" enctype="multipart/form-data">
                            @csrf
                            <input type="hidden" id="ticket_id" name="id">
        
                            <!-- Row 1: Status & Priority -->
                            <div class="row mb-3">
                                <div class="form-group col-sm-6">
                                    <label for="status" class="custom-label">Status</label>
                                    <select class="form-control" name="status" id="status">
                                        <option value="pending" selected>Open</option>
                                        <option value="in_progress">Work In Progress</option>
                                        <option value="completed">Completed</option>
                                        <option value="cancel">Approve Or Cancel</option>
                                    </select>
                                </div>

                                <div class="form-group col-sm-6">
                                    <label for="priority" class="custom-label">Priority</label>
                                    <select class="form-control" name="priority" id="priority">
                                        <option value="" selected>Select Priority</option>
                                        <option value="low">Low</option>
                                        <option value="medium">Medium</option>
                                        <option value="high">High</option>
                                    </select>
                                </div>
                            </div>
        
                            <!-- Row 2: Date & Image -->
                            <div class="row mb-3">
                                <div class="form-group col-sm-6">
                                    <label for="date" class="custom-label">Date Of Completion</label>
                                    <input type="date" class="form-control" id="date" name="date">
                                </div>
                                <div class="form-group col-sm-6">
                                    <label for="image" class="custom-label">Attachment</label>
                                    <input type="file" class="form-control" id="image" name="image" accept="image/*">
                                </div>
                            </div>
        
                            <!-- Row 3: Remark -->
                            <div class="row">
                                <div class="form-group col-sm-12">
                                    <label for="remark" class="custom-label">Remark</label>
                                    <textarea name="remark" id="remark" class="form-control" placeholder="Enter Remark" rows="3"></textarea>
                                </div>
                            </div>
                        </form>
                    </div>
        
                    <!-- Modal Footer -->
                    <div class="modal-footer">
                        <button type="submit" id="ticketSubmit" class="btn btn-outline-primary btn-sm">Submit!</button>
                        <button type="button" class="btn btn-outline-primary btn-sm" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>




    </div>
</div>
@endsection
@section('scripts')
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" />
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).ready(function () {
        $('.js-example-basic-single').select2();

        let tableColumns = [
            { data: 'id', name: 'id', class: 'text-center' },
            { data: 'ticket_no', name: 'ticket_no' },
            { data: 'title', name: 'title', class: 'text-center' },
            {
                data: 'description',
                name: 'description',
                class: 'text-center',
                render: function (data, type, row) {
                    if (!data) return '';
                    let shortText = data.length > 15 ? data.substr(0, 15) + '...' : data;
                    return `<span title="${data.replace(/"/g, '&quot;')}">${shortText}</span>`;
                }
            },
            { data: 'contact', name: 'contact', class: 'text-center' },
            { data: 'email_id', name: 'email_id', class: 'text-center' },
            { data: 'created_at', name: 'created_at', class: 'text-center'},
            { data: 'date', name: 'date', class: 'text-center'},
            { data: 'user_name', name: 'user_name', class: 'text-center' },
            { data: 'status', name: 'status', class: 'text-center' },
            {
                data: 'remark',
                name: 'remark',
                class: 'text-center',
                render: function (data, type, row) {
                    if (!data) return '';
                    let shortText = data.length > 15 ? data.substr(0, 15) + '...' : data;
                    return `<span title="${data.replace(/"/g, '&quot;')}">${shortText}</span>`;
                }
            },
            {
                data: 'action',
                name: 'action',
                orderable: false,
                searchable: false,
                class: 'text-center'
            }
        ];

        window.LaravelDataTables = window.LaravelDataTables || {};
        window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '{{ route("tickets") }}',
                method: 'GET',
                data: function (d) {
                    d.title = $(".datatable-form-filter input[name='title']").val();
                    d.description = $(".datatable-form-filter select[name='description']").val();
                    d.contact = $(".datatable-form-filter select[name='contact']").val();
                    d.email_id = $(".datatable-form-filter select[name='email_id']").val();
                    d.user_name = $(".datatable-form-filter input[name='user_name']").val();
                    d.status = $(".datatable-form-filter select[name='status']").val();
                }
            },
            columns: tableColumns,
            language: {
                "info": "_START_ - _END_ of _TOTAL_",
                "lengthMenu": "_MENU_ ",
                "infoFiltered": ""
            },
            paging: true,
            searching: false,
            scrollCollapse: true,
            bSortCellsTop: true,
            order: [[0, 'DESC']],
            responsive: true,
            dom: '<"top"f>rt<"bottom"ipl><"clear">',
            pageLength: 10,
        });

        $('.datatable-form-filter input').on('keyup', function (e) {
            if ($(this).val().length >= 3 || e.keyCode == 13 || !$(this).val()) {
                window.LaravelDataTables["dataTableBuilder"].draw();
            }
        });

        $('.datatable-form-filter select').on('change', function () {
            window.LaravelDataTables["dataTableBuilder"].draw();
        });
    });

    function change_status(object) {
        var id = $(object).data("id");
        var status = $(object).data("status");

        if (confirm('Are you sure?')) {
            $.ajax({
                url: "{!! route('fule_type.change.status') !!}",
                dataType: "json",
                type: "POST",
                data: {
                    id: id,
                    status: status,
                    _token: "{{ csrf_token() }}"
                },
                success: function(response) {
                    if (response.code == 200) {
                        window.LaravelDataTables["dataTableBuilder"].ajax.reload();
                        toastr.success('Status changed successfully', 'Success');
                    } else {
                        toastr.error('Failed to change status', 'Error');
                    }
                }
            });
        }
    }
    
    function support_ticket(object) {
        const modalElement = document.getElementById('ticketModal');
        const recordId = $(object).data("id");
        let status = $(object).data("status");
    
        // Fallback to 'pending' (Open) if empty or undefined
        status = (status && status.trim()) ? status : "pending";
    
        $("#ticket_id").val(recordId);
        $("#status").val(status);
        $("#priority").val('');
        $("#date").val('');
        $("#image").val('');
        $("#remark").val('');
    
        $('#ticket_module_title').text('Support Ticket');
    
        if (modalElement) {
            const myModal = new bootstrap.Modal(modalElement);
            myModal.show();
        } else {
            console.error("Modal element not found in DOM!");
        }
    }


    
    $('#ticketSubmit').on('click', function (e) {
        e.preventDefault();
    
        var formElement = document.getElementById('ticketForm');
        var formData = new FormData(formElement);
    
        $.ajax({
            url: "{{ route('ticket.status.update') }}",
            type: "POST",
            data: formData,
            processData: false, // Needed for FormData
            contentType: false, // Needed for FormData
            success: function (response) {
                if (response.success) {
                    Swal.fire('Success', response.message, 'success');
                    $('#ticketModal').modal('hide');
                    window.LaravelDataTables["dataTableBuilder"].ajax.reload();
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function (xhr) {
                let message = 'Server error occurred.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                Swal.fire('Error', message, 'error');
            }
        });
    });

</script>

@endsection