<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>CML ERP</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #f8f9fc; }
        
        /* Sidebar & Topbar (Inherited from Base Design) */
        #sidebar { width: 260px; background-color: #111425; position: fixed; height: 100vh; overflow-y: auto; z-index: 1000; }
        .sidebar-brand { color: #fff; padding: 1.5rem 1.25rem; font-weight: 700; }
        .sidebar-brand-icon { background: #5c4df0; padding: 0.5rem; border-radius: 8px; margin-right: 10px; }
        .sidebar-nav-item { color: #8a90a5; text-decoration: none; padding: 0.75rem 1.25rem; display: block; border-radius: 8px; margin: 0.2rem 1rem; font-size: 0.9rem; }
        .sidebar-nav-item:hover, .sidebar-nav-item.active { background-color: #5c4df0; color: #fff; }
        .sidebar-heading { color: #5a617a; font-size: 0.75rem; text-transform: uppercase; padding: 1rem 1.25rem 0.5rem; font-weight: 600; }
        
        #main-content { margin-left: 260px; min-height: 100vh; }
        .topbar { background: #fff; height: 70px; border-bottom: 1px solid #eaedf1; padding: 0 1.5rem; }
        
        /* Cards & Tables */
        .content-card { background: #fff; border: 1px solid #eaedf1; border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
        .table-custom th { background-color: #f8f9fc; color: #5a617a; font-weight: 600; font-size: 0.8rem; text-transform: uppercase; border-bottom: 2px solid #eaedf1; padding: 1rem; }
        .table-custom td { padding: 1rem; vertical-align: middle; font-size: 0.9rem; border-bottom: 1px solid #eaedf1; }
        
        /* Modal Customization */
        .modal-content { border-radius: 12px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
        .modal-header { border-bottom: 1px solid #eaedf1; background-color: #f8f9fc; border-radius: 12px 12px 0 0; }
        .modal-footer { border-top: 1px solid #eaedf1; }
        .form-control:focus, .form-select:focus { border-color: #5c4df0; box-shadow: 0 0 0 0.25rem rgba(92, 77, 240, 0.25); }
    </style>
</head>
<body>

    <aside id="sidebar">
        <div class="sidebar-brand d-flex align-items-center">
            <span class="sidebar-brand-icon"><i class="bi bi-buildings"></i></span>
            <div>
                <div class="mb-0 fs-6">NEXUS <span class="badge bg-secondary ms-1" style="font-size: 0.6rem;">ERP</span></div>
            </div>
        </div>
        <div class="sidebar-heading mt-2">Core Entities</div>
        <a href="#" class="sidebar-nav-item"><i class="bi bi-person-badge me-2"></i> Staff Directory</a>
        <a href="#" class="sidebar-nav-item"><i class="bi bi-people me-2"></i> Clients</a>
        <a href="#" class="sidebar-nav-item"><i class="bi bi-broadcast-pin me-2"></i> MNO Partners</a>
        <div class="sidebar-heading mt-2">Resources</div>
        <a href="#" class="sidebar-nav-item active"><i class="bi bi-folder2-open me-2"></i> Document Vault</a>
    </aside>

    <main id="main-content">
        <header class="topbar d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center">
                <span class="fw-bold" style="font-size: 0.95rem;">Document Vault</span>
            </div>
        </header>

        <div class="container-fluid p-4">
            
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h4 class="fw-bold mb-1">Corporate Documents</h4>
                    <p class="text-secondary mb-0" style="font-size: 0.9rem;">Manage compliance files, MNO agreements, and client contracts.</p>
                </div>
                <button class="btn text-white fw-bold d-flex align-items-center" style="background-color: #5c4df0; border-radius: 8px;" id="btnOpenUploadModal">
                    <i class="bi bi-cloud-upload me-2"></i> Upload Document
                </button>
            </div>

            <div class="content-card">
                <div class="table-responsive">
                    <table class="table table-custom table-hover mb-0">
                        <thead>
                            <tr>
                                <th>File Name</th>
                                <th>Related Entity</th>
                                <th>Type</th>
                                <th>Size</th>
                                <th>Uploaded</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <i class="bi bi-file-earmark-pdf text-danger me-2"></i>
                                    <span class="fw-bold text-dark">MTN_SIP_Trunk_SLA_2026.pdf</span>
                                </td>
                                <td><span class="badge bg-dark bg-opacity-10 text-dark">MNO: MTN</span></td>
                                <td>Contract</td>
                                <td class="text-secondary">2.4 MB</td>
                                <td class="text-secondary">Jun 15, 2026</td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-light text-primary me-1"><i class="bi bi-download"></i></button>
                                    <button class="btn btn-sm btn-light text-secondary me-1 btn-edit-doc" data-id="1" data-filename="MTN_SIP_Trunk_SLA_2026.pdf" data-entity="mno_mtn" data-type="contract"><i class="bi bi-pencil"></i></button>
                                    <button class="btn btn-sm btn-light text-danger"><i class="bi bi-trash"></i></button>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <i class="bi bi-file-earmark-word text-primary me-2"></i>
                                    <span class="fw-bold text-dark">Telecel_Interconnect_Draft.docx</span>
                                </td>
                                <td><span class="badge bg-dark bg-opacity-10 text-dark">MNO: Telecel</span></td>
                                <td>Draft</td>
                                <td class="text-secondary">850 KB</td>
                                <td class="text-secondary">Jun 12, 2026</td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-light text-primary me-1"><i class="bi bi-download"></i></button>
                                    <button class="btn btn-sm btn-light text-secondary me-1 btn-edit-doc" data-id="2" data-filename="Telecel_Interconnect_Draft.docx" data-entity="mno_telecel" data-type="draft"><i class="bi bi-pencil"></i></button>
                                    <button class="btn btn-sm btn-light text-danger"><i class="bi bi-trash"></i></button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <div class="modal fade" id="documentModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold" id="documentModalTitle">Upload New Document</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <form id="documentForm" enctype="multipart/form-data">
                    <div class="modal-body p-4">
                        <input type="hidden" id="docId" name="id">
                        <input type="hidden" id="docMethod" name="_method" value="POST">
                        
                        <div class="mb-3">
                            <label class="form-label text-secondary fw-semibold" style="font-size: 0.85rem;">Select File</label>
                            <input class="form-control" type="file" id="docFile" name="file">
                            <div class="form-text" id="fileHelpText">Max size: 10MB. Allowed: PDF, DOCX, PNG, JPG.</div>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-6">
                                <label class="form-label text-secondary fw-semibold" style="font-size: 0.85rem;">Document Type</label>
                                <select class="form-select" id="docType" name="type" required>
                                    <option value="" selected disabled>Select...</option>
                                    <option value="contract">SLA / Contract</option>
                                    <option value="draft">Draft Proposal</option>
                                    <option value="identity">KYC / Identity</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label text-secondary fw-semibold" style="font-size: 0.85rem;">Related Entity</label>
                                <select class="form-select" id="docEntity" name="entity_id">
                                    <option value="">General (None)</option>
                                    <optgroup label="Mobile Network Operators">
                                        <option value="mno_mtn">MTN</option>
                                        <option value="mno_telecel">Telecel</option>
                                        <option value="mno_at">AT</option>
                                    </optgroup>
                                    <optgroup label="Clients">
                                        <option value="client_1">Click Tech Corp</option>
                                    </optgroup>
                                </select>
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label text-secondary fw-semibold" style="font-size: 0.85rem;">Description</label>
                            <textarea class="form-control" id="docNotes" name="notes" rows="2" placeholder="Optional notes..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer bg-light">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn text-white fw-bold px-4" style="background-color: #5c4df0;" id="btnSubmitDoc">
                            Upload File
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Setup CSRF token for all AJAX requests 
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            const docModal = new bootstrap.Modal(document.getElementById('documentModal'));
            const $form = $('#documentForm');

            // --- OPEN MODAL FOR CREATE ---
            $('#btnOpenUploadModal').on('click', function() {
                $form[0].reset(); // Clear previous data
                $('#docId').val('');
                $('#docMethod').val('POST');
                
                $('#documentModalTitle').text('Upload New Document');
                $('#btnSubmitDoc').html('<i class="bi bi-cloud-upload me-2"></i>Upload File');
                $('#docFile').prop('required', true); // File is mandatory for upload
                $('#fileHelpText').text('Max size: 10MB. Allowed: PDF, DOCX, PNG, JPG.');
                
                docModal.show();
            });

            // --- OPEN MODAL FOR EDIT ---
            $('.btn-edit-doc').on('click', function() {
                const id = $(this).data('id');
                const filename = $(this).data('filename');
                const entity = $(this).data('entity');
                const type = $(this).data('type');

                $form[0].reset();
                $('#docId').val(id);
                $('#docMethod').val('PUT'); // Set to PUT for backend routing
                
                // Populate existing data
                $('#docType').val(type);
                $('#docEntity').val(entity);
                
                $('#documentModalTitle').text('Edit Document Info');
                $('#btnSubmitDoc').html('<i class="bi bi-save me-2"></i>Save Changes');
                $('#docFile').prop('required', false); // File is optional when editing
                $('#fileHelpText').text('Leave file input blank to keep existing file: ' + filename);
                
                docModal.show();
            });

            // --- HANDLE FORM SUBMISSION VIA AJAX ---
            $form.on('submit', function(e) {
                e.preventDefault();
                const $btn = $('#btnSubmitDoc');
                const originalText = $btn.html();
                
                $btn.html('<span class="spinner-border spinner-border-sm me-2"></span> Processing...');
                $btn.prop('disabled', true);

                // Use FormData to handle the multipart/form-data payload natively
                let formData = new FormData(this);
                let isEdit = $('#docId').val() !== '';
                let ajaxUrl = isEdit ? '/api/documents/' + $('#docId').val() : '/api/documents';

                // Simulating the AJAX call
                setTimeout(() => {
                    console.log('Submitted Payload:', Object.fromEntries(formData));
                    
                    $btn.html(originalText);
                    $btn.prop('disabled', false);
                    docModal.hide();
                    
                    // Here you would normally trigger a toast notification or reload the data table
                    alert(isEdit ? 'Document metadata updated successfully!' : 'File uploaded successfully!');
                }, 1200);

                /* // Actual AJAX Call Structure:
                $.ajax({
                    url: ajaxUrl,
                    type: 'POST', // Always POST for FormData, pass _method=PUT in data for edits
                    data: formData,
                    processData: false, // Prevent jQuery from processing the data
                    contentType: false, // Prevent jQuery from setting contentType
                    success: function(response) {
                        docModal.hide();
                        // Refresh DataTables or UI
                    },
                    error: function(xhr) {
                        $btn.html(originalText).prop('disabled', false);
                        // Handle validation errors
                    }
                });
                */
            });
        });
    </script>
</body>
</html>