@extends('admin.layouts.main-layout')
@section('title', 'Manage Projects')

@section('content')
    <!-- Content wrapper -->
    <div class="content-wrapper">
        <!-- Content -->
        <div class="container-xxl flex-grow-1 container-p-y">
            @if (session('success'))
                <div class="alert alert-success alert-dismissible" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            @elseif (session('error'))
                <div class="alert alert-danger alert-dismissible" role="alert">
                    {{ session('error') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            @endif
            <!-- Hoverable Table rows -->
            <div class="card">
                <h5 class="card-header">Manage Projects
                    <span class="float-end">
                        <a href="{{ route('add.project') }}"
                            class="btn rounded-pill btn-icon btn-outline-primary float-end ms-2"
                            style="font-size: 1.7em;">+</a>
                        {{-- <a href="{{ route('manage.courses') }}"
                            class="btn btn-icon rounded-pill btn-outline-secondary float-end">
                            <i class='bx bx-left-arrow-alt' style="font-size: 1.7rem;"></i>
                        </a> --}}
                    </span>
                </h5>
                <div class="card-body">
                    <div class="mb-4">
                        <button class="btn btn-sm btn-outline-danger me-2" id="bulk_delete">
                            <i class="bx bx-trash me-1"></i> Delete Selected
                        </button>

                        <button class="btn btn-sm btn-outline-primary me-2" id="bulk_status">
                            <i class="bx bx-toggle-left me-1"></i> Status Selected
                        </button>
                    </div>

                    <div class="table-responsive text-nowrap pb-4">
                        <table id="projects_table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <input type="checkbox" id="select_all">
                                    </th>
                                    <th>S. No.</th>
                                    <th>Subject Code (Subject Name)</th>
                                    <th>Project Code</th>
                                    <th>Project Title</th>
                                    <th>Project Position</th>
                                    <th>Project Image</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody class="table-border-bottom-0"></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <!--/ Hoverable Table rows -->
        </div>
    </div>
@endsection

@section('admin-custom-js')
    <script>
        let projectsTable = $('#projects_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('manage.projects.data') }}",

            pageLength: 25,
            lengthMenu: [10, 25, 50, 100],
            autoWidth: false,

            columns: [{
                    data: "checkbox",
                    orderable: false,
                    searchable: false
                },
                {
                    data: "id"
                },
                {
                    data: "subject"
                },
                {
                    data: "project_code"
                },
                {
                    data: "project_title"
                },
                {
                    data: "position_order"
                },
                {
                    data: "project_image"
                },
                {
                    data: "status"
                },
                {
                    data: "action"
                },
            ],

            columnDefs: [{
                    width: "80px",
                    targets: 0
                },
                {
                    width: "150px",
                    targets: 1
                }, // Subject
                {
                    width: "120px",
                    targets: 2
                }, // Project Code
                {
                    width: "250px",
                    targets: 3
                }, // Project Title
                {
                    width: "100px",
                    targets: 4
                }, // Position
                {
                    width: "120px",
                    targets: 5
                }, // Image
                {
                    width: "90px",
                    targets: 6
                }, // Status
                {
                    width: "90px",
                    targets: 7
                } // Actions
            ],

            drawCallback: function() {
                $('#select_all').prop('checked', false);
            }
        });

        $(document).on('click', '#select_all', function() {
            $('.row_checkbox').prop('checked', this.checked);
        });

        $(document).on('change', '.row_checkbox', function() {
            if (!this.checked) {
                $('#select_all').prop('checked', false);
            }
        });

        function getSelectedEncryptedIds() {
            let encrypted_ids = [];
            $('.row_checkbox:checked').each(function() {
                encrypted_ids.push($(this).val());
            });
            return encrypted_ids;
        }

        $('#bulk_status').on('click', function() {
            let encrypted_ids = getSelectedEncryptedIds();

            if (encrypted_ids.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No selection',
                    text: 'Please select at least one project.'
                });
                return;
            }

            Swal.fire({
                title: 'Update Status',
                text: `Change status for ${encrypted_ids.length} project(s)?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, update',
                cancelButtonText: 'Cancel'
            }).then((result) => {

                if (!result.isConfirmed) return;

                $('#bulk_status').prop('disabled', true);

                $.ajax({
                    url: "{{ route('projects.bulk.status') }}",
                    type: "POST",
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    data: {
                        encrypted_ids: encrypted_ids
                    },

                    success: function(result) {
                        Swal.fire({
                            icon: result.status === 'done' ? 'success' : 'error',
                            title: result.message,
                            timer: 1500,
                            showConfirmButton: false
                        });

                        if (result.status === 'done') {
                            setTimeout(() => {
                                projectsTable.ajax.reload(null, false);
                                $('#select_all').prop('checked', false);
                            }, 1500);
                        }
                    },

                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Server Error',
                            text: 'Something went wrong.'
                        });
                    },

                    complete: function() {
                        $('#bulk_status').prop('disabled', false);
                    }
                });
            });
        });

        $('#bulk_delete').on('click', function() {
            let encrypted_ids = getSelectedEncryptedIds();

            if (encrypted_ids.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No selection',
                    text: 'Please select at least one project.'
                });
                return;
            }

            const swalWithBootstrapButtons = Swal.mixin({
                customClass: {
                    confirmButton: "btn btn-success ms-2",
                    cancelButton: "btn btn-danger"
                },
                buttonsStyling: false
            });

            swalWithBootstrapButtons.fire({
                title: "Are you sure?",
                text: "You won't be able to revert this!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "No, cancel!",
                reverseButtons: true
            }).then((result) => {

                if (!result.isConfirmed) {
                    swalWithBootstrapButtons.fire({
                        title: "Cancelled",
                        text: "Your data is safe 🙂",
                        icon: "info",
                        timer: 1500,
                        showConfirmButton: false
                    });
                    return;
                }

                $('#bulk_delete').prop('disabled', true);

                $.ajax({
                    url: "{{ route('projects.bulk.delete') }}",
                    type: "POST",
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    data: {
                        encrypted_ids: encrypted_ids
                    },
                    success: function(result) {
                        swalWithBootstrapButtons.fire({
                            title: result.title,
                            text: result.message,
                            icon: result.status === 'done' ? 'success' : 'error',
                            timer: 1500,
                            showConfirmButton: false
                        });

                        if (result.status === 'done') {
                            setTimeout(() => {
                                projectsTable.ajax.reload(null, false);
                                $('#select_all').prop('checked', false);
                            }, 1500);
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Server Error',
                            text: 'Something went wrong. Please try again.'
                        });
                    },
                    complete: function() {
                        $('#bulk_delete').prop('disabled', false);
                    }
                });
            });
        });
    </script>
@endsection
