<?php
/**
 * SISPENRA - Pengaturan Sekolah, Tahun Pelajaran & Formula Nilai
 */
require_once '../includes/functions.php';
requireAdmin();

$pageTitle  = 'Pengaturan';
$activeMenu = 'pengaturan';

$pengaturan = getPengaturan();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ── Simpan bobot PSAJ ──────────────────────────────────
    if ($action === 'psaj_bobot') {
        $bt  = floatval($_POST['psaj_bobot_tertulis']   ?? 40);
        $bp  = floatval($_POST['psaj_bobot_praktik']    ?? 20);
        $bpr = floatval($_POST['psaj_bobot_proyek']     ?? 15);
        $bpo = floatval($_POST['psaj_bobot_portofolio'] ?? 15);
        $bps = floatval($_POST['psaj_bobot_presentasi'] ?? 10);
        $total = $bt + $bp + $bpr + $bpo + $bps;
        if (abs($total - 100) < 0.01) {
            $p = getPengaturan();
            db_update('pengaturan', array(
                'psaj_bobot_tertulis'   => $bt,
                'psaj_bobot_praktik'    => $bp,
                'psaj_bobot_proyek'     => $bpr,
                'psaj_bobot_portofolio' => $bpo,
                'psaj_bobot_presentasi' => $bps,
            ), 'id = :id', array('id' => $p['id']));
            setFlash('success', 'Bobot PSAJ berhasil disimpan!');
        } else {
            setFlash('danger', 'Total bobot PSAJ harus 100%. Saat ini: '.$total.'%');
        }
        header('Location: pengaturan.php'); exit;
    }

    // ---- Simpan Data Sekolah ----
    if ($action === 'sekolah') {
        db_update('pengaturan', array(
            'nama_sekolah'   => sanitize($_POST['nama_sekolah'] ?? ''),
            'nss'            => sanitize($_POST['nss'] ?? ''),
            'npsn'           => sanitize($_POST['npsn'] ?? ''),
            'alamat'         => sanitize($_POST['alamat'] ?? ''),
            'kecamatan'      => sanitize($_POST['kecamatan'] ?? ''),
            'telepon'        => sanitize($_POST['telepon'] ?? ''),
            'email'          => sanitize($_POST['email'] ?? ''),
            'website'        => sanitize($_POST['website'] ?? ''),
            'kepala_sekolah' => sanitize($_POST['kepala_sekolah'] ?? ''),
            'nip_kepsek'     => sanitize($_POST['nip_kepsek'] ?? ''),
        ), 'id = :id', array('id' => $pengaturan['id']));
        setFlash('success', 'Data sekolah berhasil disimpan!');
        header('Location: pengaturan.php'); exit;
    }

    // ---- Simpan Tahun Pelajaran ----
    if ($action === 'tahun_ajaran') {
        $ta  = sanitize($_POST['tahun_ajaran_aktif'] ?? '');
        $sem = $_POST['semester_aktif'] ?? '1';
        if (!preg_match('/^\d{4}\/\d{4}$/', $ta)) {
            setFlash('danger', 'Format tahun ajaran harus: 2024/2025');
            header('Location: pengaturan.php'); exit;
        }
        db_update('pengaturan', array(
            'tahun_ajaran_aktif' => $ta,
            'semester_aktif'     => $sem,
        ), 'id = :id', array('id' => $pengaturan['id']));
        unset($_SESSION['base_url']);
        setFlash('success', 'Tahun pelajaran & semester aktif berhasil diubah!');
        header('Location: pengaturan.php'); exit;
    }

    // ---- Upload Logo Sekolah ----
    if ($action === 'logo') {
        if (isset($_FILES['logo_sekolah']) && $_FILES['logo_sekolah']['error'] === UPLOAD_ERR_OK) {
            $file     = $_FILES['logo_sekolah'];
            $allowed  = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
            $maxSize  = 2 * 1024 * 1024; // 2 MB

            if (!in_array($file['type'], $allowed)) {
                setFlash('danger', 'Format file tidak didukung. Gunakan JPG, PNG, GIF, WEBP, atau SVG.');
                header('Location: pengaturan.php'); exit;
            }
            if ($file['size'] > $maxSize) {
                setFlash('danger', 'Ukuran file terlalu besar. Maksimal 2 MB.');
                header('Location: pengaturan.php'); exit;
            }

            $uploadDir = dirname(__DIR__) . '/uploads/logo/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

            $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = 'logo_sekolah.' . strtolower($ext);
            $target   = $uploadDir . $filename;

            // Hapus logo lama jika ada (ekstensi berbeda)
            foreach (glob($uploadDir . 'logo_sekolah.*') as $old) {
                if ($old !== $target) unlink($old);
            }

            if (move_uploaded_file($file['tmp_name'], $target)) {
                // Simpan path relatif ke database
                db_update('pengaturan', ['logo_sekolah' => 'uploads/logo/' . $filename], 'id = :id', ['id' => $pengaturan['id']]);
                setFlash('success', 'Logo sekolah berhasil diperbarui!');
            } else {
                setFlash('danger', 'Gagal menyimpan logo. Periksa izin folder uploads/logo/.');
            }
        } elseif (isset($_POST['hapus_logo'])) {
            // Hapus logo
            $logoPath = dirname(__DIR__) . '/' . ($pengaturan['logo_sekolah'] ?? '');
            if (!empty($pengaturan['logo_sekolah']) && file_exists($logoPath)) unlink($logoPath);
            db_update('pengaturan', ['logo_sekolah' => ''], 'id = :id', ['id' => $pengaturan['id']]);
            setFlash('success', 'Logo sekolah berhasil dihapus.');
        } else {
            setFlash('danger', 'Tidak ada file yang diunggah.');
        }
        header('Location: pengaturan.php'); exit;
    }

    // ---- Simpan Formula Nilai ----
    if ($action === 'formula') {
        $rs  = floatval($_POST['formula_rata_sumatif'] ?? 50);
        $sts = floatval($_POST['formula_sts'] ?? 25);
        $sas = floatval($_POST['formula_sas'] ?? 25);
        $js  = intval($_POST['formula_jumlah_sumatif'] ?? 5);

        // Validasi total bobot harus 100
        $total = $rs + $sts + $sas;
        if (abs($total - 100) > 0.01) {
            setFlash('danger', 'Total bobot formula harus 100%. Saat ini: ' . number_format($total, 1) . '%');
            header('Location: pengaturan.php'); exit;
        }
        if ($js < 1 || $js > 10) {
            setFlash('danger', 'Jumlah sumatif harus antara 1 sampai 10.');
            header('Location: pengaturan.php'); exit;
        }

        db_update('pengaturan', array(
            'formula_rata_sumatif'   => $rs,
            'formula_sts'            => $sts,
            'formula_sas'            => $sas,
            'formula_jumlah_sumatif' => $js,
        ), 'id = :id', array('id' => $pengaturan['id']));
        setFlash('success', 'Formula nilai rapor berhasil disimpan!');
        header('Location: pengaturan.php'); exit;
    }
}

