<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireRole('admin');

$id   = (int)($_GET['id'] ?? 0);
$edit = $id > 0;
$data = [];

if ($edit) {
    $data = Database::fetchOne("SELECT * FROM dokumen WHERE id=?", [$id]);
    if (!$data) { setFlash('error','Dokumen tidak ditemukan.'); redirect(BASE_URL.'/modules/dokumen/index.php'); }
}

$sekolahList = Database::fetchAll("SELECT id,nama_sekolah FROM sekolah WHERE aktif=1 ORDER BY nama_sekolah");
$jenisList   = ['SK','Surat Edaran','Pedoman','Juknis','Form','Laporan','Lainnya'];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $errors[] = 'Token tidak valid.'; }

    $fields = [
        'sekolah_id'   => (int)($_POST['sekolah_id'] ?? 0) ?: null,
        'nama_dokumen' => sanitize($_POST['nama_dokumen'] ?? ''),
        'jenis'        => sanitize($_POST['jenis'] ?? 'Lainnya'),
        'deskripsi'    => sanitize($_POST['deskripsi'] ?? ''),
        'tahun'        => sanitize($_POST['tahun'] ?? '') ?: null,
        'publik'       => isset($_POST['publik']) ? 1 : 0,
    ];

    if (empty($fields['nama_dokumen'])) $errors[] = 'Nama dokumen wajib diisi.';

    if (!$edit && empty($_FILES['file_dokumen']['name'])) {
        $errors[] = 'File dokumen wajib diupload.';
    }

    if (empty($errors)) {
        if (!empty($_FILES['file_dokumen']['name'])) {
            $up = uploadFile($_FILES['file_dokumen'], 'dokumen', ALLOWED_DOC, MAX_FILE_SIZE);
            if (!$up['success']) { $errors[] = $up['error']; }
            else {
                // Hapus file lama jika edit
                if ($edit && !empty($data['nama_file'])) {
                    deleteFile('dokumen', $data['nama_file']);
                }
                $fields['nama_file'] = $up['filename'];
                $fields['nama_asli'] = $_FILES['file_dokumen']['name'];
                $fields['ukuran']    = $_FILES['file_dokumen']['size'];
            }
        }

        if (empty($errors)) {
            if ($edit) {
                $set  = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
                $vals = array_values($fields); $vals[] = $id;
                Database::execute("UPDATE dokumen SET {$set} WHERE id=?", $vals);
                auditLog('UPDATE','dokumen',$id,$fields['nama_dokumen']);
                setFlash('success','Dokumen berhasil diperbarui.');
            } else {
                $cols = implode(',', array_keys($fields));
                $pls  = implode(',', array_fill(0, count($fields), '?'));
                Database::execute("INSERT INTO dokumen ({$cols}) VALUES ({$pls})", array_values($fields));
                auditLog('INSERT','dokumen',(int)Database::lastInsertId(),$fields['nama_dokumen']);
                setFlash('success','Dokumen berhasil diupload.');
            }
            redirect(BASE_URL.'/modules/dokumen/index.php');
        }
    }
    $data = array_merge($data, $fields);
}

$pageTitle  = ($edit?'Edit':'Upload').' Dokumen';
$activePage = 'dokumen';
require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-cloud-upload me-2 text-primary"></i><?= $pageTitle ?></h1>
    <nav><ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dokumen/index.php">Dokumen</a></li>
      <li class="breadcrumb-item active"><?= $edit?'Edit':'Upload' ?></li>
    </ol></nav>
  </div>
</div>

<?php if($errors): ?>
<div class="alert alert-danger border-0 mb-3"><ul class="mb-0 ps-3"><?php foreach($errors as $e): ?><li><?= e($e) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<div class="row justify-content-center">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header"><span class="card-header-title"><i class="bi bi-file-earmark-plus me-2"></i>Form Dokumen</span></div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <?= csrf_field() ?>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Nama Dokumen <span class="text-danger">*</span></label>
              <input type="text" name="nama_dokumen" class="form-control" value="<?= e($data['nama_dokumen'] ?? '') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Jenis Dokumen</label>
              <select name="jenis" class="form-select">
                <?php foreach($jenisList as $j): ?>
                <option value="<?= $j ?>" <?= ($data['jenis']??'')===$j?'selected':'' ?>><?= $j ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">Tahun</label>
              <input type="number" name="tahun" class="form-control" min="2000" max="2030" value="<?= e($data['tahun'] ?? date('Y')) ?>">
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <div class="form-check mb-1">
                <input class="form-check-input" type="checkbox" name="publik" id="chkPublik" <?= ($data['publik'] ?? 0) ? 'checked' : '' ?>>
                <label class="form-check-label" for="chkPublik">Dokumen publik</label>
              </div>
            </div>
            <div class="col-12">
              <label class="form-label">Sekolah <small class="text-muted">(kosongkan jika dokumen umum)</small></label>
              <select name="sekolah_id" class="form-select">
                <option value="">— Dokumen Umum / Dinas —</option>
                <?php foreach($sekolahList as $s): ?>
                <option value="<?= $s['id'] ?>" <?= ($data['sekolah_id']??0)==(int)$s['id']?'selected':'' ?>><?= e($s['nama_sekolah']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label">Deskripsi</label>
              <textarea name="deskripsi" class="form-control" rows="2"><?= e($data['deskripsi'] ?? '') ?></textarea>
            </div>
            <div class="col-12">
              <label class="form-label">File Dokumen <?= $edit ? '<small class="text-muted">(kosongkan jika tidak diganti)</small>' : '<span class="text-danger">*</span>' ?></label>
              <label class="upload-zone w-100" style="cursor:pointer">
                <div class="upload-icon"><i class="bi bi-file-earmark-arrow-up"></i></div>
                <p class="mb-1 fw-600">Pilih atau seret file</p>
                <p class="text-muted mb-0" style="font-size:.78rem">PDF, DOC, DOCX • Maks 10MB</p>
                <input type="file" name="file_dokumen" accept=".pdf,.doc,.docx" class="d-none" id="fileDokInput">
              </label>
              <div id="filePreview" class="mt-2 d-none p-2 bg-light rounded d-flex align-items-center gap-2" style="font-size:.83rem">
                <i class="bi bi-file-earmark text-primary fs-5"></i>
                <span id="filePreviewName"></span>
              </div>
              <?php if($edit && !empty($data['nama_asli'])): ?>
              <div class="mt-2 text-muted" style="font-size:.8rem"><i class="bi bi-paperclip me-1"></i>File saat ini: <?= e($data['nama_asli']) ?></div>
              <?php endif; ?>
            </div>
            <div class="col-12 pt-2 d-flex gap-2">
              <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i><?= $edit?'Simpan':'Upload Dokumen' ?></button>
              <a href="<?= BASE_URL ?>/modules/dokumen/index.php" class="btn btn-outline-secondary">Batal</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php
$extraJs = <<<JS
<script>
document.getElementById('fileDokInput')?.addEventListener('change', function() {
  const preview = document.getElementById('filePreview');
  const name    = document.getElementById('filePreviewName');
  if (this.files[0]) {
    name.textContent = this.files[0].name + ' (' + (this.files[0].size/1024).toFixed(1) + ' KB)';
    preview.classList.remove('d-none');
    preview.classList.add('d-flex');
  }
});
</script>
JS;
require_once ROOT_PATH . '/views/layouts/footer.php';
?>
