@extends('admin.admin_master')

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/css/folder-management.css') }}">
@endpush

@section('admin')
<div class="page-content">
    <div class="container-fluid">

        <!-- Toast Messages -->
        @if(session('toast'))
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    showToast('{{ session('toast.message') }}', '{{ session('toast.type') }}');
                });
            </script>
        @endif

        <!-- Legacy Success Alert (for backward compatibility) -->
        @if(session('message'))
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    showToast('{{ session('message') }}', 'success');
                });
            </script>
        @endif

        @if($errors->any())
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    showToast('{{ $errors->first() }}', 'error');
                });
            </script>
        @endif

        <!-- Enhanced Page Header with Navigation -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="page-header-card">
                    <div class="page-header-content">
                        <div class="d-flex align-items-center justify-content-between">
                            <!-- Left side: Page Icon & Title with Breadcrumb -->
                            <div class="d-flex align-items-center">
                                <!-- Page Icon -->
                                <div class="page-icon me-3">
                                    <div class="avatar-md">
                                        <div class="avatar-title bg-primary-subtle text-primary rounded-circle">
                                            <i class="ri-folder-line font-size-24"></i>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Page Title & Breadcrumb -->
                                <div class="flex-grow-1">
                                    <h4 class="page-title mb-1">Folder Management</h4>
                                    <!-- Breadcrumb Navigation -->
                                    <nav aria-label="breadcrumb">
                                        <ol class="breadcrumb mb-0" id="folderBreadcrumb">
                                            <li class="breadcrumb-item">
                                                <a href="#" onclick="navigateToRoot()" class="text-primary">
                                                    <i class="ri-home-4-line me-1"></i>
                                                </a>
                                            </li>
                                            <!-- Dynamic breadcrumb items will be added here -->
                                        </ol>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- View Toggle (Grid only) -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary btn-sm initially-hidden" onclick="navigateBack()" id="backBtn">
                            <i class="ri-arrow-left-line me-1"></i> Back
                        </button>
                     
                    </div>
                    <div class="d-flex gap-2">
                        @can('View Folder')
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="location.reload()" data-bs-toggle="tooltip" title="Refresh Folders">
                            <i class="ri-refresh-line font-size-12"></i>
                        </button>
                        @endcan
                        @can('Create Folder')
                        <button type="button" class="btn btn-primary btn-sm d-flex align-items-center" data-bs-toggle="modal" data-bs-target="#createFolderModal" title="Create New Folder">
                            <i class="ri-folder-add-line font-size-14 me-1"></i>
                            <span>Create Folder</span>
                        </button>
                        @endcan
                    </div>
                </div>
            </div>
        </div>

        <!-- Search and Filter Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card shadow-sm border-0 search-filter-card">
                    <div class="card-body p-3">
                        <div class="row g-3 align-items-center">
                            <!-- Search Input -->
                            <div class="col-md-4">
                                <div class="input-group">
                                    <span class="input-group-text bg-white border-end-0">
                                        <i class="ri-search-line text-muted"></i>
                                    </span>
                                    <input type="text" 
                                           class="form-control border-start-0" 
                                           id="folderSearchInput" 
                                           placeholder="Search folders..." 
                                           onkeyup="searchFolders()">
                                    <button class="btn btn-outline-secondary initially-hidden" type="button" onclick="clearSearch()" id="clearSearchBtn">
                                        <i class="ri-close-line"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Filter Options -->
                            <div class="col-md-5">
                                <select class="form-select" id="folderSortFilter" onchange="applyFilters()">
                                    <option value="name-asc">Name (A-Z)</option>
                                    <option value="name-desc">Name (Z-A)</option>
                                    <option value="date-newest">Newest First</option>
                                    <option value="date-oldest">Oldest First</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Folders Card -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4">
                        <!-- Grid View for Root Level -->
                        <div id="gridView" class="folder-grid-container">
                            @if($folders->count() > 0)
                                <div class="row g-3">
                                    @foreach($folders as $folder)
                                        @include('folders.folder_grid_item', ['folder' => $folder])
                                    @endforeach
                                </div>
                            @else
                                <div class="text-center py-5">
                                    <div class="avatar-lg mx-auto mb-3">
                                        <div class="avatar-title bg-soft-primary text-primary rounded-circle">
                                            <i class="ri-folder-line font-size-32"></i>
                                        </div>
                                    </div>
                                    <h5 class="font-size-16">No folders found</h5>

                                    @can('Create Folder')
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createFolderModal">
                                        <i class="ri-folder-add-line me-1"></i> Create First Folder
                                    </button>
                                    @else
                                    <div class="alert alert-info" role="alert">
                                        <i class="ri-information-line me-1"></i>
                                        You don't have permission to create folders.
                                    </div>
                                    @endcan
                                </div>
                            @endif
                        </div>

                        <!-- Table View for Inside Folder -->
                        <div id="tableView" class="folder-table-container d-none">
                            <div class="table-responsive folder-table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Name</th>
                                            <th>Type</th>
                                            <th>Items</th>
                                            <th>Modified</th>

                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="folderTableBody">
                                        <!-- Only folders will be displayed here. File rows removed. -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                            <!-- File Comment Modal -->
                            <div class="modal fade" id="fileCommentModal" tabindex="-1" aria-labelledby="fileCommentModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form id="fileCommentForm" method="POST" action="{{ route('files.updateComment') }}">
                                            @csrf
                                            <input type="hidden" name="file_id" id="fileCommentFileId">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="fileCommentModalLabel">Edit File Comment</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label for="fileCommentText" class="form-label">Comment</label>
                                                    <textarea class="form-control" name="comment" id="fileCommentText" rows="3"></textarea>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="submit" class="btn btn-primary">Save Comment</button>
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                    @push('scripts')
                    <script>
                        var fileCommentModal = document.getElementById('fileCommentModal');
                        if (fileCommentModal) {
                            fileCommentModal.addEventListener('show.bs.modal', function (event) {
                                var button = event.relatedTarget;
                                var fileId = button.getAttribute('data-file-id');
                                var comment = button.getAttribute('data-file-comment');
                                document.getElementById('fileCommentFileId').value = fileId;
                                document.getElementById('fileCommentText').value = comment || '';
                            });
                        }
                    </script>
                    @endpush
                    </div>
                </div>
            </div>
        </div>

        <!-- Create Folder Modal -->
        <div class="modal fade" id="createFolderModal" tabindex="-1" aria-labelledby="createFolderModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <form id="createFolderForm" action="{{ route('folders.store') }}" method="POST">
                        @csrf
                        <input type="hidden" name="parent_id" id="parent_id">
                        <div class="modal-header modal-header-primary d-flex justify-content-between">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                            <h5 class="modal-title mb-0" id="createFolderModalLabel">
                                <i class="ri-folder-add-line me-2 text-white"></i> <span class="text-white">Create New Folder</span>
                            </h5>
                            <div style="width: 24px;"></div> <!-- Spacer for balance -->
                        </div>
                        <div class="modal-body">
                            <div id="clientErrorMsg" class="alert alert-danger d-none mb-3"></div>
                            <div class="row g-4">
                                <div class="col-md-12">
                                    <div class="mb-4">
                                        <label for="name" class="form-label">Folder Name</label>
                                        <input type="text" name="name" id="name" class="form-control @if($errors->has('name')) is-invalid @endif" required placeholder="Enter folder name" value="{{ old('name') }}">
                                        @if($errors->has('name'))
                                            <span class="invalid-feedback d-block" role="alert">
                                                <i class="ri-error-warning-line me-2"></i>
                                                {{ $errors->first('name') }}
                                            </span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-top">
                            <button type="submit" class="btn btn-success px-4">
                                <i class="ri-folder-add-line me-1"></i> Create Folder
                            </button>
                            <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Share Folder Modal -->
        <div class="modal fade" id="shareFolderModal" tabindex="-1" aria-labelledby="shareFolderModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <form id="shareFolderForm" action="{{ route('folders.share') }}" method="POST">
                        @csrf
                        <input type="hidden" name="folder_id" id="share_folder_id">
                        <div class="modal-header modal-header-primary d-flex justify-content-between align-items-center">
                            <h5 class="modal-title mb-0" id="shareFolderModalLabel">
                                <i class="ri-share-line me-2"></i> Share Folder: <span id="shareFolderName" class="fw-normal">Loading...</span>
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <!-- Information Alert -->
                            <div class="alert alert-info d-flex align-items-start mb-4" role="alert">
                                <i class="ri-information-line font-size-16 me-2 mt-1"></i>
                                <div class="flex-grow-1">
                                    <small class="mb-0">
                                        <strong>Note:</strong> When you share this folder, permissions will automatically be applied to all existing subfolders and any new subfolders created in the future.
                                    </small>
                                </div>
                            </div>
                            
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <div class="mb-4">
                                        <label class="form-label">Share with Users  </label>
                                        <select name="users[]" id="shareUsersSelect" class="selectpicker form-control" multiple title="Select Users" data-actions-box="true" @cannot('Share Folder') disabled @endcannot>
                                       @foreach($users as $user)
                                                <option value="{{ $user->id }}">{{ $user->first_name }} {{ $user->last_name }} - {{ $user->email }}</option>
                                            @endforeach
                                        </select>
                                                   </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-4">
                                        <label class="form-label">Share with Roles</label>
                                        <select name="roles[]" id="shareRolesSelect" class="selectpicker form-control" multiple title="Select Roles" data-actions-box="true" @cannot('Share Folder') disabled @endcannot>
                                            @foreach($roles as $role)
                                                <option value="{{ $role->id }}">{{ $role->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                @can('Share Folder')
                                <div class="col-md-12">
                                    <div class="text-center mb-4">
                                        <button type="button" class="btn btn-primary btn-sm shadow-sm" id="addPermissionsBtn">
                                            <i class="ri-add-line me-1"></i> Add Selected Users/Roles
                                        </button>
                                    </div>
                                </div>
                                @else
                                <div class="col-md-12">
                                    <div class="text-center mb-4">
                                        <div class="alert alert-warning" role="alert">
                                            <i class="ri-information-line me-1"></i>
                                            You don't have permission to share folders.
                                        </div>
                                    </div>
                                </div>
                                @endcan
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <label class="form-label mb-0">Currently Shared With</label>
                                            @can('View Folder')
                                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="loadSavedPermissions(document.getElementById('share_folder_id').value)" title="Refresh">
                                                <i class="ri-refresh-line font-size-12 me-1"></i> Refresh
                                            </button>
                                            @endcan
                                        </div>
                                        <div class="border rounded p-3 share-permissions-container">
                                            <table class="table table-sm mb-0" id="shareWithTable">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th width="80">Type</th>
                                                        <th>Name</th>
                                                        <th>Details</th>
                                                        <th width="80">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td colspan="5" class="text-center text-muted">
                                                            <i class="ri-information-line me-1"></i>
                                                            Loading shared permissions...
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-top">
                            <button type="button" class="btn btn-success px-4" data-bs-dismiss="modal">
                                <i class="ri-check-line me-1"></i> Done
                            </button>
                            <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Required JavaScript variables -->
        <script>
            // Set global variables for JavaScript file
            window.folderNames = [
                @foreach($folders as $folder)
                    "{{ addslashes($folder->name) }}",
                @endforeach
            ];
            window.baseUrl = "{{ request()->getBaseUrl() }}";
            window.csrfToken = "{{ csrf_token() }}";
 </script>
 <script>
    window.permissions = {
        canViewFile: {{ auth()->user()->can('view file') ? 'true' : 'false' }},
        canShareFolder: {{ auth()->user()->can('share folder') ? 'true' : 'false' }}
    };
</script>
        <!-- External JavaScript -->
        <script src="{{ asset('assets/js/folder-management.js') }}?v={{ filemtime(public_path('assets/js/folder-management.js')) }}"></script>

    </div>
</div>
@endsection