$pengaturan = getPengaturan();
$formula    = getFormula();

$tahunOptions = array();
$ty = intval(date('Y'));
for ($t = $ty - 4; $t <= $ty + 2; $t++) $tahunOptions[] = $t.'/'.($t+1);

include '../templates/header.php';
?>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;align-items:start;">

  <!-- ===== TAHUN PELAJARAN ===== -->
  <div class="card" style="border-top:3px solid var(--accent);">
    <div class="card-header">
      <span class="card-title"><i class="fas fa-calendar-alt" style="color:var(--accent);margin-right:8px;"></i>Tahun Pelajaran Aktif</span>
    </div>
    <div class="card-body">
      <div style="background:linear-gradient(135deg,var(--primary-dark),var(--primary));border-radius:10px;padding:18px 20px;margin-bottom:20px;color:#fff;text-align:center;">
        <div style="font-size:12px;opacity:.8;margin-bottom:4px;">Saat ini aktif:</div>
        <div style="font-size:26px;font-weight:800;letter-spacing:1px;"><?= htmlspecialchars($pengaturan['tahun_ajaran_aktif'] ?? '-') ?></div>
        <div style="font-size:14px;margin-top:4px;opacity:.9;">Semester <?= $pengaturan['semester_aktif'] ?? '-' ?></div>
      </div>
      <form method="POST">
        <input type="hidden" name="action" value="tahun_ajaran">
        <div class="form-group">
          <label class="form-label">Pilih atau Ketik Tahun Pelajaran</label>
          <select name="_ta_select" class="form-control" onchange="document.querySelector('[name=tahun_ajaran_aktif]').value=this.value">
            <?php foreach ($tahunOptions as $opt): ?>
            <option value="<?= $opt ?>" <?= ($pengaturan['tahun_ajaran_aktif'] === $opt) ? 'selected' : '' ?>><?= $opt ?></option>
            <?php endforeach; ?>
          </select>
          <input type="text" name="tahun_ajaran_aktif" class="form-control" style="margin-top:6px;"
                 placeholder="Contoh: 2024/2025"
                 value="<?= htmlspecialchars($pengaturan['tahun_ajaran_aktif'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Semester Aktif</label>
          <div style="display:flex;gap:12px;">
            <label style="display:flex;align-items:center;gap:8px;padding:10px 16px;border:2px solid var(--border);border-radius:8px;cursor:pointer;flex:1;" id="sem1label">
              <input type="radio" name="semester_aktif" value="1" <?= ($pengaturan['semester_aktif']??'1')==='1'?'checked':'' ?> onchange="highlightSem()" style="accent-color:var(--primary);">
              <span><strong>Semester 1</strong><br><small style="color:var(--text-muted);">Juli – Desember</small></span>
            </label>
            <label style="display:flex;align-items:center;gap:8px;padding:10px 16px;border:2px solid var(--border);border-radius:8px;cursor:pointer;flex:1;" id="sem2label">
              <input type="radio" name="semester_aktif" value="2" <?= ($pengaturan['semester_aktif']??'1')==='2'?'checked':'' ?> onchange="highlightSem()" style="accent-color:var(--primary);">
              <span><strong>Semester 2</strong><br><small style="color:var(--text-muted);">Januari – Juni</small></span>
            </label>
          </div>
        </div>
        <div style="background:#fff8e1;border:1px solid #ffe082;border-radius:8px;padding:10px 14px;margin-bottom:16px;font-size:12px;color:#7c5e00;">
          <i class="fas fa-exclamation-triangle"></i> Mengubah tahun/semester mempengaruhi seluruh data di aplikasi.
        </div>
        <button type="submit" class="btn btn-accent" style="width:100%;justify-content:center;"><i class="fas fa-save"></i> Simpan Tahun Pelajaran</button>
      </form>
    </div>
  </div>

  <!-- ===== FORMULA NILAI RAPOR ===== -->
  <div class="card" style="border-top:3px solid var(--success);">
    <div class="card-header">
      <span class="card-title"><i class="fas fa-calculator" style="color:var(--success);margin-right:8px;"></i>Formula Nilai Rapor</span>
    </div>
    <div class="card-body">

      <!-- Preview formula aktif -->
      <div style="background:#f0faf4;border:1px solid #a7d7b8;border-radius:10px;padding:14px 16px;margin-bottom:18px;">
        <div style="font-size:11px;color:#2d7a4f;font-weight:700;margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px;">
          <i class="fas fa-check-circle"></i> Formula yang Berlaku Saat Ini
        </div>
        <div style="font-size:13px;color:var(--text);font-family:monospace;line-height:2;">
          Nilai Rapor =
          <span style="background:#e8f5e9;padding:2px 7px;border-radius:4px;">(Rata Sumatif × <strong id="prev_rs"><?= $formula['rata_sumatif'] ?>%</strong>)</span>
          +
          <span style="background:#e3f2fd;padding:2px 7px;border-radius:4px;">(STS × <strong id="prev_sts"><?= $formula['sts'] ?>%</strong>)</span>
          +
          <span style="background:#fff8e1;padding:2px 7px;border-radius:4px;">(SAS × <strong id="prev_sas"><?= $formula['sas'] ?>%</strong>)</span>
        </div>
        <div style="font-size:12px;color:var(--text-muted);margin-top:6px;">
          <i class="fas fa-list-ol"></i> Jumlah kolom Sumatif: <strong id="prev_js"><?= $formula['jumlah_sumatif'] ?></strong> kolom (S1 – S<?= $formula['jumlah_sumatif'] ?>)
        </div>
        <div id="total_bobot_info" style="font-size:12px;margin-top:4px;"></div>
      </div>

      <form method="POST" id="formulaForm">
        <input type="hidden" name="action" value="formula">

        <div class="form-group">
          <label class="form-label">Jumlah Kolom Sumatif (1 – 10)</label>
          <div style="display:flex;align-items:center;gap:12px;">
            <input type="range" name="formula_jumlah_sumatif" id="sl_js"
                   min="1" max="10" step="1"
                   value="<?= $formula['jumlah_sumatif'] ?>"
                   style="flex:1;accent-color:var(--primary);"
                   oninput="updatePreview()">
            <span id="lbl_js" style="font-size:20px;font-weight:800;color:var(--primary);min-width:24px;text-align:center;"><?= $formula['jumlah_sumatif'] ?></span>
            <span style="font-size:13px;color:var(--text-muted);">kolom</span>
          </div>
          <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-muted);margin-top:2px;">
            <span>S1</span><span>S10</span>
          </div>
        </div>

        <div style="background:var(--bg);border-radius:10px;padding:14px 16px;margin-bottom:16px;">
          <div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:.5px;">Bobot Formula (%)</div>

          <div class="form-group" style="margin-bottom:10px;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
              <label class="form-label" style="margin:0;color:var(--success);">
                <i class="fas fa-layer-group"></i> Rata-rata Sumatif
              </label>
              <span id="lbl_rs" style="font-weight:800;font-size:16px;color:var(--success);"><?= $formula['rata_sumatif'] ?>%</span>
            </div>
            <input type="range" name="formula_rata_sumatif" id="sl_rs"
                   min="0" max="100" step="5"
                   value="<?= $formula['rata_sumatif'] ?>"
                   style="width:100%;accent-color:var(--success);"
                   oninput="updatePreview()">
          </div>

          <div class="form-group" style="margin-bottom:10px;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
              <label class="form-label" style="margin:0;color:var(--info);">
                <i class="fas fa-file-alt"></i> Sumatif Tengah Semester (STS)
              </label>
              <span id="lbl_sts" style="font-weight:800;font-size:16px;color:var(--info);"><?= $formula['sts'] ?>%</span>
            </div>
            <input type="range" name="formula_sts" id="sl_sts"
                   min="0" max="100" step="5"
                   value="<?= $formula['sts'] ?>"
                   style="width:100%;accent-color:var(--info);"
                   oninput="updatePreview()">
          </div>

          <div class="form-group" style="margin-bottom:0;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
              <label class="form-label" style="margin:0;color:var(--accent);">
                <i class="fas fa-file-alt"></i> Sumatif Akhir Semester (SAS)
              </label>
              <span id="lbl_sas" style="font-weight:800;font-size:16px;color:var(--accent);"><?= $formula['sas'] ?>%</span>
            </div>
            <input type="range" name="formula_sas" id="sl_sas"
                   min="0" max="100" step="5"
                   value="<?= $formula['sas'] ?>"
                   style="width:100%;accent-color:var(--accent);"
                   oninput="updatePreview()">
          </div>
        </div>

        <!-- Total bobot indicator -->
        <div id="bobot_bar" style="border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:13px;font-weight:600;text-align:center;">
        </div>

        <!-- Contoh perhitungan -->
        <div style="background:#f8f9fa;border-radius:8px;padding:12px 14px;margin-bottom:14px;font-size:12px;">
          <div style="font-weight:700;margin-bottom:6px;color:var(--text-muted);"><i class="fas fa-calculator"></i> Contoh Perhitungan:</div>
          <div id="contoh_hitung" style="font-family:monospace;line-height:1.8;color:var(--text);"></div>
        </div>

        <button type="submit" id="btnSimpanFormula" class="btn btn-success" style="width:100%;justify-content:center;">
          <i class="fas fa-save"></i> Simpan Formula
        </button>
      </form>
    </div>
  </div>

  <!-- ===== DATA SEKOLAH (full width bawah) ===== -->
  <div class="card" style="grid-column:1 / -1;">
    <div class="card-header">
      <span class="card-title"><i class="fas fa-school" style="color:var(--primary);margin-right:8px;"></i>Data Sekolah</span>
    </div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="action" value="sekolah">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
          <div class="form-group" style="grid-column:1/-1;">
            <label class="form-label">Nama Sekolah</label>
            <input type="text" name="nama_sekolah" class="form-control"
                   value="<?= htmlspecialchars($pengaturan['nama_sekolah'] ?? '') ?>" placeholder="SMP Negeri 1 ...">
          </div>
          <div class="form-group">
            <label class="form-label">NSS</label>
            <input type="text" name="nss" class="form-control" value="<?= htmlspecialchars($pengaturan['nss'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">NPSN</label>
            <input type="text" name="npsn" class="form-control" value="<?= htmlspecialchars($pengaturan['npsn'] ?? '') ?>">
          </div>
          <div class="form-group" style="grid-column:1/-1;">
            <label class="form-label">Alamat</label>
            <textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars($pengaturan['alamat'] ?? '') ?></textarea>
          </div>
          <div class="form-group">
            <label class="form-label">Kecamatan <span style="font-size:11px;color:var(--text-muted);">(untuk tanda tangan daftar nilai)</span></label>
            <input type="text" name="kecamatan" class="form-control"
                   value="<?= htmlspecialchars($pengaturan['kecamatan'] ?? '') ?>"
                   placeholder="Contoh: Sugio">
          </div>
          <div class="form-group">
            <label class="form-label">Telepon</label>
            <input type="text" name="telepon" class="form-control" value="<?= htmlspecialchars($pengaturan['telepon'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Email</label>
            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($pengaturan['email'] ?? '') ?>">
          </div>
          <div class="form-group" style="grid-column:1/-1;">
            <label class="form-label">Website</label>
            <input type="text" name="website" class="form-control" value="<?= htmlspecialchars($pengaturan['website'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Nama Kepala Sekolah</label>
            <input type="text" name="kepala_sekolah" class="form-control" value="<?= htmlspecialchars($pengaturan['kepala_sekolah'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">NIP Kepala Sekolah</label>
            <input type="text" name="nip_kepsek" class="form-control" value="<?= htmlspecialchars($pengaturan['nip_kepsek'] ?? '') ?>">
          </div>
        </div>
        <button type="submit" class="btn btn-primary" style="margin-top:8px;"><i class="fas fa-save"></i> Simpan Data Sekolah</button>
      </form>

      <hr style="margin:24px 0;border-color:var(--border);">

      <!-- ===== LOGO SEKOLAH ===== -->
      <div>
        <div style="font-size:14px;font-weight:700;margin-bottom:14px;color:var(--text);">
          <i class="fas fa-image" style="color:var(--primary);margin-right:6px;"></i>Logo Sekolah
        </div>
        <div style="display:flex;align-items:flex-start;gap:24px;flex-wrap:wrap;">

          <!-- Preview logo -->
          <div style="flex-shrink:0;text-align:center;">
            <?php
              $logoUrl = !empty($pengaturan['logo_sekolah']) ? '../' . htmlspecialchars($pengaturan['logo_sekolah']) : '';
            ?>
            <div id="logoPreviewWrap" style="width:120px;height:120px;border:2px dashed var(--border);border-radius:12px;display:flex;align-items:center;justify-content:center;overflow:hidden;background:#f8f9fa;">
              <?php if ($logoUrl): ?>
                <img id="logoPreview" src="<?= $logoUrl ?>?v=<?= time() ?>" alt="Logo Sekolah" style="max-width:116px;max-height:116px;object-fit:contain;">
              <?php else: ?>
                <div id="logoPlaceholder" style="text-align:center;color:var(--text-muted);font-size:12px;padding:8px;">
                  <i class="fas fa-image" style="font-size:32px;display:block;margin-bottom:6px;opacity:.4;"></i>Belum ada logo
                </div>
              <?php endif; ?>
            </div>
            <?php if ($logoUrl): ?>
            <form method="POST" style="margin-top:8px;" onsubmit="return confirm('Hapus logo sekolah?')">
              <input type="hidden" name="action" value="logo">
              <input type="hidden" name="hapus_logo" value="1">
              <button type="submit" class="btn" style="font-size:12px;padding:4px 12px;color:var(--danger);border:1px solid var(--danger);background:transparent;">
                <i class="fas fa-trash"></i> Hapus Logo
              </button>
            </form>
            <?php endif; ?>
          </div>

          <!-- Form upload -->
          <div style="flex:1;min-width:220px;">
            <form method="POST" enctype="multipart/form-data" id="formLogoUpload">
              <input type="hidden" name="action" value="logo">
              <div class="form-group">
                <label class="form-label">Unggah Logo Baru</label>
                <div id="logoDropZone"
                     style="border:2px dashed var(--border);border-radius:10px;padding:20px;text-align:center;cursor:pointer;transition:.2s;background:#fafafa;"
                     onclick="document.getElementById('inputLogo').click()"
                     ondragover="event.preventDefault();this.style.borderColor='var(--primary)';this.style.background='#eef4ff';"
                     ondragleave="this.style.borderColor='var(--border)';this.style.background='#fafafa';"
                     ondrop="handleDrop(event)">
                  <i class="fas fa-cloud-upload-alt" style="font-size:24px;color:var(--primary);margin-bottom:8px;display:block;"></i>
                  <div style="font-size:13px;font-weight:600;color:var(--text);">Klik atau seret file ke sini</div>
                  <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">JPG, PNG, GIF, WEBP, SVG &mdash; maks. 2 MB</div>
                </div>
                <input type="file" name="logo_sekolah" id="inputLogo" accept="image/*" style="display:none;" onchange="previewLogo(this)">
                <div id="namaFileLogo" style="font-size:12px;color:var(--text-muted);margin-top:6px;"></div>
              </div>
              <button type="submit" id="btnUploadLogo" class="btn btn-primary" disabled style="opacity:.5;">
                <i class="fas fa-upload"></i> Upload Logo
              </button>
            </form>
            <div style="margin-top:10px;font-size:12px;color:var(--text-muted);line-height:1.6;">
              <i class="fas fa-info-circle" style="color:var(--info);"></i>
              Logo akan ditampilkan di header rapor dan dokumen sekolah. Disarankan ukuran <strong>200&times;200 px</strong> dengan latar transparan (PNG).
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

