<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Pustaka Dokumen | SINARAN RSU ANANDA PURWOKERTO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --brand-primary:#1a56db; --brand-primary-light:#e8efff; --brand-primary-hover:#1246c0;
            --brand-success:#0e9f6e; --brand-danger:#e02424;
            --bg-page:#f4f6fb; --bg-card:#ffffff;
            --text-primary:#111827; --text-secondary:#6b7280; --text-muted:#9ca3af;
            --border-color:#e5e7eb; --border-radius:12px; --border-radius-sm:8px;
            --shadow-sm:0 1px 3px rgba(0,0,0,0.06),0 1px 2px rgba(0,0,0,0.04);
            --shadow-md:0 4px 12px rgba(0,0,0,0.08); --transition:all 0.2s ease;
        }
        *{box-sizing:border-box;}
        body{font-family:'Plus Jakarta Sans',sans-serif;background-color:var(--bg-page);color:var(--text-primary);font-size:14px;}
        
        /* ========================================================
           CSS RESPONSIVE & FIT SCREEN (ANTI JEBOL & FIX SIDEBAR HP)
           ======================================================== */
        body, html {
            overflow-x: hidden !important;
            width: 100%;
            max-width: 100vw;
        }

        @media (max-width: 991.98px) {
            #layoutSidenav_content {
                padding-left: 0 !important;
                margin-left: 0 !important;
                width: 100% !important;
                max-width: 100vw !important;
            }
            .page-wrapper {
                padding: 1rem !important;
            }
        }

        #layoutSidenav_content {
            width: 100%;
            max-width: 100vw;
            overflow-x: hidden !important;
        }

        .table-responsive {
            width: 100% !important;
            max-width: 100% !important;
            overflow-x: auto !important;
            -webkit-overflow-scrolling: touch;
        }
        /* ======================================================== */

        .page-wrapper{padding:1.5rem;max-width:1100px;margin:0 auto;}
        .page-header{margin-bottom:1.5rem;}
        .page-header h1{font-size:22px;font-weight:700;color:var(--text-primary);margin-bottom:4px;}
        .page-header p{font-size:13px;color:var(--text-secondary);margin:0;}
        .doc-card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:var(--border-radius);box-shadow:var(--shadow-sm);margin-bottom:1.25rem;overflow:hidden;}
        .doc-card-header{padding:.875rem 1.25rem;border-bottom:1px solid var(--border-color);display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--text-primary);background:#fafbfc;}
        .doc-card-header i{color:var(--brand-primary);font-size:16px;}
        .doc-card-body{padding:1.25rem;}
        .year-tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:1.25rem;}
        .year-btn{padding:7px 20px;border-radius:20px;font-size:13px;font-weight:600;cursor:pointer;border:1.5px solid var(--border-color);background:var(--bg-page);color:var(--text-secondary);transition:var(--transition);letter-spacing:.3px;}
        .year-btn:hover{border-color:var(--brand-primary);color:var(--brand-primary);background:var(--brand-primary-light);}
        .year-btn.active{background:var(--brand-primary);border-color:var(--brand-primary);color:#fff;box-shadow:0 2px 8px rgba(26,86,219,.3);}
        
        /* Menggunakan repeat auto-fill agar Grid POKJA fleksibel mengikuti lebar device */
        .pokja-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px;}
        .pokja-item{border:1.5px solid var(--border-color);border-radius:var(--border-radius-sm);padding:14px 10px;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;background:var(--bg-card);transition:var(--transition);}
        .pokja-item:hover{border-color:var(--brand-primary);background:var(--brand-primary-light);transform:translateY(-2px);box-shadow:var(--shadow-md);}
        .pokja-icon{width:44px;height:44px;border-radius:10px;background:var(--brand-primary-light);display:flex;align-items:center;justify-content:center;font-size:20px;color:var(--brand-primary);transition:var(--transition);}
        .pokja-item:hover .pokja-icon{background:var(--brand-primary);color:#fff;}
        .pokja-num{font-size:11px;font-weight:700;color:var(--brand-primary);letter-spacing:.5px;text-transform:uppercase;}
        .pokja-name{font-size:11px;font-weight:500;color:var(--text-primary);line-height:1.35;}
        .pokja-badge{font-size:10px;font-weight:600;padding:2px 8px;border-radius:10px;background:#e5e7eb;color:var(--text-secondary);}
        .pokja-badge.has-files{background:#d1fae5;color:#065f46;}
        .bc-nav{display:flex;align-items:center;gap:6px;font-size:13px;flex-wrap:wrap;margin-bottom:1rem;}
        .bc-nav span{color:var(--text-secondary);}
        .bc-nav i{font-size:10px;color:var(--text-muted);}
        .bc-nav .bc-current{font-weight:600;color:var(--brand-primary);}
        .btn-back{display:inline-flex;align-items:center;gap:6px;padding:6px 14px;border-radius:20px;font-size:13px;font-weight:500;border:1.5px solid var(--border-color);background:var(--bg-card);color:var(--text-secondary);cursor:pointer;transition:var(--transition);margin-bottom:1rem;}
        .btn-back:hover{color:var(--brand-primary);border-color:var(--brand-primary);}
        .upload-area{border:2px dashed #93c5fd;border-radius:var(--border-radius-sm);padding:32px 20px;text-align:center;cursor:pointer;background:#eff6ff;transition:var(--transition);}
        .upload-area:hover,.upload-area.drag-over{background:#dbeafe;border-color:var(--brand-primary);}
        .upload-icon{font-size:36px;color:var(--brand-primary);margin-bottom:10px;display:block;}
        .upload-area:hover .upload-icon { color: var(--brand-primary); }
        .upload-title{font-size:14px;font-weight:600;color:var(--brand-primary);margin-bottom:4px;}
        .upload-sub{font-size:12px;color:#60a5fa;}
        .file-selected{font-size:13px;font-weight:600;color:var(--brand-success);margin-top:8px;}
        .file-list{display:flex;flex-direction:column;gap:8px;}
        
        /* Modifikasi flex layout baris file agar membungkus dengan rapi di viewport kecil */
        .file-row{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid var(--border-color);border-radius:var(--border-radius-sm);background:#fff;transition:var(--transition);flex-wrap:wrap;}
        .file-row:hover{border-color:#93c5fd;background:#f8faff;}
        .file-thumb{width:36px;height:36px;border-radius:8px;background:#fee2e2;display:flex;align-items:center;justify-content:center;font-size:16px;color:#dc2626;flex-shrink:0;}
        .file-info{flex:1;min-width:0;}
        .file-name{font-size:13px;font-weight:500;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
        .file-meta{font-size:11px;color:var(--text-muted);margin-top:1px;}
        .file-actions{display:flex;gap:4px;flex-shrink:0;}
        .action-btn{width:30px;height:30px;border-radius:6px;border:1px solid var(--border-color);background:#fff;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;font-size:13px;color:var(--text-secondary);transition:var(--transition);text-decoration:none;}
        .action-btn:hover{transform:translateY(-1px);}
        .action-btn.view:hover{color:var(--brand-primary);border-color:#93c5fd;background:#eff6ff;}
        .action-btn.download:hover{color:var(--brand-success);border-color:#6ee7b7;background:#ecfdf5;}
        .action-btn.delete:hover{color:var(--brand-danger);border-color:#fca5a5;background:#fef2f2;}
        .empty-state{text-align:center;padding:2.5rem 1rem;color:var(--text-muted);}
        .empty-state i{font-size:40px;display:block;margin-bottom:12px;opacity:.4;}
        .empty-state p{font-size:13px;margin:0;}
        .loading-state{text-align:center;padding:2rem;}
        .spinner{width:32px;height:32px;border:3px solid var(--border-color);border-top-color:var(--brand-primary);border-radius:50%;animation:spin .7s linear infinite;margin:0 auto 10px;}
        @keyframes spin{to{transform:rotate(360deg)}}
        .upload-progress{display:none;margin-top:12px;}
        .progress-bar-wrap{height:6px;background:var(--border-color);border-radius:10px;overflow:hidden;}
        .progress-bar-fill{height:100%;background:var(--brand-primary);border-radius:10px;width:0%;transition:width .3s ease;}
        .progress-text{font-size:12px;color:var(--text-secondary);text-align:center;margin-top:6px;}
        
        .toast-container{position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;pointer-events:none;}
         Penting: Tambahkan max-width kontainer toast agar pas di device kecil 
        .toast-item{padding:12px 18px;border-radius:10px;font-size:13px;font-weight:500;color:#fff;display:flex;align-items:center;gap:8px;min-width:240px;max-width:calc(100vw - 40px);box-shadow:0 4px 16px rgba(0,0,0,.15);pointer-events:all;opacity:0;transform:translateX(30px);transition:all .35s cubic-bezier(.16,1,.3,1);}
        .toast-item.show{opacity:1;transform:translateX(0);}
        .toast-item.success{background:#059669;}
        .toast-item.error{background:#dc2626;}
        .toast-item.info{background:var(--brand-primary);}
        .btn-upload{display:inline-flex;align-items:center;gap:8px;padding:8px 20px;font-size:13px;font-weight:600;border-radius:8px;background:var(--brand-primary);color:#fff;border:none;cursor:pointer;transition:var(--transition);}
        .btn-upload:hover{background:var(--brand-primary-hover);}
        .btn-upload:disabled{opacity:.6;cursor:not-allowed;}
        
        @media(max-width:576px){
            .page-wrapper{padding:1rem;}
            .pokja-grid{grid-template-columns:repeat(auto-fill,minmax(100px,1fr)) !important;gap:8px !important;}
            .pokja-item{padding:10px 6px !important;}
            .year-btn{padding:6px 14px !important;font-size:12px !important;}
            .doc-card-body{padding:1rem !important;}
            .file-meta{display:none;}
            .upload-area{padding:20px 12px !important;}
            .file-row { flex-direction: column; align-items: flex-start; }
            .file-actions { width: 100%; justify-content: flex-end; margin-top: 5px; }
        }
        @media(max-width:400px){.pokja-grid{grid-template-columns:repeat(3,1fr) !important;}}
    </style>
</head>
<body>
<div id="layoutSidenav_content">
<main>
<div class="page-wrapper">

    <div class="page-header">
        <h1><i class="fas fa-book-open me-2" style="color:var(--brand-primary)"></i>Pustaka Dokumen</h1>
        <p>Manajemen dokumen akreditasi rumah sakit berdasarkan tahun dan kelompok kerja (pokja)</p>
    </div>

    <div id="viewMain">
        <div class="doc-card">
            <div class="doc-card-header">
                <i class="fas fa-calendar-alt"></i> Pilih Tahun Dokumen
            </div>
            <div class="doc-card-body">
                <div class="year-tabs" id="yearTabs"></div>
                <div id="pokjaGrid" class="pokja-grid"></div>
            </div>
        </div>
    </div>

    <div id="viewDetail" style="display:none;">
        <button class="btn-back" onclick="backToMain()">
            <i class="fas fa-arrow-left"></i> Kembali ke daftar pokja
        </button>
        <div class="bc-nav" id="bcNav"></div>

        <?php
            $akses        = $this->session->userdata("nm_user");
            $akses_upload = [
                'dr.Adam Malik S',
                'Prilly Alya Fauzziah, dr.',
                'Try Uswatun Khasanah',
                'dr. Dhian Shinto Hapsari',
                'Finaldy Agung Pranadita, dr.',
                'ADNAN ADITYA M',
                'HIZBULLOH PUTRA ADI',
                'Dhiesty Kusuma Purbasari,dr',
                'SABILLA DWI SETYA PURWANTI',
                'NANI HIDAYATI',
                'CITRA ADHITYARINI',
                'DANI ANJAR SAPUTRI',
                'PANTES WIDADI',
                'DWI HANDOYO',
                'NILNA ULIYATAL QONITAH',
                'NOVIAH INDRASARI',
                'ADE RIZKI YANUAR',
                'NURIASIH',
                'AHMAD KAHFI',
                'ANIEK TRISNAWATI',
                'SITI SOLIKHATUN',
                'EKAWATI',
                'VEBRI FUAD LATIFIGANA',
                'DITO KUSUMO DAMAR P',
                'DWI ARYANI',
                'UCI AFRILIA',
                'PUTRI PERMATA SARI RACHMAT',
                'MAULANA ACHMAD MIFTAHUDIN',
                'RAGIL IRAWATI',
                'dr. Tasya Sri Cahyani Susilawati',
                'NURVITA PRANASARI, dr.',
                'TRIANA INDRAJATI',
                'MILA WARDANI',
                'RONI NURFAUZI',
                'NOVARIZQI NUR AZIZAH',
                'AKMAL FAISAL UTOMO',
                'WAHYU JANWARI',
                'TRIASARI ANGGARANINGRUM',
                'IGA NURCAHYANI',
                'dr. Muhammad Irfan Amrizal',
                'SITI MUKAROMATUNNIMAH',
                'RATIH DWI YUNITA',
                'LISTY DIAN LESTARI KUSWANTO PUTRI'
            ];

            $akses_delete = [
                'dr.Adam Malik S',
                'Prilly Alya Fauzziah, dr.',
                'Try Uswatun Khasanah',
                'dr. Dhian Shinto Hapsari',
                'Finaldy Agung Pranadita, dr.',
                'ADNAN ADITYA M',
                'HIZBULLOH PUTRA ADI',
                'Dhiesty Kusuma Purbasari,dr',
                'SABILLA DWI SETYA PURWANTI',
                'NANI HIDAYATI',
                'CITRA ADHITYARINI',
                'DANI ANJAR SAPUTRI',
                'PANTES WIDADI',
                'DWI HANDOYO',
                'NILNA ULIYATAL QONITAH',
                'NOVIAH INDRASARI',
                'ADE RIZKI YANUAR',
                'NURIASIH',
                'AHMAD KAHFI',
                'ANIEK TRISNAWATI',
                'SITI SOLIKHATUN',
                'EKAWATI',
                'VEBRI FUAD LATIFIGANA',
                'DITO KUSUMO DAMAR P',
                'DWI ARYANI',
                'UCI AFRILIA',
                'PUTRI PERMATA SARI RACHMAT',
                'MAULANA ACHMAD MIFTAHUDIN',
                'RAGIL IRAWATI',
                'dr. Tasya Sri Cahyani Susilawati',
                'NURVITA PRANASARI, dr.',
                'TRIANA INDRAJATI',
                'MILA WARDANI',
                'RONI NURFAUZI',
                'NOVARIZQI NUR AZIZAH',
                'AKMAL FAISAL UTOMO',
                'WAHYU JANWARI',
                'TRIASARI ANGGARANINGRUM',
                'IGA NURCAHYANI',
                'dr. Muhammad Irfan Amrizal',
                'SITI MUKAROMATUNNIMAH',
                'RATIH DWI YUNITA',
                'LISTY DIAN LESTARI KUSWANTO PUTRI'
            ];
            $can_upload   = in_array($akses, $akses_upload);
            $can_delete   = in_array($akses, $akses_delete);
        ?>

        <?php if ($can_upload): ?>
        <div class="doc-card" id="uploadCard">
            <div class="doc-card-header">
                <i class="fas fa-cloud-upload-alt"></i> Unggah Dokumen Baru
            </div>
            <div class="doc-card-body">
                <form id="uploadForm" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="tahun" id="inputTahun">
                    <input type="hidden" name="pokja" id="inputPokja">
                    <div class="upload-area" id="uploadArea">
                        <i class="fas fa-file-pdf upload-icon"></i>
                        <div class="upload-title">Seret file PDF ke sini</div>
                        <div class="upload-sub">atau klik untuk memilih &middot; Maks. 2 MB per file</div>
                        <div class="file-selected" id="fileSelectedLabel" style="display:none;"></div>
                    </div>
                    <input type="file" name="file" id="fileInput" hidden accept=".pdf">
                    <div class="upload-progress" id="uploadProgress">
                        <div class="progress-bar-wrap"><div class="progress-bar-fill" id="progressFill"></div></div>
                        <div class="progress-text" id="progressText">Mengunggah...</div>
                    </div>
                    <div class="text-center mt-3">
                        <button type="submit" class="btn-upload" id="btnUpload" disabled>
                            <i class="fas fa-paper-plane"></i> Unggah Sekarang
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <div class="doc-card">
            <div class="doc-card-header">
                <i class="fas fa-folder-open"></i>
                <span id="folderTitle">Daftar Dokumen</span>
            </div>
            <div class="doc-card-body" id="fileListArea">
                <div class="loading-state"><div class="spinner"></div><div style="font-size:13px;color:var(--text-muted)">Memuat dokumen...</div></div>
            </div>
        </div>
    </div>

</div>
</main>

<div class="toast-container" id="toastContainer"></div>

<footer class="py-3 mt-4" style="border-top:1px solid var(--border-color);background:#fff;">
    <div class="container-fluid px-4">
        <div class="d-flex align-items-center justify-content-between small text-muted flex-wrap gap-2">
            <span>Copyright &copy; BY IT RSU ANANDA PURWOKERTO <?= date('Y') ?></span>
            <div><a href="#" class="text-muted text-decoration-none me-2">Privacy Policy</a> <a href="#" class="text-muted text-decoration-none">Terms &amp; Conditions</a></div>
        </div>
    </div>
</footer>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
    const BASE_URL   = '<?= base_url() ?>';
    const CAN_DELETE = <?= $can_delete ? 'true' : 'false' ?>;
    const YEARS  = [2022, 2024, 2025];
    const POKJAS = [
        {id:1, short:'PMKP',  name:'Peningkatan Mutu dan Keselamatan Pasien'},
        {id:2, short:'PPI',   name:'Pencegahan dan Pengendalian Infeksi'},
        {id:3, short:'KPS',   name:'Kualifikasi dan Pendidikan Staf'},
        {id:4, short:'MIRMK', name:'Manajemen Rekam Medis & Informasi Kesehatan '},
        {id:5, short:'MFK',   name:'Manajemen Fasilitas dan Keselamatan'},
        {id:6, short:'TKRS',  name:'Tata Kelola Rumah Sakit'},
        {id:7, short:'PKPO',  name:'Pelayanan Kefarmasian Penggunaan Obat'},
        {id:8, short:'PAB',   name:'Pelayanan Anestesi dan Bedah'},
        {id:9, short:'KE',    name:'Komunikasi dan Edukas'},
        {id:10,short:'PP',    name:'Pengkajian Pasien'},
        {id:11,short:'PAP',   name:'Pelayanan dan Asuhan Pasien'},
        {id:12,short:'HPK',   name:'Hak Pasien dan Keluarga'},
        {id:13,short:'AKP',   name:'Akses dan Kontinuitas Pelayanan'},
        {id:14,short:'SKP',   name:' Sasaran Keselamatan Pasien'},
        {id:15,short:'PROGNAS-PONEK',    name:'PONEK'},
        {id:16,short:'PROGNAS-HIV/AIDS', name:'HIV/AIDS'},
        {id:17,short:'PROGNAS-TB',       name:'TB'},
        {id:18,short:'PROGNAS-PKBRS',    name:'Pelayanan Keluarga Berencana Rumah Sakit'},
        {id:19,short:'PROGNAS-PPRA',     name:'Program Pengendalian Resistensi Antimikroba'},
        {id:20,short:'PROGNAS-STUNTING', name:'STUNTING & WASTING'},
    ];

    let activeYear=YEARS[YEARS.length-1], activePokja=null;

    /* ---- TOAST ---- */
    function toast(msg,type='success'){
        const icon=type==='success'?'fa-check-circle':type==='error'?'fa-exclamation-circle':'fa-info-circle';
        const el=$(`<div class="toast-item ${type}"><i class="fas ${icon}"></i> ${msg}</div>`);
        $('#toastContainer').append(el);
        requestAnimationFrame(()=>el.addClass('show'));
        setTimeout(()=>{el.removeClass('show');setTimeout(()=>el.remove(),400);},3500);
    }

    /* ---- YEAR TABS ---- */
    function renderYears(){
        const $c=$('#yearTabs').empty();
        YEARS.forEach(y=>{
            $c.append($(`<button class="year-btn${y===activeYear?' active':''}">${y}</button>`)
                .on('click',()=>{activeYear=y;renderYears();renderPokjaGrid();}));
        });
    }

    /* ---- POKJA GRID ---- */
    function renderPokjaGrid(){
        const $g=$('#pokjaGrid').html('<div style="text-align:center;padding:1.5rem;color:var(--text-muted);font-size:13px;grid-column:1/-1"><i class="fas fa-spinner fa-spin me-2"></i>Memuat info folder...</div>');
        $.ajax({
            url:BASE_URL+'dashboard/file_counts',
            type:'GET',data:{tahun:activeYear},dataType:'json',
            success:function(counts){
                $g.empty();
                POKJAS.forEach(p=>{
                    const cnt=(counts&&counts[p.id])?parseInt(counts[p.id]):0;
                    const badge=cnt>0?`<span class="pokja-badge has-files">${cnt} file</span>`:`<span class="pokja-badge">Kosong</span>`;
                    $g.append(`<div class="pokja-item" data-pokja="${p.id}">
                        <div class="pokja-icon"><i class="fas fa-folder"></i></div>
                        <div class="pokja-num">Pokja ${p.id}</div>
                        <div class="pokja-name">${p.short}</div>
                        ${badge}</div>`);
                });
            },
            error:function(){
                $g.empty();
                POKJAS.forEach(p=>{
                    $g.append(`<div class="pokja-item" data-pokja="${p.id}">
                        <div class="pokja-icon"><i class="fas fa-folder"></i></div>
                        <div class="pokja-num">Pokja ${p.id}</div>
                        <div class="pokja-name">${p.short}</div>
                        <span class="pokja-badge">—</span></div>`);
                });
            }
        });
    }

    $(document).ready(function() {
        $(document).on('click','.pokja-item',function(){
            activePokja=parseInt($(this).data('pokja'));
            openFolder();
        });
    });

    /* ---- OPEN FOLDER ---- */
    function openFolder(){
        const p=POKJAS.find(x=>x.id===activePokja);
        $('#viewMain').hide();
        $('#viewDetail').show();
        $('#bcNav').html(`<span>Tahun ${activeYear}</span><i class="fas fa-chevron-right"></i><span class="bc-current">Pokja ${activePokja} &mdash; ${p.short} &bull; ${p.name}</span>`);
        $('#folderTitle').text(`Pokja ${activePokja} \u00B7 ${p.short} \u00B7 ${activeYear}`);
        $('#inputTahun').val(activeYear);
        $('#inputPokja').val(activePokja);
        loadFiles();
    }

    window.backToMain=function(){
        activePokja=null;
        $('#viewDetail').hide();
        $('#viewMain').show();
        renderPokjaGrid();
    };

    /* ---- LOAD FILES ---- */
    function loadFiles(){
        $('#fileListArea').html('<div class="loading-state"><div class="spinner"></div><div style="font-size:13px;color:var(--text-muted)">Memuat dokumen...</div></div>');
        $.ajax({
            url:BASE_URL+'dashboard/file',
            type:'GET',data:{tahun:activeYear,pokja:activePokja},dataType:'json',
            success:function(files){
                if(!files||files.length===0){
                    $('#fileListArea').html('<div class="empty-state"><i class="fas fa-folder-open"></i><p>Belum ada dokumen di folder ini.<br><span style="font-size:12px;color:var(--text-muted)">Unggah PDF pertama Anda menggunakan form di atas.</span></p></div>');
                    return;
                }
                let html='<div class="file-list">';
                files.forEach(function(f){
                    const rawName = f.file_name || f.nama_file || '';
                    const fileName = rawName.split('/').pop().split('\\').pop() || rawName;

                    const delBtn=CAN_DELETE?`<button class="action-btn delete delete-file" data-file="${fileName}" title="Hapus"><i class="fas fa-trash-alt"></i></button>`:'';
                    html+=`<div class="file-row">
                        <div class="file-thumb"><i class="fas fa-file-pdf"></i></div>
                        <div class="file-info">
                            <div class="file-name" title="${fileName}">${fileName}</div>
                            <div class="file-meta">${f.file_size||''} ${f.upload_date?'&bull; '+f.upload_date:''}</div>
                        </div>
                        <div class="file-actions">
                            <a href="${f.file_path}" target="_blank" class="action-btn view" title="Lihat"><i class="fas fa-eye"></i></a>
                            <a href="${f.file_path}" class="action-btn download" title="Unduh" download><i class="fas fa-download"></i></a>
                            ${delBtn}
                        </div></div>`;
                });
                html+='</div>';
                $('#fileListArea').html(html);
            },
            error:function(){
                toast('Gagal memuat daftar file.','error');
                $('#fileListArea').html('<div class="empty-state"><i class="fas fa-exclamation-triangle"></i><p>Gagal memuat file.</p></div>');
            }
        });
    }

    /* ---- UPLOAD AREA ---- */
    const $area=$('#uploadArea'),$input=$('#fileInput'),$btn=$('#btnUpload'),$label=$('#fileSelectedLabel');
    if($area.length){
        $area.on('click',function(e){if(e.target.id!=='fileInput')$input.click();});
        $area.on('dragover',function(e){e.preventDefault();$(this).addClass('drag-over');});
        $area.on('dragleave',function(e){e.preventDefault();$(this).removeClass('drag-over');});
        $area.on('drop',function(e){
            e.preventDefault();$(this).removeClass('drag-over');
            const dt=e.originalEvent.dataTransfer;
            if(dt.files.length){$input[0].files=dt.files;handleFileSelect($input[0].files[0]);}
        });
        $input.on('change',function(){if(this.files.length)handleFileSelect(this.files[0]);});
    }
    function handleFileSelect(file){
        if(!file)return;
        if(file.type!=='application/pdf'){toast('Hanya file PDF yang diizinkan.','error');$input.val('');return;}
        if(file.size>2*1024*1024){toast('Ukuran file melebihi batas 2 MB.','error');$input.val('');return;}
        const sizeMB=(file.size/(1024*1024)).toFixed(2);
        $label.text('\u2713 '+file.name+' ('+sizeMB+' MB)').show();
        $btn.prop('disabled',false);
    }

    /* ---- UPLOAD SUBMIT ---- */
    $('#uploadForm').on('submit',function(e){
        e.preventDefault();
        if($input[0].files.length===0){toast('Silakan pilih file terlebih dahulu.','error');return;}
        const fd=new FormData(this);
        $btn.prop('disabled',true).html('<i class="fas fa-spinner fa-spin me-2"></i>Mengunggah...');
        $('#uploadProgress').show();$('#progressFill').css('width','0%');$('#progressText').text('Mempersiapkan...');
        $.ajax({
            url:BASE_URL+'dashboard/upload_pdf',type:'POST',data:fd,
            contentType:false,processData:false,dataType:'json',
            xhr:function(){
                const xhr=new XMLHttpRequest();
                xhr.upload.addEventListener('progress',function(ev){
                    if(ev.lengthComputable){const p=Math.round(ev.loaded/ev.total*100);$('#progressFill').css('width',p+'%');$('#progressText').text('Mengunggah... '+p+'%');}
                });
                return xhr;
            },
            success:function(res){
                if(res.status==='success'){
                    toast('File berhasil diunggah!','success');
                    loadFiles();$('#uploadForm')[0].reset();$label.hide();$btn.prop('disabled',true);
                }else{toast('Gagal: '+res.message,'error');}
            },
            error:function(){toast('Terjadi kesalahan saat mengunggah.','error');},
            complete:function(){
                $btn.prop('disabled',false).html('<i class="fas fa-paper-plane me-2"></i>Unggah Sekarang');
                setTimeout(()=>$('#uploadProgress').hide(),1000);
            }
        });
    });

    /* ---- DELETE ---- */
    $(document).on('click','.delete-file',function(){
        const fn=$(this).data('file');
        if(!confirm('Hapus file:\n'+fn+'\n\nTindakan ini tidak dapat dibatalkan.'))return;
        const $row=$(this).closest('.file-row');$row.css('opacity','0.4');
        $.ajax({
            url:BASE_URL+'dashboard/hapus1',type:'POST',
            data:{tahun:activeYear,pokja:activePokja,file:fn},dataType:'json',
            success:function(res){
                if(res.status==='success'){
                    toast('File berhasil dihapus.','success');
                    $row.slideUp(300,function(){$(this).remove();
                        if($('.file-row').length===0)$('#fileListArea').html('<div class="empty-state"><i class="fas fa-folder-open"></i><p>Belum ada dokumen di folder ini.</p></div>');
                    });
                }else{toast('Gagal menghapus: '+res.message,'error');$row.css('opacity','1');}
            },
            error:function(){toast('Terjadi kesalahan saat menghapus.','error');$row.css('opacity','1');}
        });
    });

    /* ---- INIT ---- */
    renderYears();
    renderPokjaGrid();
});
</script>
</body>
</html>