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

@section('backend_content')

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

    <!-- Custom Table Styles -->
    <style>
        #permissionsTable .btn i.feather {
            width: 18px !important;
            height: 18px !important;
        }

        #permissionsTable .btn {
            padding: 5px 8px !important;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
    </style>

    <!-- 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">Permissions</h6>
                <p class="page-title-description mr-0 d-none d-md-inline-block">Manage system permissions and access
                    controls</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">Permissions</li>
                </ol>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="widget-list">
            <div class="row">
                <div class="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">Permissions List</h5>
                            <div>
                                @can('create Permission')
                                    <button type="button" class="btn btn-success btn-sm mr-2" onclick="showImportModal()">
                                        <i class="feather feather-upload"></i> Import Excel
                                    </button>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="showAddModal()">
                                        <i class="feather feather-plus"></i> Add New Permission
                                    </button>
                                @endcan
                            </div>
                        </div>

                        <div class="widget-body table-responsive">
                            <table id="permissionsTable"
                                class="table table-striped table-bordered text-center w-100 align-middle">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="75%">Name</th>
                                        <th width="20%">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="permissionModal" 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 Permission</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="permissionForm">
                    @csrf
                    <div class="modal-body">
                        <input type="hidden" id="permission_id" name="permission_id">
                        <div class="form-group">
                            <label class="font-weight-bold">Permission Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" placeholder="e.g. edit articles"
                                required>
                            <small class="form-text text-muted">Use a descriptive, action-based name (lowercase
                                recommended).</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 Excel Import -->
    <div class="modal fade" id="importModal" 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">Import Permissions</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="importForm" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <strong>Format Rule:</strong> The Excel/CSV file must have a header row named exactly
                            <code>name</code>.
                            <div class="mt-2">
                                <!-- Download Sample Link -->
                                <a href="{{ route('admin.permissions.sample') }}"
                                    class="btn btn-sm btn-outline-info bg-white font-weight-bold">
                                    <i class="feather feather-download"></i> Download Sample CSV
                                </a>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="font-weight-bold">Select Excel/CSV File <span class="text-danger">*</span></label>
                            <input type="file" class="form-control-file" id="excel_file" name="excel_file"
                                accept=".xlsx, .xls, .csv" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-success" id="importBtn">Upload & Import</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-body pt-4">
                    <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_permission_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 DataTable
        var table = $('#permissionsTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('admin.permissions.fetch') }}",
            columns: [
                { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                { data: 'name', name: 'name' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ],
            drawCallback: function (settings) {
                if (typeof feather !== 'undefined') feather.replace();
            }
        });

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

        // --- Single Permission Create/Edit Logic ---
        function showAddModal() {
            $('#permissionForm')[0].reset();
            $('#permission_id').val('');
            $('#modalTitle').text('Add Permission');
            $('#permissionModal').modal('show');
        }

        function editPermission(id) {
            $.get("/admin/permissions/edit/" + id, function (response) {
                $('#modalTitle').text('Edit Permission');
                $('#permission_id').val(response.permission.id);
                $('#name').val(response.permission.name);
                $('#permissionModal').modal('show');
            });
        }

        $('#permissionForm').submit(function (e) {
            e.preventDefault();
            let formData = new FormData(this);
            let btn = $('#saveBtn');
            let originalText = btn.html();
            btn.html('<i class="feather feather-loader fa-spin"></i> Saving...').prop('disabled', true);

            $.ajax({
                type: "POST",
                url: "{{ route('admin.permissions.store') }}",
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#permissionModal').modal('hide');
                    btn.html(originalText).prop('disabled', false);
                    fetchTable();
                    if (typeof toastr !== 'undefined') { toastr.success(response.success); } else { alert(response.success); }
                },
                error: function (xhr) {
                    btn.html(originalText).prop('disabled', false);
                    if (xhr.status === 422) {
                        let errors = xhr.responseJSON.errors;
                        if (errors.name) {
                            if (typeof toastr !== 'undefined') { toastr.error(errors.name[0]); } else { alert(errors.name[0]); }
                        }
                    } else {
                        if (typeof toastr !== 'undefined') { toastr.error('An error occurred.'); } else { alert('An error occurred.'); }
                    }
                }
            });
        });

        // --- Excel Import Logic ---
        function showImportModal() {
            $('#importForm')[0].reset();
            $('#importModal').modal('show');
        }

        $('#importForm').submit(function (e) {
            e.preventDefault();
            let formData = new FormData(this);
            let btn = $('#importBtn');
            let originalText = btn.html();
            btn.html('<i class="feather feather-loader fa-spin"></i> Uploading...').prop('disabled', true);

            $.ajax({
                type: "POST",
                url: "{{ route('admin.permissions.import') }}",
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#importModal').modal('hide');
                    btn.html(originalText).prop('disabled', false);
                    fetchTable();
                    if (typeof toastr !== 'undefined') { toastr.success(response.success); } else { alert(response.success); }
                },
                error: function (xhr) {
                    btn.html(originalText).prop('disabled', false);
                    if (xhr.status === 422) {
                        if (typeof toastr !== 'undefined') { toastr.error('Please upload a valid Excel or CSV file.'); } else { alert('Please upload a valid file.'); }
                    } else {
                        let msg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'An error occurred during import.';
                        if (typeof toastr !== 'undefined') { toastr.error(msg); } else { alert(msg); }
                    }
                }
            });
        });

        // --- Delete Logic ---
        function confirmDelete(id) {
            $('#delete_permission_id').val(id);
            $('#deleteModal').modal('show');
        }

        $('#confirmDeleteBtn').click(function () {
            let id = $('#delete_permission_id').val();
            let btn = $(this);
            let originalText = btn.html();
            btn.html('<i class="feather feather-loader fa-spin"></i> Deleting...').prop('disabled', true);

            $.ajax({
                type: "DELETE",
                url: "/admin/permissions/destroy/" + id,
                success: function (response) {
                    $('#deleteModal').modal('hide');
                    btn.html(originalText).prop('disabled', false);
                    fetchTable();
                    if (typeof toastr !== 'undefined') { toastr.success(response.success); } else { alert(response.success); }
                },
                error: function (xhr) {
                    btn.html(originalText).prop('disabled', false);
                    if (typeof toastr !== 'undefined') { toastr.error('Could not delete permission.'); } else { alert('Could not delete permission.'); }
                }
            });
        });
    </script>
@endsection