<script>
function updatePreview() {
    var rs  = parseFloat(document.getElementById('sl_rs').value)  || 0;
    var sts = parseFloat(document.getElementById('sl_sts').value) || 0;
    var sas = parseFloat(document.getElementById('sl_sas').value) || 0;
    var js  = parseInt(document.getElementById('sl_js').value)    || 5;
    var total = rs + sts + sas;

    document.getElementById('lbl_rs').textContent  = rs  + '%';
    document.getElementById('lbl_sts').textContent = sts + '%';
    document.getElementById('lbl_sas').textContent = sas + '%';
    document.getElementById('lbl_js').textContent  = js;

    // Preview formula di atas
    document.getElementById('prev_rs').textContent  = rs  + '%';
    document.getElementById('prev_sts').textContent = sts + '%';
    document.getElementById('prev_sas').textContent = sas + '%';
    document.getElementById('prev_js').textContent  = js;

    // Bobot bar
    var bar = document.getElementById('bobot_bar');
    var btn = document.getElementById('btnSimpanFormula');
    if (Math.abs(total - 100) < 0.01) {
        bar.style.background = '#d4edda'; bar.style.color = '#155724'; bar.style.border = '1px solid #c3e6cb';
        bar.innerHTML = '<i class="fas fa-check-circle"></i> Total bobot: <strong>100%</strong> ✓';
        btn.disabled = false; btn.style.opacity = '1';
    } else {
        bar.style.background = '#f8d7da'; bar.style.color = '#721c24'; bar.style.border = '1px solid #f5c6cb';
        bar.innerHTML = '<i class="fas fa-times-circle"></i> Total bobot: <strong>' + total + '%</strong> — harus tepat 100%';
        btn.disabled = true; btn.style.opacity = '.5';
    }

    // Contoh perhitungan pakai nilai 80
    var rata = rs > 0 ? '80 × ' + rs + '% = ' + (80 * rs / 100).toFixed(1) : '';
    var stsC = sts > 0 ? '75 × ' + sts + '% = ' + (75 * sts / 100).toFixed(1) : '';
    var sasC = sas > 0 ? '85 × ' + sas + '% = ' + (85 * sas / 100).toFixed(1) : '';
    var parts = [rata, stsC, sasC].filter(function(x){ return x !== ''; });
    var totalNilai = (80 * rs / 100) + (75 * sts / 100) + (85 * sas / 100);
    var normTotal  = total > 0 ? Math.round((totalNilai / total) * 100) : 0;
    var html = 'Contoh (Rata Sumatif=80, STS=75, SAS=85):<br>';
    html += parts.join(' + ') + (total !== 100 ? ' (bobot disesuaikan)' : '') + '<br>';
    html += '<strong>Nilai Rapor = ' + normTotal + '</strong>';
    document.getElementById('contoh_hitung').innerHTML = html;
}

