@extends('backend.master')
@section('title', 'Journal Management')

@section('backend_content')

    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">

    <!-- Page Title Area -->
    <div class="container-fluid">
        <div class="row page-title clearfix">
            <div class="page-title-left">
                <h6 class="page-title-heading mr-0 mr-r-5">Journals</h6>
                <p class="page-title-description mr-0 d-none d-md-inline-block">Manage your journals</p>
            </div>
            <div class="page-title-right d-none d-sm-inline-flex">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item active">Journals</li>
                </ol>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="widget-list">
            <div class="row">
                <div class="widget-holder col-md-12">
                    <div class="widget-bg">
                        <div class="widget-heading widget-heading-border d-flex justify-content-between align-items-center">
                            <h5 class="widget-title">Journal List</h5>
                            @can('create Journal')
                                <button type="button" class="btn btn-primary btn-sm" onclick="showAddModal()">
                                    <i class="feather feather-plus"></i> Add New Journal
                                </button>
                            @endcan
                        </div>

                        <div class="widget-body table-responsive">
                            <table id="journalTable"
                                class="table table-striped table-bordered text-center w-100 align-middle">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="15%">Cover Image</th>
                                        <th width="20%">Volume</th>
                                        <th width="20%">Issue</th>
                                        <th width="15%">Status</th>
                                        <th width="15%">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Yajra DataTables will populate this dynamically -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Modal for Create/Edit -->
    <div class="modal fade" id="journalModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add Journal</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="journalForm" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-body">
                        <input type="hidden" id="journal_id" name="journal_id">

                        <div class="form-group">
                            <label>Volume</label>
                            <input type="text" class="form-control" id="volume" name="volume" required>
                        </div>

                        <div class="form-group">
                            <label>Issue</label>
                            <input type="text" class="form-control" id="issue" name="issue" required>
                        </div>

                        <div class="form-group">
                            <label>Link</label>
                            <input type="url" class="form-control" id="link" name="link" required>
                        </div>

                        <div class="form-group">
                            <label>Cover Image (Leave empty to keep old image on edit)</label>
                            <input type="file" class="form-control" id="cover_image" name="cover_image" accept="image/*">
                            <div id="imagePreview" class="mt-3"></div>
                        </div>

                        <div class="form-group">
                            <label class="d-block">Status</label>
                            <!-- Hidden input ensures '0' is sent if toggle is OFF -->
                            <input type="hidden" name="status" value="0">

                            <!-- Bootstrap 4 Toggle Switch -->
                            <div class="custom-control custom-switch custom-control-inline">
                                <input type="checkbox" class="custom-control-input" id="statusToggle" name="status"
                                    value="1" checked>
                                <label class="custom-control-label" for="statusToggle">Active</label>
                            </div>

                            <small class="text-danger d-block mt-2">* Setting this to Active will automatically deactivate
                                all other journals.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" id="saveBtn">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap Modal for Delete Confirmation -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
            <div class="modal-content text-center">
                <div class="modal-header border-0 pb-0">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body pt-0">
                    <i class="feather feather-alert-circle text-danger mb-3" style="font-size: 50px;"></i>
                    <h4>Are you sure?</h4>
                    <p class="text-muted">You won't be able to revert this!</p>
                    <input type="hidden" id="delete_journal_id">
                </div>
                <div class="modal-footer justify-content-center border-0 pt-0">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Yes, delete it!</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>

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

        // Initialize Yajra DataTable
        var table = $('#journalTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('admin.journals.fetch') }}",
            columns: [
                { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                { data: 'cover_image', name: 'cover_image', orderable: false, searchable: false },
                { data: 'volume', name: 'volume' },
                { data: 'issue', name: 'issue' },
                { data: 'status', name: 'status', orderable: false, searchable: false },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ],
            drawCallback: function (settings) {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }
        });

        function fetchJournals() {
            table.ajax.reload(null, false);
        }

        // Show Add Modal
        function showAddModal() {
            $('#journalForm')[0].reset();
            $('#journal_id').val('');
            $('#imagePreview').html('');
            $('#statusToggle').prop('checked', true);
            $('#modalTitle').text('Add Journal');
            $('#journalModal').modal('show');
        }

        // Show Edit Modal & Fetch Data
        function editJournal(id) {
            // Added leading slash '/'
            $.get("/admin/journals/" + id + "/edit", function (response) {
                $('#modalTitle').text('Edit Journal');
                $('#journal_id').val(response.journal.id);
                $('#volume').val(response.journal.volume);
                $('#issue').val(response.journal.issue);
                $('#link').val(response.journal.link);

                if (response.journal.status == '1') {
                    $('#statusToggle').prop('checked', true);
                } else {
                    $('#statusToggle').prop('checked', false);
                }

                if (response.journal.cover_image) {
                    $('#imagePreview').html('<img src="/' + response.journal.cover_image + '" width="100" style="border-radius:4px;">');
                } else {
                    $('#imagePreview').html('');
                }

                $('#journalModal').modal('show');
            }).fail(function (xhr) {
                alert('Error fetching data: ' + xhr.status + ' ' + xhr.statusText);
            });
        }

        // Submit Form (Create or Update)
        $('#journalForm').submit(function (e) {
            e.preventDefault();

            let id = $('#journal_id').val();
            // Added leading slash '/'
            let url = id ? "/admin/journals/" + id : "{{ route('admin.journals.store') }}";
            let formData = new FormData(this);

            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#journalModal').modal('hide');
                    $('#journalForm')[0].reset();
                    fetchJournals();
                    if (typeof toastr !== 'undefined') {
                        toastr.success(response.success);
                    } else {
                        alert(response.success);
                    }
                },
                error: function (xhr) {
                    let errorMsg = xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : 'An error occurred.';
                    alert('Error (' + xhr.status + '): ' + errorMsg);
                }
            });
        });

        // Show Delete Confirmation Modal
        function confirmDelete(id) {
            $('#delete_journal_id').val(id);
            $('#deleteModal').modal('show');
        }

        // Execute Delete Request
        $('#confirmDeleteBtn').click(function () {
            let id = $('#delete_journal_id').val();

            $.ajax({
                type: "POST",
                url: "/admin/journals/" + id, // Fixed: Added leading slash '/'
                data: {
                    _method: 'DELETE',
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    $('#deleteModal').modal('hide');
                    fetchJournals();
                    if (typeof toastr !== 'undefined') {
                        toastr.success(response.success || response.message);
                    } else {
                        alert('Journal deleted successfully!');
                    }
                },
                error: function (xhr) {
                    let errorMsg = 'Could not delete journal.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    } else if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    }

                    alert('Delete Failed (Status ' + xhr.status + '): ' + errorMsg);
                }
            });
        });
    </script>
@endsection