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

$page_title = 'Pengaturan Sistem';
$page_icon = 'bi-gear';
$active_tab = $_GET['tab'] ?? 'identitas';
$message = '';

// ==========================================
// == LOGIKA PROSES (ACTION HANDLING) ==
// ==========================================
try {
    // 1. Update Identitas Sekolah & Logo
    if (isset($_POST['action']) && $_POST['action'] === 'update_identitas') {
        $nama_sekolah = $_POST['nama_sekolah'];
        $alamat = $_POST['alamat'];
        $bendahara = $_POST['bendahara'];
        $nip_bendahara = $_POST['nip_bendahara'];
        
        // Logika Upload Logo
        $logo_query = "";
        $params = [$nama_sekolah, $alamat, $bendahara, $nip_bendahara];
        
        if (!empty($_FILES['logo']['name'])) {
            $target_dir = "../assets/img/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            
            $file_ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $new_name = "logo_sekolah_" . time() . "." . $file_ext;
            $target_file = $target_dir . $new_name;
            
            if (move_uploaded_file($_FILES['logo']['tmp_name'], $target_file)) {
                $logo_query = ", logo_sekolah=?";
                $params[] = $new_name;
            }
        }

        $sql = "UPDATE pengaturan_aplikasi SET nama_sekolah=?, alamat=?, bendahara=?, nip_bendahara=? $logo_query WHERE id=1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        $_SESSION['msg'] = "Identitas sekolah berhasil diperbarui!";
        header("Location: pengaturan.php?tab=identitas"); exit();
    }

    // 2. Logika Manajemen Pengguna (Hak Akses)
    if (isset($_POST['simpan_user'])) {
        $nama = $_POST['nama_lengkap'];
        $user = $_POST['username'];
        $pass = $_POST['password']; 
        $id = $_POST['id'] ?? '';

        if (!empty($id)) {
            // Mode Update
            if (!empty($pass)) {
                $pass_hash = password_hash($pass, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET nama_lengkap=?, username=?, password=? WHERE id=?");
                $stmt->execute([$nama, $user, $pass_hash, $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET nama_lengkap=?, username=? WHERE id=?");
                $stmt->execute([$nama, $user, $id]);
            }
            $_SESSION['msg'] = "Pengguna berhasil diperbarui.";
        } else {
            // Mode Tambah
            $role = $_POST['role'];
            $cek = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
            $cek->execute([$user]);
            if ($cek->fetchColumn() > 0) {
                $_SESSION['error'] = "Username '$user' sudah digunakan!";
            } else {
                $pass_hash = password_hash($pass, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (nama_lengkap, username, password, role) VALUES (?, ?, ?, ?)");
                $stmt->execute([$nama, $user, $pass_hash, $role]);
                $_SESSION['msg'] = "Pengguna baru ditambahkan.";
            }
        }
        header("Location: pengaturan.php?tab=akses"); exit();
    }

    // 3. Hapus Pengguna
    if (isset($_POST['delete_user_id'])) {
        $id_hapus = $_POST['delete_user_id'];
        if ($id_hapus != $_SESSION['user_id']) {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role != 'siswa'");
            $stmt->execute([$id_hapus]);
            $_SESSION['msg'] = "Pengguna berhasil dihapus.";
        }
        header("Location: pengaturan.php?tab=akses"); exit();
    }

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

    if (isset($_GET['action']) && $_GET['action'] === 'set_aktif') {
        $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'] = "Periode aktif berhasil diubah.";
        header("Location: pengaturan.php?tab=tahun"); exit();
    }

} catch (PDOException $e) {
    $message = '<div class="alert alert-danger">Kesalahan Sistem: ' . $e->getMessage() . '</div>';
}

// Ambil Data 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();
$users = $pdo->query("SELECT * FROM users WHERE role != 'siswa' ORDER BY role ASC")->fetchAll();

include 'header.php';
?>

<div class="container-fluid mt-4">
    <?php if(isset($_SESSION['msg'])): ?>
        <div class="alert alert-success alert-dismissible fade show"><?= $_SESSION['msg']; unset($_SESSION['msg']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>
    <?php if(isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></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 == 'akses' ? 'active' : '' ?>" href="?tab=akses"><i class="bi bi-shield-lock"></i> Hak Akses</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</a>
        </div>
    </nav>

    <div class="tab-content content-card shadow-sm p-4 bg-white border border-top-0 rounded-bottom">
        
        <?php if($active_tab == 'identitas'): ?>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_identitas">
            <div class="row">
                <div class="col-md-3 text-center mb-3">
                    <label class="d-block mb-2">Logo Sekolah</label>
                    <?php if(!empty($pengaturan['logo_sekolah'])): ?>
                        <img src="../assets/img/<?= $pengaturan['logo_sekolah'] ?>" class="img-thumbnail mb-2" style="height: 120px;">
                    <?php else: ?>
                        <div class="bg-light border rounded mb-2 d-flex align-items-center justify-content-center" style="height: 120px;"><i class="bi bi-image text-muted" style="font-size: 3rem;"></i></div>
                    <?php endif; ?>
                    <input type="file" name="logo" class="form-control form-control-sm" accept="image/*">
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="form-label fw-bold">Nama Sekolah / Madrasah</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 class="form-label fw-bold">Nama Bendahara</label>
                            <input type="text" name="bendahara" class="form-control" value="<?= htmlspecialchars($pengaturan['bendahara']) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">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 class="form-label fw-bold">Alamat Lengkap</label>
                            <textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars($pengaturan['alamat']) ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <hr>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Simpan Identitas</button>
        </form>
        <?php endif; ?>

        <?php if($active_tab == 'akses'): ?>
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold"><i class="bi bi-people"></i> Pengelola Sistem (Admin & Operator)</h6>
            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalUser" onclick="resetUserForm()">Tambah User</button>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-bordered align-middle">
                <thead class="table-light small text-uppercase">
                    <tr><th>Nama Lengkap</th><th>Username</th><th>Role</th><th class="text-center">Aksi</th></tr>
                </thead>
                <tbody class="small">
                    <?php foreach($users as $u): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($u['nama_lengkap']) ?></strong></td>
                        <td><code><?= htmlspecialchars($u['username']) ?></code></td>
                        <td><span class="badge bg-<?= $u['role']=='admin'?'danger':'primary' ?>"><?= strtoupper($u['role']) ?></span></td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-outline-warning" onclick="editUser(<?= htmlspecialchars(json_encode($u)) ?>)"><i class="bi bi-pencil"></i></button>
                            <?php if($u['id'] != $_SESSION['user_id']): ?>
                                <button class="btn btn-sm btn-outline-danger" onclick="confirmDeleteUser(<?= $u['id'] ?>, '<?= $u['nama_lengkap'] ?>')"><i class="bi bi-trash"></i></button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <?php if($active_tab == 'tahun'): ?>
        <div class="d-flex justify-content-between mb-3">
            <h6 class="fw-bold">Periode Aktif Tabungan</h6>
            <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalTahun">Tambah Periode</button>
        </div>
        <table class="table table-bordered align-middle">
            <thead class="table-light small text-uppercase">
                <tr><th>Nama Periode</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-4 border-success h-100 shadow-sm">
                    <h6 class="fw-bold text-success"><i class="bi bi-download"></i> Backup Database</h6>
                    <p class="small text-muted">Amankan data tabungan Anda secara berkala. Seluruh tabel akan diunduh dalam format .SQL.</p>
                    <a href="backup_script.php" class="btn btn-success mt-auto">Unduh Backup (.sql)</a>
                </div>
            </div>
            <div class="col-md-6 mb-4">
                <div class="card p-4 border-danger h-100 shadow-sm">
                    <h6 class="fw-bold text-danger"><i class="bi bi-upload"></i> Restore Database</h6>
                    <p class="small text-muted">Gunakan file cadangan untuk memulihkan keadaan sistem. <br><strong>Peringatan:</strong> Semua data saat ini akan ditimpa!</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 w-100" onclick="return confirm('Apakah Anda yakin? Data saat ini akan hilang!')">Pulihkan Data</button>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="modalUser" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5 class="modal-title fw-bold" id="userModalTitle">Tambah Pengguna</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="id" id="user_id">
                <div class="mb-3"><label class="form-label">Nama Lengkap</label><input type="text" name="nama_lengkap" id="nama_lengkap" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Username</label><input type="text" name="username" id="username" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Password</label><input type="password" name="password" id="password" class="form-control" placeholder="Kosongkan jika tidak diganti"></div>
                <div class="mb-3" id="role_wrapper">
                    <label class="form-label">Hak Akses (Role)</label>
                    <select name="role" id="role" class="form-select"><option value="admin">Admin</option><option value="operator">Operator</option></select>
                </div>
            </div>
            <div class="modal-footer"><button type="submit" name="simpan_user" class="btn btn-primary">Simpan Data</button></div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalTahun" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <form class="modal-content" method="POST">
            <div class="modal-header"><h5>Tambah Periode</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 small">Nama Tahun (Contoh: 2025/2026)</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>

<form id="formDeleteUser" method="POST" style="display:none;">
    <input type="hidden" name="delete_user_id" id="delete_user_id">
</form>

<script>
function resetUserForm() {
    document.getElementById('user_id').value = '';
    document.getElementById('nama_lengkap').value = '';
    document.getElementById('username').value = '';
    document.getElementById('password').required = true;
    document.getElementById('userModalTitle').innerText = 'Tambah Pengguna';
    document.getElementById('role_wrapper').style.display = 'block';
}

function editUser(u) {
    document.getElementById('userModalTitle').innerText = 'Edit Pengguna';
    document.getElementById('user_id').value = u.id;
    document.getElementById('nama_lengkap').value = u.nama_lengkap;
    document.getElementById('username').value = u.username;
    document.getElementById('password').required = false;
    document.getElementById('role_wrapper').style.display = 'none'; // Role tidak diubah saat edit
    new bootstrap.Modal(document.getElementById('modalUser')).show();
}

function confirmDeleteUser(id, nama) {
    if (confirm('Hapus akun ' + nama + '?')) {
        document.getElementById('delete_user_id').value = id;
        document.getElementById('formDeleteUser').submit();
    }
}
</script>

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