function highlightSem() {
    var r1 = document.querySelector('[name=semester_aktif][value="1"]');
    var r2 = document.querySelector('[name=semester_aktif][value="2"]');
    document.getElementById('sem1label').style.borderColor = r1.checked ? 'var(--primary)' : 'var(--border)';
    document.getElementById('sem2label').style.borderColor = r2.checked ? 'var(--primary)' : 'var(--border)';
    document.getElementById('sem1label').style.background  = r1.checked ? 'rgba(26,74,122,.05)' : '';
    document.getElementById('sem2label').style.background  = r2.checked ? 'rgba(26,74,122,.05)' : '';
}

function previewLogo(input) {
    var file = input.files[0];
    if (!file) return;
    document.getElementById('namaFileLogo').textContent = file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)';
    var btn = document.getElementById('btnUploadLogo');
    btn.disabled = false; btn.style.opacity = '1';

    var reader = new FileReader();
    reader.onload = function(e) {
        var wrap = document.getElementById('logoPreviewWrap');
        wrap.innerHTML = '<img id="logoPreview" src="' + e.target.result + '" style="max-width:116px;max-height:116px;object-fit:contain;">';
        document.getElementById('logoDropZone').style.borderColor = 'var(--success)';
        document.getElementById('logoDropZone').style.background  = '#f0faf4';
    };
    reader.readAsDataURL(file);
}

