<?php
include_once 'init.php'; // Menghubungkan koneksi $pdo dan session

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$message = '';

// ==========================================
// == LOGIKA PROSES (ACTION HANDLING) ==
// ==========================================
try {
    // 1. Update Identitas Sekolah
    if ($action === 'update_identitas') {
        $stmt = $pdo->prepare("UPDATE pengaturan_aplikasi SET nama_sekolah=?, alamat=?, bendahara=?, nip_bendahara=? WHERE id=1");
        $stmt->execute([$_POST['nama_sekolah'], $_POST['alamat'], $_POST['bendahara'], $_POST['nip_bendahara']]);
        $_SESSION['msg'] = "Identitas sekolah berhasil diperbarui!";
        header("Location: pengaturan.php?tab=identitas"); exit();
    }

    // 2. Tambah Tahun Fiskal Baru
    if ($action === 'tambah_tahun') {
        $stmt = $pdo->prepare("INSERT INTO tahun_fiskal (nama_tahun, status) VALUES (?, 'arsip')");
        $stmt->execute([$_POST['nama_tahun']]);
        $_SESSION['msg'] = "Tahun fiskal baru berhasil ditambahkan.";
        header("Location: pengaturan.php?tab=tahun"); exit();
    }

    // 3. Set Tahun Aktif (Arsip yang lain)
    if ($action === 'set_aktif' && isset($_GET['id'])) {
        $pdo->query("UPDATE tahun_fiskal SET status = 'arsip'");
        $stmt = $pdo->prepare("UPDATE tahun_fiskal SET status = 'aktif' WHERE id_tahun = ?");
        $stmt->execute([$_GET['id']]);
        $_SESSION['msg'] = "Tahun fiskal aktif berhasil diubah.";
        header("Location: pengaturan.php?tab=tahun"); exit();
    }
} catch (PDOException $e) {
    $message = '<div class="alert alert-danger">Kesalahan: ' . $e->getMessage() . '</div>';
}

// Ambil Data dari DB
$pengaturan = $pdo->query("SELECT * FROM pengaturan_aplikasi WHERE id = 1")->fetch();
$tahun_list = $pdo->query("SELECT * FROM tahun_fiskal ORDER BY nama_tahun DESC")->fetchAll();

$page_title = 'Pengaturan Sistem';
$page_icon = 'bi-gear';
$active_tab = $_GET['tab'] ?? 'identitas';
include 'header.php';
?>

<div class="container-fluid mt-4">
    <?php if(isset($_SESSION['msg'])): ?>
        <div class="alert alert-success"><?= $_SESSION['msg']; unset($_SESSION['msg']); ?></div>
    <?php endif; ?>
    <?= $message ?>

    <nav>
        <div class="nav nav-tabs" id="nav-tab">
            <a class="nav-link <?= $active_tab == 'identitas' ? 'active' : '' ?>" href="?tab=identitas"><i class="bi bi-bank"></i> Identitas</a>
            <a class="nav-link <?= $active_tab == 'tahun' ? 'active' : '' ?>" href="?tab=tahun"><i class="bi bi-calendar-check"></i> Tahun Fiskal</a>
            <a class="nav-link <?= $active_tab == 'backup' ? 'active' : '' ?>" href="?tab=backup"><i class="bi bi-database-down"></i> Backup & Restore</a>
        </div>
    </nav>

    <div class="tab-content content-card shadow-sm p-4 bg-white border border-top-0">
        <?php if($active_tab == 'identitas'): ?>
        <form method="POST">
            <input type="hidden" name="action" value="update_identitas">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Nama Sekolah</label>
                    <input type="text" name="nama_sekolah" class="form-control" value="<?= htmlspecialchars($pengaturan['nama_sekolah']) ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Nama Bendahara</label>
                    <input type="text" name="bendahara" class="form-control" value="<?= htmlspecialchars($pengaturan['bendahara']) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label>NIP Bendahara</label>
                    <input type="text" name="nip_bendahara" class="form-control" value="<?= htmlspecialchars($pengaturan['nip_bendahara']) ?>">
                </div>
                <div class="col-12 mb-3">
                    <label>Alamat Sekolah</label>
                    <textarea name="alamat" class="form-control" rows="3"><?= htmlspecialchars($pengaturan['alamat']) ?></textarea>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Simpan Perubahan</button>
        </form>
        <?php endif; ?>

        <?php if($active_tab == 'tahun'): ?>
        <div class="d-flex justify-content-between mb-3">
            <h5>Daftar Periode Tabungan</h5>
            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalTahun">Tambah Tahun</button>
        </div>
        <table class="table table-bordered">
            <thead class="table-light">
                <tr><th>Nama Tahun</th><th>Status</th><th>Aksi</th></tr>
            </thead>
            <tbody>
                <?php foreach($tahun_list as $t): ?>
                <tr class="<?= $t['status']=='aktif' ? 'table-success' : '' ?>">
                    <td><?= $t['nama_tahun'] ?></td>
                    <td><span class="badge bg-<?= $t['status']=='aktif'?'success':'secondary' ?>"><?= strtoupper($t['status']) ?></span></td>
                    <td>
                        <?php if($t['status'] != 'aktif'): ?>
                        <a href="?action=set_aktif&id=<?= $t['id_tahun'] ?>" class="btn btn-sm btn-success">Aktifkan</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <?php if($active_tab == 'backup'): ?>
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card p-3 border-success h-100">
                    <h6><i class="bi bi-download text-success"></i> Backup Database</h6>
                    <p class="small text-muted">Unduh seluruh data tabungan dan konfigurasi dalam format .SQL.</p>
                    <a href="backup_script.php" class="btn btn-success mt-auto">Unduh Backup</a>
                </div>
            </div>
            <div class="col-md-6 mb-4">
                <div class="card p-3 border-danger h-100">
                    <h6><i class="bi bi-upload text-danger"></i> Restore Database</h6>
                    <p class="small text-muted">Unggah file .SQL untuk memulihkan data. <br><strong>Perhatian:</strong> Data saat ini akan terhapus!</p>
                    <form method="POST" action="restore_script.php" enctype="multipart/form-data">
                        <input type="file" name="sql_file" class="form-control mb-2" required>
                        <button type="submit" class="btn btn-danger">Restore Data</button>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="modalTahun" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5>Tambah Tahun Fiskal</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="tambah_tahun">
                <label class="form-label">Nama Tahun (Contoh: 2024/2025)</label>
                <input type="text" name="nama_tahun" class="form-control" placeholder="2025/2026" required>
            </div>
            <div class="modal-footer"><button type="submit" class="btn btn-primary">Simpan</button></div>
        </form>
    </div>
</div>

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