<?php
/* ══════════════════════════════════════════════════════
   arsip.php — Arsip Dokumen
   MA As-Syafi'iyah 02 Bekasi
   Integrasi: navbar.php (sidebar + topbar + loader)
══════════════════════════════════════════════════════ */
$page_title  = "Arsip Dokumen — MA As-Syafi'iyah 02";
$active_menu = 'arsip';
$loader_text = 'Memuat Arsip Dokumen';
include 'navbar.php';
include 'koneksi.php';
date_default_timezone_set('Asia/Jakarta');

// ── Handle Upload ──
$success = ''; $error = '';
if(isset($_POST['upload'])){
    $judul      = trim(mysqli_real_escape_string($conn, $_POST['judul']      ?? ''));
    $kategori   = trim(mysqli_real_escape_string($conn, $_POST['kategori']   ?? ''));
    $keterangan = trim(mysqli_real_escape_string($conn, $_POST['keterangan'] ?? ''));
    $tanggal    = $_POST['tanggal'] ?? date('Y-m-d');

    if(empty($judul) || empty($kategori)){
        $error = 'Judul dan kategori wajib diisi!';
    } else {
        $file_path = '';
        if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
            $upload_dir = 'uploads/arsip/';
            if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            $ext      = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
            $filename = time().'_'.uniqid().'.'.$ext;
            $target   = $upload_dir.$filename;
            if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) $file_path = $target;
        }
        $q = "INSERT INTO arsip_surat (judul,kategori,keterangan,file_path,tanggal,uploaded_by,created_at)
              VALUES ('$judul','$kategori','$keterangan','$file_path','$tanggal','{$_SESSION['user_id']}',NOW())";
        if(mysqli_query($conn, $q)) $success = "Dokumen <strong>$judul</strong> berhasil diarsipkan!";
        else $error = 'Gagal menyimpan: '.mysqli_error($conn);
    }
}

// ── Handle Delete ──
if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);
    $r  = mysqli_query($conn, "SELECT file_path FROM arsip_surat WHERE id=$id LIMIT 1");
    if($r && $row = mysqli_fetch_array($r)){
        if(!empty($row['file_path']) && file_exists($row['file_path'])) unlink($row['file_path']);
        mysqli_query($conn, "DELETE FROM arsip_surat WHERE id=$id");
        $success = "Dokumen berhasil dihapus!";
    }
}

// ── Filter ──
$search = trim(mysqli_real_escape_string($conn, $_GET['q']       ?? ''));
$kat    = $_GET['kategori'] ?? '';
$tahun  = $_GET['tahun']    ?? '';

$where = "1=1";
if($search) $where .= " AND (judul LIKE '%$search%' OR keterangan LIKE '%$search%')";
if($kat)    $where .= " AND kategori='".mysqli_real_escape_string($conn,$kat)."'";
if($tahun)  $where .= " AND YEAR(tanggal)='$tahun'";

// ── Stats ──
$total    = mysqli_fetch_array(mysqli_query($conn,"SELECT COUNT(*) t FROM arsip_surat WHERE $where"))['t'];
$kat_q    = mysqli_query($conn,"SELECT kategori,COUNT(*) c FROM arsip_surat GROUP BY kategori");
$kat_stats = [];
while($r = mysqli_fetch_array($kat_q)) $kat_stats[$r['kategori']] = $r['c'];