function handleDrop(e) {
    e.preventDefault();
    document.getElementById('logoDropZone').style.borderColor = 'var(--border)';
    document.getElementById('logoDropZone').style.background  = '#fafafa';
    var files = e.dataTransfer.files;
    if (files.length) {
        var inp = document.getElementById('inputLogo');
        inp.files = files;
        previewLogo(inp);
    }
}

// Init
updatePreview();
highlightSem();
</script>


<!-- ══════════════ BOBOT PSAJ ══════════════ -->
<div class="card" id="psaj" style="margin-top:20px;">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-graduation-cap" style="color:#7c3aed;margin-right:8px;"></i>
      Bobot Nilai PSAJ (Penilaian Sumatif Akhir Jenjang) — Kelas 9
    </span>
  </div>
  <div class="card-body">
    <p style="font-size:13px;color:var(--text-muted);margin-bottom:16px;">
      <i class="fas fa-info-circle"></i>
      Total bobot harus <strong>100%</strong>. Digunakan untuk menghitung Nilai Akhir PSAJ kelas 9.
    </p>
    <form method="POST">
      <input type="hidden" name="action" value="psaj_bobot">
      <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:16px;">
        <?php
        $psajKomp = array(
            'tertulis'   => array('Tes Tertulis',            '#1e40af', '#dbeafe'),
            'praktik'    => array('Praktik / Unjuk Kerja',   '#065f46', '#d1fae5'),
            'proyek'     => array('Proyek',                  '#92400e', '#fef3c7'),
            'portofolio' => array('Portofolio',              '#4c1d95', '#ede9fe'),
            'presentasi' => array('Presentasi / Penugasan',  '#991b1b', '#fee2e2'),
        );
        $psajDefault = array('tertulis'=>40,'praktik'=>20,'proyek'=>15,'portofolio'=>15,'presentasi'=>10);
        foreach ($psajKomp as $key => $info):
            $val = floatval($pengaturan['psaj_bobot_'.$key] ?? $psajDefault[$key]);
        ?>
        <div>
          <label style="font-size:12px;font-weight:700;color:<?= $info[1] ?>;display:flex;align-items:center;gap:6px;margin-bottom:6px;">
            <span style="background:<?= $info[2] ?>;border-radius:6px;padding:2px 8px;"><?= $info[0] ?></span>
          </label>
          <div style="display:flex;align-items:center;gap:8px;">
            <input type="range" name="psaj_bobot_<?= $key ?>" id="psaj_<?= $key ?>"
                   min="0" max="100" step="5" value="<?= $val ?>"
                   style="flex:1;accent-color:<?= $info[1] ?>;"
                   oninput="updatePsajPreview()">
            <span id="lbl_psaj_<?= $key ?>" style="font-weight:800;font-size:17px;min-width:40px;color:<?= $info[1] ?>;">
              <?= $val ?>%
            </span>
          </div>
        </div>
        <?php endforeach; ?>
      </div>

      <div id="psaj_status" style="padding:8px 14px;border-radius:8px;font-size:13px;font-weight:600;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;">
        <span id="psaj_status_text"></span>
        <button type="submit" id="psaj_btnSimpan" class="btn btn-primary btn-sm">
          <i class="fas fa-save"></i> Simpan Bobot PSAJ
        </button>
      </div>
    </form>
  </div>
</div>

<script>
function updatePsajPreview() {
    var keys = ['tertulis','praktik','proyek','portofolio','presentasi'];
    var total = 0;
    keys.forEach(function(k) {
        var v = parseFloat(document.getElementById('psaj_'+k).value) || 0;
        document.getElementById('lbl_psaj_'+k).textContent = v + '%';
        total += v;
    });
    var st  = document.getElementById('psaj_status');
    var tx  = document.getElementById('psaj_status_text');
    var btn = document.getElementById('psaj_btnSimpan');
    if (Math.abs(total - 100) < 0.01) {
        st.style.cssText = 'background:#d4edda;color:#155724;border:1px solid #c3e6cb;padding:8px 14px;border-radius:8px;font-size:13px;font-weight:600;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;';
        tx.innerHTML = '<i class="fas fa-check-circle"></i> Total bobot: 100% ✓';
        btn.disabled = false; btn.style.opacity = '1';
    } else {
        st.style.cssText = 'background:#f8d7da;color:#721c24;border:1px solid #f5c6cb;padding:8px 14px;border-radius:8px;font-size:13px;font-weight:600;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;';
        tx.innerHTML = '<i class="fas fa-times-circle"></i> Total: ' + total + '% — harus 100%';
        btn.disabled = true; btn.style.opacity = '.5';
    }
}
updatePsajPreview();
</script>

<?php include '../templates/footer.php'; ?>