// ── Data ──
$arsip = mysqli_query($conn,"SELECT a.*,u.nama as uploader FROM arsip_surat a
         LEFT JOIN users u ON a.uploaded_by=u.id
         WHERE $where ORDER BY tanggal DESC,created_at DESC LIMIT 50");
?>

<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;900&family=Source+Sans+3:wght@300;400;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
/* ════════════════════════════════════════════════════════
   TOKEN LOKAL — prefix ar- (isolasi dari navbar)
   Navbar sidebar: 272px (≥1025px) | 240px (769–1024px) | 0px (≤768px)
   Topbar mobile : 60px
════════════════════════════════════════════════════════ */
:root{
    --ar-ink:     #1C1917; --ar-ink2:#44403C; --ar-ink3:#78716C;
    --ar-parch:   #FAF7F2; --ar-cream:#F5F0E8;
    --ar-cd:      #EDE7D9; --ar-cdd: #DDD5C5;
    --ar-gold:    #B45309; --ar-gold-l:#D97706; --ar-gold-xl:#F59E0B;
    --ar-gold-p:  #FEF3C7;
    --ar-forest:  #166534; --ar-forest-p:#DCFCE7;
    --ar-ruby:    #9F1239; --ar-ruby-p:#FFE4E6;
    --ar-sapp:    #1E3A5F; --ar-sapp-p:#DBEAFE;
    --ar-coral:   #C2410C; --ar-coral-p:#FFEDD5;
    --ar-sh-sm:   0 1px 3px rgba(0,0,0,.08);
    --ar-sh-md:   0 4px 16px rgba(0,0,0,.10);
    --ar-sh-lg:   0 12px 40px rgba(0,0,0,.14);
}

/* ── Override background .main ── */
.main{
    background: var(--ar-parch) !important;
    color: var(--ar-ink);
    overflow-x: hidden;
}
.main::after{
    content:''; position:fixed; inset:0; z-index:0; pointer-events:none;
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='400' height='400' filter='url(%23n)' opacity='0.025'/%3E%3C/svg%3E");
}
.main .wrap{ position:relative; z-index:1; font-family:'Source Sans 3',sans-serif; }

@keyframes arFadeUp{ from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }
@keyframes arSlideD{ from{opacity:0;transform:translateY(-10px)} to{opacity:1;transform:translateY(0)} }

/* ══════════════════════════════════════════
   TOPBAR HALAMAN
══════════════════════════════════════════ */
.ar-topbar{
    display:flex; align-items:center; justify-content:space-between;
    gap:1rem; padding:1.25rem 0; margin-bottom:1.5rem;
    border-bottom:1px solid var(--ar-cdd);
    flex-wrap:wrap;
}
.ar-topbar-info{ flex:1; min-width:0; }
.ar-topbar-title{
    font-family:'Playfair Display',serif;
    font-size:1.35rem; font-weight:700; color:var(--ar-ink);
}
.ar-topbar-sub{ font-size:.72rem; color:var(--ar-ink3); margin-top:2px; }
.ar-topbar-btns{ display:flex; align-items:center; gap:.625rem; flex-shrink:0; }

.ar-btn-back{
    display:flex; align-items:center; gap:.4rem;
    padding:.5rem 1.125rem;
    background:#fff; color:var(--ar-ink2);
    border:1.5px solid var(--ar-cdd); border-radius:50px;
    font-size:.78rem; font-weight:700;
    font-family:'Source Sans 3',sans-serif;
    text-decoration:none; cursor:pointer; transition:all .22s;
    white-space:nowrap;
}
.ar-btn-back:hover{
    background:var(--ar-cream); border-color:var(--ar-gold);
    color:var(--ar-gold); transform:translateY(-1px);
    box-shadow:0 4px 12px rgba(180,83,9,.15);
}
.ar-btn-upload{
    display:flex; align-items:center; gap:.4rem;
    padding:.5rem 1.25rem;
    background:var(--ar-ink); color:#fff;
    border:none; border-radius:50px;
    font-size:.78rem; font-weight:700;
    font-family:'Source Sans 3',sans-serif;
    cursor:pointer; transition:all .22s;
    white-space:nowrap;
}
.ar-btn-upload:hover{ background:#292524; transform:translateY(-1px); }

/* ══════════════════════════════════════════
   ALERTS
══════════════════════════════════════════ */
.ar-alert{
    display:flex; align-items:center; gap:.75rem;
    padding:1rem 1.25rem; border-radius:14px;
    margin-bottom:1.5rem; font-size:.875rem; font-weight:700;
    animation:arSlideD .4s ease-out; border-left:4px solid;
}
.ar-aok { background:#F0FDF4; color:#166534; border-color:#4ADE80; }
.ar-aerr{ background:#FEF2F2; color:#991B1B; border-color:#FCA5A5; }
.ar-alert-ico{ font-size:1.25rem; flex-shrink:0; }
.ar-alert-cls{ cursor:pointer; background:none; border:none; font-size:1.1rem; color:inherit; margin-left:auto; opacity:.6; font-weight:900; }
.ar-alert-cls:hover{ opacity:1; }

/* ══════════════════════════════════════════
   FILTER
══════════════════════════════════════════ */
.ar-filter{
    background:var(--ar-cream); border-radius:18px;
    border:1px solid var(--ar-cdd); padding:1.5rem;
    margin-bottom:1.75rem; box-shadow:var(--ar-sh-sm);
    animation:arFadeUp .4s ease-out;
}
.ar-filter-title{
    font-family:'Playfair Display',serif; font-size:1rem; font-weight:700;
    color:var(--ar-ink); margin-bottom:1.125rem;
    display:flex; align-items:center; gap:.5rem;
}
.ar-filter-grid{
    display:grid;
    grid-template-columns:2fr 1fr 1fr auto;
    gap:1rem; align-items:end;
}
.ar-fg{ display:flex; flex-direction:column; gap:.4rem; }
.ar-flbl{ font-size:.72rem; font-weight:700; color:var(--ar-ink2); text-transform:uppercase; letter-spacing:.06em; }
.ar-finp, .ar-fsel{
    padding:.7rem .9rem; background:#fff;
    border:1px solid var(--ar-cdd); border-radius:10px;
    font-family:'Source Sans 3',sans-serif; font-size:.875rem; font-weight:600;
    color:var(--ar-ink); transition:all .2s; width:100%;
}
.ar-finp:focus, .ar-fsel:focus{ border-color:var(--ar-gold); outline:none; box-shadow:0 0 0 3px rgba(180,83,9,.1); }
.ar-fsel{ cursor:pointer; }
.ar-btn-filter{
    padding:.72rem 1.5rem; background:var(--ar-gold); color:#fff;
    border:none; border-radius:10px; font-size:.875rem; font-weight:700;
    font-family:'Source Sans 3',sans-serif; cursor:pointer; transition:all .22s; width:100%;
}
.ar-btn-filter:hover{ background:var(--ar-gold-l); transform:translateY(-1px); box-shadow:0 4px 14px rgba(180,83,9,.3); }

/* ══════════════════════════════════════════
   STAT CARDS
══════════════════════════════════════════ */
.ar-stat-row{
    display:grid; grid-template-columns:repeat(4,1fr);
    gap:1.125rem; margin-bottom:1.75rem;
}
.ar-sc{
    background:var(--ar-cream); border-radius:18px;
    border:1px solid var(--ar-cdd); padding:1.25rem 1.375rem;
    position:relative; overflow:hidden;
    transition:all .22s; cursor:default;
    animation:arFadeUp .4s ease-out backwards;
    box-shadow:var(--ar-sh-sm);
}
.ar-sc:hover{ transform:translateY(-4px); box-shadow:var(--ar-sh-md); }
.ar-sc::before{ content:''; position:absolute; top:0; left:0; right:0; height:3px; border-radius:18px 18px 0 0; }
.ar-sc-all::before { background:linear-gradient(90deg,var(--ar-ink),var(--ar-ink2)); }
.ar-sc-doc::before { background:linear-gradient(90deg,var(--ar-sapp),#1D4ED8); }
.ar-sc-img::before { background:linear-gradient(90deg,var(--ar-coral),var(--ar-gold-xl)); }
.ar-sc-pdf::before { background:linear-gradient(90deg,var(--ar-ruby),#E11D48); }
.ar-sc:nth-child(1){ animation-delay:.04s } .ar-sc:nth-child(2){ animation-delay:.08s }
.ar-sc:nth-child(3){ animation-delay:.12s } .ar-sc:nth-child(4){ animation-delay:.16s }
.ar-sc-top{ display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:.625rem; }
.ar-sc-ico{
    width:42px; height:42px; border-radius:11px;
    display:flex; align-items:center; justify-content:center; font-size:1.375rem;
    transition:transform .25s cubic-bezier(.34,1.56,.64,1); flex-shrink:0;
}
.ar-sc:hover .ar-sc-ico{ transform:scale(1.15) rotate(-6deg); }
.ar-sc-all .ar-sc-ico { background:var(--ar-cd); }
.ar-sc-doc .ar-sc-ico { background:var(--ar-sapp-p); }
.ar-sc-img .ar-sc-ico { background:var(--ar-coral-p); }
.ar-sc-pdf .ar-sc-ico { background:var(--ar-ruby-p); }
.ar-sc-lbl{ font-size:.67rem; font-weight:700; text-transform:uppercase; letter-spacing:.07em; color:var(--ar-ink3); margin-bottom:.25rem; }
.ar-sc-n{ font-family:'Playfair Display',serif; font-size:2rem; font-weight:700; line-height:1; }
.ar-sc-all .ar-sc-n { color:var(--ar-ink); }
.ar-sc-doc .ar-sc-n { color:var(--ar-sapp); }
.ar-sc-img .ar-sc-n { color:var(--ar-coral); }
.ar-sc-pdf .ar-sc-n { color:var(--ar-ruby); }

/* ══════════════════════════════════════════
   ARCHIVE CARD GRID
══════════════════════════════════════════ */
.ar-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill, minmax(280px,1fr));
    gap:1.125rem;
}
.ar-card{
    background:var(--ar-cream); border-radius:18px;
    border:1px solid var(--ar-cdd); padding:1.375rem;
    transition:all .25s; position:relative; overflow:hidden;
    animation:arFadeUp .4s ease-out backwards;
    display:flex; flex-direction:column;
}
.ar-card:hover{ transform:translateY(-4px); box-shadow:var(--ar-sh-md); border-color:var(--ar-cd); }
/* left accent */
.ar-card::before{ content:''; position:absolute; left:0; top:0; bottom:0; width:4px; border-radius:4px 0 0 4px; }
.ar-c-surat::before  { background:var(--ar-sapp); }
.ar-c-sk::before     { background:var(--ar-coral); }
.ar-c-laporan::before{ background:var(--ar-forest); }
.ar-c-lainnya::before{ background:var(--ar-gold); }

.ar-card-head{ display:flex; gap:1rem; margin-bottom:1rem; }
.ar-card-ico{
    width:48px; height:48px; border-radius:12px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center; font-size:1.5rem;
}
.ar-c-surat  .ar-card-ico { background:var(--ar-sapp-p); }
.ar-c-sk     .ar-card-ico { background:var(--ar-coral-p); }
.ar-c-laporan.ar-card-ico  { background:var(--ar-forest-p); }
.ar-c-lainnya.ar-card-ico  { background:var(--ar-gold-p); }
.ar-c-laporan .ar-card-ico { background:var(--ar-forest-p); }
.ar-c-lainnya .ar-card-ico { background:var(--ar-gold-p); }

.ar-card-meta{ flex:1; min-width:0; }
.ar-card-date{ font-size:.68rem; color:var(--ar-ink3); margin-bottom:.3rem; }
.ar-card-kat{
    display:inline-block; padding:.15rem .65rem; border-radius:50px;
    font-size:.65rem; font-weight:700; text-transform:uppercase; letter-spacing:.05em;
}
.ar-c-surat   .ar-card-kat{ background:var(--ar-sapp-p);   color:var(--ar-sapp); }
.ar-c-sk      .ar-card-kat{ background:var(--ar-coral-p);  color:var(--ar-coral); }
.ar-c-laporan .ar-card-kat{ background:var(--ar-forest-p); color:var(--ar-forest); }
.ar-c-lainnya .ar-card-kat{ background:var(--ar-gold-p);   color:var(--ar-gold); }

.ar-card-title{
    font-size:.95rem; font-weight:700; color:var(--ar-ink); line-height:1.45;
    margin-bottom:.5rem;
    display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden;
}
.ar-card-desc{
    font-size:.78rem; color:var(--ar-ink3); line-height:1.55;
    display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden;
    margin-bottom:.875rem; flex:1;
}
.ar-card-foot{
    display:flex; align-items:center; justify-content:space-between;
    padding-top:.875rem; border-top:1px solid var(--ar-cdd);
    gap:.5rem; flex-wrap:wrap;
    margin-top:auto;
}
.ar-card-user{ font-size:.72rem; color:var(--ar-ink3); }
.ar-card-acts{ display:flex; gap:.5rem; }
.ar-abtn{
    display:inline-flex; align-items:center; gap:.3rem;
    padding:.3rem .75rem; border-radius:8px;
    font-size:.72rem; font-weight:700;
    cursor:pointer; border:1px solid transparent;
    transition:all .2s; text-decoration:none;
    font-family:'Source Sans 3',sans-serif;
}
.ar-abtn-view{ background:var(--ar-cd); color:var(--ar-ink); border-color:var(--ar-cdd); }
.ar-abtn-view:hover{ background:var(--ar-ink); color:#fff; }
.ar-abtn-del { background:var(--ar-ruby-p); color:var(--ar-ruby); border-color:rgba(159,18,57,.2); }
.ar-abtn-del:hover{ background:var(--ar-ruby); color:#fff; }

/* Empty state */
.ar-empty{
    grid-column:1/-1; text-align:center; padding:4rem 2rem; color:var(--ar-ink3);
}
.ar-empty-ico{ font-size:4rem; margin-bottom:1rem; }
.ar-empty-txt{ font-weight:700; font-size:1rem; }

/* ══════════════════════════════════════════
   MODAL UPLOAD
══════════════════════════════════════════ */
.ar-modal{
    display:none; position:fixed; inset:0; z-index:500;
    background:rgba(28,25,23,.65); backdrop-filter:blur(6px);
    align-items:center; justify-content:center; padding:1rem;
}
.ar-modal.open{ display:flex; }
.ar-mcon{
    background:var(--ar-cream); border-radius:24px;
    border:2px solid var(--ar-cdd); box-shadow:var(--ar-sh-lg);
    width:100%; max-width:540px; max-height:90vh; overflow-y:auto;
}
.ar-mhd{
    padding:1.5rem 1.75rem; background:var(--ar-ink);
    display:flex; align-items:center; justify-content:space-between;
    position:sticky; top:0; z-index:10;
}
.ar-mhd-title{ font-family:'Playfair Display',serif; font-size:1.1rem; font-weight:700; color:#fff; }
.ar-mbtn-close{
    background:rgba(255,255,255,.1); border:1px solid rgba(255,255,255,.2);
    border-radius:50%; width:36px; height:36px; font-size:1.1rem;
    cursor:pointer; display:flex; align-items:center; justify-content:center;
    transition:all .2s; color:#fff;
}
.ar-mbtn-close:hover{ background:var(--ar-ruby); border-color:var(--ar-ruby); }
.ar-mbdy{ padding:1.75rem; }
.ar-mfg{ display:flex; flex-direction:column; gap:.45rem; margin-bottom:1.125rem; }
.ar-mflbl{ font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.08em; color:var(--ar-ink); }
.ar-mfi{
    width:100%; padding:.8rem .9rem;
    background:#fff; border:1px solid var(--ar-cdd); border-radius:12px;
    font-family:'Source Sans 3',sans-serif; font-size:.9rem; font-weight:600;
    color:var(--ar-ink); transition:all .2s;
}
.ar-mfi:focus{ border-color:var(--ar-gold); outline:none; box-shadow:0 0 0 3px rgba(180,83,9,.1); }
.ar-mft{
    display:flex; gap:.75rem; justify-content:flex-end;
    padding:1.25rem 1.75rem; border-top:1px solid var(--ar-cdd);
    position:sticky; bottom:0; background:var(--ar-cream); z-index:10;
}
.ar-btn-cancel{
    padding:.75rem 1.5rem; background:var(--ar-cd); border:1px solid var(--ar-cdd);
    border-radius:12px; font-family:'Source Sans 3',sans-serif;
    font-size:.875rem; font-weight:700; cursor:pointer; color:var(--ar-ink); transition:all .2s;
}
.ar-btn-cancel:hover{ background:var(--ar-cdd); }
.ar-btn-save{
    padding:.75rem 1.75rem; background:var(--ar-ink); color:#fff;
    border:none; border-radius:12px; font-family:'Source Sans 3',sans-serif;
    font-size:.875rem; font-weight:700; cursor:pointer; transition:all .25s;
}
.ar-btn-save:hover{ background:#292524; transform:translateY(-1px); }

/* ══════════════════════════════════════════════════════════
   RESPONSIVE — SIDEBAR AWARE
   ≥1025px    → sidebar 272px fixed
   769–1024px → sidebar 240px fixed
   ≤768px     → sidebar hilang, topbar 60px di atas
══════════════════════════════════════════════════════════ */

/* ── Desktop sedang 1025–1199px (konten ~753–927px) ── */
@media(min-width:1025px) and (max-width:1199px){
    .ar-filter-grid  { grid-template-columns:1fr 1fr; }
    .ar-stat-row     { grid-template-columns:repeat(2,1fr); gap:.875rem; }
    .ar-grid         { grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); }
}

/* ── Tablet 769–1024px (sidebar 240px, konten ~529–784px) ── */
@media(min-width:769px) and (max-width:1024px){
    .ar-filter-grid  { grid-template-columns:1fr 1fr; gap:.875rem; }
    .ar-stat-row     { grid-template-columns:repeat(2,1fr); gap:.875rem; }
    .ar-grid         { grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:.875rem; }
    .ar-topbar-title { font-size:1.15rem; }
}

/* ── Mobile ≤768px (sidebar hilang, topbar 60px) ── */
@media(max-width:768px){
    /* Topbar */
    .ar-topbar       { padding:1rem 0; margin-bottom:1.25rem; }
    .ar-topbar-title { font-size:1.1rem; }
    .ar-topbar-btns  { gap:.5rem; }
    .ar-btn-back,
    .ar-btn-upload   { padding:.45rem .9rem; font-size:.74rem; }

    /* Filter: 2 kolom */
    .ar-filter       { padding:1.125rem; border-radius:14px; margin-bottom:1.25rem; }
    .ar-filter-grid  { grid-template-columns:1fr 1fr; gap:.75rem; }

    /* Stats: 2 kolom */
    .ar-stat-row     { grid-template-columns:1fr 1fr; gap:.75rem; margin-bottom:1.25rem; }
    .ar-sc           { padding:1rem 1.125rem; border-radius:14px; }
    .ar-sc-n         { font-size:1.75rem; }
    .ar-sc-ico       { width:38px; height:38px; font-size:1.2rem; }

    /* Grid: 1 kolom */
    .ar-grid         { grid-template-columns:1fr; gap:.875rem; }
    .ar-card         { padding:1.125rem; border-radius:14px; }
}

/* ── Mobile kecil ≤480px ── */
@media(max-width:480px){
    /* Topbar */
    .ar-topbar-btns  { width:100%; }
    .ar-btn-back,
    .ar-btn-upload   { flex:1; justify-content:center; }

    /* Filter: 1 kolom */
    .ar-filter-grid  { grid-template-columns:1fr; gap:.75rem; }

    /* Stats: 1 kolom */
    .ar-stat-row     { grid-template-columns:1fr; gap:.625rem; }
    .ar-sc{
        display:flex; align-items:center;
        padding:.875rem 1.125rem;
    }
    .ar-sc-top  { flex:1; margin-bottom:0; align-items:center; }
    .ar-sc-ico  { width:36px; height:36px; font-size:1.1rem; }
    .ar-sc-n    { font-size:1.625rem; }

    /* Modal */
    .ar-mbdy    { padding:1.25rem; }
    .ar-mft     { padding:1rem 1.25rem; }
}

@media print{
    .ar-topbar, .ar-filter, .ar-modal{ display:none!important; }
    .main{ background:#fff!important; }
}
</style>

<!-- ══ KONTEN UTAMA ══ -->
<div class="main">
<div class="wrap">

    <!-- TOPBAR -->
    <div class="ar-topbar">
        <div class="ar-topbar-info">
            <div class="ar-topbar-title">🗄️ Arsip Dokumen</div>
            <div class="ar-topbar-sub">Manajemen Dokumen &amp; File Surat</div>
        </div>
        <div class="ar-topbar-btns">
            <a href="surat.php" class="ar-btn-back">← Kembali</a>
            <button class="ar-btn-upload" onclick="arOpenModal()">📤 Upload Dokumen</button>
        </div>
    </div>

    <!-- ALERTS -->
    <?php if($success): ?>
    <div class="ar-alert ar-aok">
        <span class="ar-alert-ico">✅</span>
        <span><?= $success ?></span>
        <button class="ar-alert-cls" onclick="this.closest('.ar-alert').remove()">✕</button>
    </div>
    <?php endif; ?>
    <?php if($error): ?>
    <div class="ar-alert ar-aerr">
        <span class="ar-alert-ico">❌</span>
        <span><?= $error ?></span>
        <button class="ar-alert-cls" onclick="this.closest('.ar-alert').remove()">✕</button>
    </div>
    <?php endif; ?>

    <!-- FILTER -->
    <form method="GET" action="arsip.php">
    <div class="ar-filter">
        <div class="ar-filter-title">🔍 Cari &amp; Filter</div>
        <div class="ar-filter-grid">
            <div class="ar-fg">
                <label class="ar-flbl">Cari Dokumen</label>
                <input type="text" name="q" class="ar-finp"
                    placeholder="Judul atau keterangan..."
                    value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="ar-fg">
                <label class="ar-flbl">Kategori</label>
                <select name="kategori" class="ar-fsel">
                    <option value="">Semua</option>
                    <option value="Surat"   <?= $kat=='Surat'  ?'selected':'' ?>>Surat</option>
                    <option value="SK"      <?= $kat=='SK'     ?'selected':'' ?>>SK</option>
                    <option value="Laporan" <?= $kat=='Laporan'?'selected':'' ?>>Laporan</option>
                    <option value="Lainnya" <?= $kat=='Lainnya'?'selected':'' ?>>Lainnya</option>
                </select>
            </div>
            <div class="ar-fg">
                <label class="ar-flbl">Tahun</label>
                <select name="tahun" class="ar-fsel">
                    <option value="">Semua</option>
                    <?php for($y=date('Y'); $y>=date('Y')-5; $y--): ?>
                    <option value="<?= $y ?>" <?= $tahun==$y?'selected':'' ?>><?= $y ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="ar-fg">
                <label class="ar-flbl">&nbsp;</label>
                <button type="submit" class="ar-btn-filter">🔍 Cari</button>
            </div>
        </div>
    </div>
    </form>

    <!-- STAT CARDS -->
    <div class="ar-stat-row">
        <div class="ar-sc ar-sc-all">
            <div class="ar-sc-top">
                <div><div class="ar-sc-lbl">Total Arsip</div><div class="ar-sc-n"><?= $total ?></div></div>
                <div class="ar-sc-ico">🗄️</div>
            </div>
        </div>
        <?php foreach(['Surat'=>['📄','doc'],'SK'=>['📜','pdf'],'Laporan'=>['📊','img'],'Lainnya'=>['📁','all']] as $k=>[$ic,$cl]): ?>
        <div class="ar-sc ar-sc-<?= $cl ?>">
            <div class="ar-sc-top">
                <div><div class="ar-sc-lbl"><?= $k ?></div><div class="ar-sc-n"><?= $kat_stats[$k]??0 ?></div></div>
                <div class="ar-sc-ico"><?= $ic ?></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- ARSIP GRID -->
    <div class="ar-grid">
    <?php
    $delay = 0;
    if(mysqli_num_rows($arsip) > 0):
        while($a = mysqli_fetch_array($arsip)):
            $kc   = strtolower($a['kategori']);
            $ext  = pathinfo($a['file_path'], PATHINFO_EXTENSION);
            $icon = ['pdf'=>'📕','doc'=>'📘','docx'=>'📘','xls'=>'📗','xlsx'=>'📗',
                     'jpg'=>'🖼️','png'=>'🖼️','zip'=>'📦'][$ext] ?? '📄';
    ?>
    <div class="ar-card ar-c-<?= $kc ?>" style="animation-delay:<?= $delay ?>s">
        <div class="ar-card-head">
            <div class="ar-card-ico"><?= $icon ?></div>
            <div class="ar-card-meta">
                <div class="ar-card-date">📅 <?= date('d M Y', strtotime($a['tanggal'])) ?></div>
                <span class="ar-card-kat"><?= htmlspecialchars($a['kategori']) ?></span>
            </div>
        </div>
        <div class="ar-card-title"><?= htmlspecialchars($a['judul']) ?></div>
        <div class="ar-card-desc"><?= htmlspecialchars($a['keterangan'] ?: '-') ?></div>
        <div class="ar-card-foot">
            <div class="ar-card-user">👤 <?= htmlspecialchars($a['uploader'] ?? 'System') ?></div>
            <div class="ar-card-acts">
                <?php if(!empty($a['file_path']) && file_exists($a['file_path'])): ?>
                <a href="<?= htmlspecialchars($a['file_path']) ?>" target="_blank" class="ar-abtn ar-abtn-view">👁️ Lihat</a>
                <?php endif; ?>
                <a href="arsip.php?delete=<?= $a['id'] ?>" class="ar-abtn ar-abtn-del"
                   onclick="return confirm('Hapus dokumen ini?')">🗑️ Hapus</a>
            </div>
        </div>
    </div>
    <?php $delay += 0.03; endwhile;
    else: ?>
    <div class="ar-empty">
        <div class="ar-empty-ico">📭</div>
        <div class="ar-empty-txt">Belum ada dokumen arsip</div>
        <div style="font-size:.82rem;margin-top:.375rem">Upload dokumen pertama dengan tombol di atas 👆</div>
    </div>
    <?php endif; ?>
    </div>

</div><!-- /wrap -->
</div><!-- /main -->

<!-- MODAL UPLOAD -->
<div class="ar-modal" id="arModal">
    <div class="ar-mcon">
        <div class="ar-mhd">
            <div class="ar-mhd-title">📤 Upload Dokumen Baru</div>
            <button class="ar-mbtn-close" onclick="arCloseModal()">✕</button>
        </div>
        <form method="POST" action="arsip.php" enctype="multipart/form-data">
            <div class="ar-mbdy">
                <input type="hidden" name="upload" value="1">
                <div class="ar-mfg">
                    <label class="ar-mflbl">Judul Dokumen <span style="color:var(--ar-ruby)">*</span></label>
                    <input type="text" name="judul" class="ar-mfi" placeholder="Judul dokumen" required>
                </div>
                <div class="ar-mfg">
                    <label class="ar-mflbl">Kategori <span style="color:var(--ar-ruby)">*</span></label>
                    <select name="kategori" class="ar-mfi" required>
                        <option value="">Pilih kategori</option>
                        <option value="Surat">📄 Surat</option>
                        <option value="SK">📜 SK</option>
                        <option value="Laporan">📊 Laporan</option>
                        <option value="Lainnya">📁 Lainnya</option>
                    </select>
                </div>
                <div class="ar-mfg">
                    <label class="ar-mflbl">Tanggal</label>
                    <input type="date" name="tanggal" class="ar-mfi" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="ar-mfg">
                    <label class="ar-mflbl">Keterangan</label>
                    <textarea name="keterangan" class="ar-mfi" rows="3"
                        placeholder="Keterangan tambahan (opsional)"></textarea>
                </div>
                <div class="ar-mfg">
                    <label class="ar-mflbl">File Dokumen</label>
                    <input type="file" name="file" class="ar-mfi"
                        accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.zip">
                    <div style="font-size:.7rem;color:var(--ar-ink3);margin-top:.3rem">
                        Format: PDF, DOC, XLS, JPG, PNG, ZIP · Maks. 10MB
                    </div>
                </div>
            </div>
            <div class="ar-mft">
                <button type="button" class="ar-btn-cancel" onclick="arCloseModal()">Batal</button>
                <button type="submit" class="ar-btn-save">💾 Simpan Dokumen</button>
            </div>
        </form>
    </div>
</div>

<script>
function arOpenModal(){
    document.getElementById('arModal').classList.add('open');
    document.body.style.overflow = 'hidden';
}
function arCloseModal(){
    document.getElementById('arModal').classList.remove('open');
    document.body.style.overflow = '';
}
document.addEventListener('keydown', e => { if(e.key === 'Escape') arCloseModal(); });
/* Klik luar modal untuk menutup */
document.getElementById('arModal').addEventListener('click', function(e){
    if(e.target === this) arCloseModal();
});

/* Auto-dismiss alert setelah 5 detik */
document.querySelectorAll('.ar-alert').forEach(a => {
    setTimeout(() => {
        a.style.transition = 'opacity .5s, transform .5s';
        a.style.opacity = '0';
        a.style.transform = 'translateY(-10px)';
        setTimeout(() => a.remove(), 500);
    }, 5000);
});
</script>