<?php

$url = $_GET['url'] ?? '';

switch ($url) {

    /* ================= LOGIN GOOGLE ================= */
    case 'login-google':

        require __DIR__ . '/../app/config/google.php';

        $auth_url = "https://accounts.google.com/o/oauth2/v2/auth?" . http_build_query([
            'client_id' => $client_id,
            'redirect_uri' => $redirect_uri,
            'response_type' => 'code',
            'scope' => 'openid email profile',
            'access_type' => 'offline',
            'prompt' => 'select_account'
        ]);

        header("Location: $auth_url");
        exit;
        break;


    /* ================= GOOGLE CALLBACK ================= */
    case 'google-callback':

        require __DIR__ . '/../app/config/google.php';
        require __DIR__ . '/../app/config/database.php';

        session_start();

        if (!isset($_GET['code'])) {
            die("Tidak ada code!");
        }

        // ambil token
        $token_url = "https://oauth2.googleapis.com/token";

        $post = [
            'code' => $_GET['code'],
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'redirect_uri' => $redirect_uri,
            'grant_type' => 'authorization_code'
        ];

        $ch = curl_init($token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $response = curl_exec($ch);
        curl_close($ch);

        $token = json_decode($response, true);

        if (!isset($token['access_token'])) {
            die("Gagal ambil token");
        }

        // ambil user
        $user_info = file_get_contents(
            "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" . $token['access_token']
        );

        $user = json_decode($user_info, true);

        if (!isset($user['email'])) {
            die("Gagal ambil user");
        }

        $email = $user['email'];
        $name  = $user['name'];
        $google_id = $user['id'];

        // cek user
        $stmt = $conn->prepare("
                SELECT 
                    m.id, 
                    m.nama, 
                    m.email, 
                    m.status,
                    m.no_hp,
                    m.perusahaan,
                    m.foto,
                    r.nama_role
                FROM members m
                LEFT JOIN roles r ON m.role_id = r.id
                WHERE m.email=? OR m.google_id=?
            ");
            
            $stmt->bind_param("ss", $email, $google_id);
            $stmt->execute();
            
            $stmt->store_result();
            $stmt->bind_result(
                $id,
                $nama_db,
                $email_db,
                $status_db,
                $no_hp,
                $perusahaan,
                $foto,
                $role_db
            );
            
            if ($stmt->fetch()) {
            
                if ($status_db != 'Approved') {
                    session_destroy();
                    header("Location: /membership/waiting");
                    exit;
                }
            
                $_SESSION['user'] = [
                    'id' => $id,
                    'nama' => $nama_db,
                    'email' => $email_db,
                    'role' => $role_db,
                    'status' => $status_db,
            
                    // 🔥 TAMBAHAN
                    'no_hp' => $no_hp,
                    'perusahaan' => $perusahaan,
                    'foto' => $foto
                ];
            } else {

            // username unik
            $username = explode('@', $email)[0] . rand(100,999);

            $stmt = $conn->prepare("
                INSERT INTO members (nama, email, username, google_id, role_id, status)
                VALUES (?, ?, ?, ?, 5, 'Waiting')
            ");
            $stmt->bind_param("ssss", $name, $email, $username, $google_id);
            $stmt->execute();

            header("Location: /membership/waiting");
            exit;
        }

        $redirect = $_SESSION['redirect_after_login'] ?? '/membership/dashboard';
        unset($_SESSION['redirect_after_login']);
        
        header("Location: $redirect");
        exit;
        break;


    /* ================= LOGIN VIEW ================= */
    case 'login':
        require __DIR__ . '/../views/auth/login.php';
        break;


    /* ================= LOGIN PROCESS ================= */
    case 'login-process':

    require __DIR__ . '/../app/config/database.php';

    session_start();

    $email = $_POST['email'];
    $password = $_POST['password'];

    $stmt = $conn->prepare("
        SELECT 
            m.id, 
            m.nama, 
            m.email, 
            m.password, 
            m.status,
            m.no_hp,
            m.perusahaan,
            m.foto,
            r.nama_role
        FROM members m
        LEFT JOIN roles r ON m.role_id = r.id
        WHERE m.email=?
    ");

    $stmt->bind_param("s", $email);
    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result(
        $id, 
        $nama, 
        $email_db, 
        $password_db, 
        $status_db,
        $no_hp,
        $perusahaan,
        $foto,
        $role_db
    );

    if ($stmt->fetch()) {

        if (!password_verify($password, $password_db)) {
            die("Password salah!");
        }

        if ($status_db != 'Approved') {
            header("Location: /membership/waiting");
            exit;
        }

        $_SESSION['user'] = [
            'id' => $id,
            'nama' => $nama,
            'email' => $email_db,
            'role' => $role_db,
            'status' => $status_db,

            // 🔥 PENTING
            'no_hp' => $no_hp,
            'perusahaan' => $perusahaan,
            'foto' => $foto
        ];

        header("Location: /membership/dashboard");
        exit;

    } else {
        echo "Email tidak ditemukan!";
    }

    break;


  
/* ================= DASHBOARD ================= */
    case 'dashboard':

    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $role = $_SESSION['user']['role'];

    // =========================
    // 🔥 DASHBOARD SEKRETARIS
    // =========================
    if ($role == 'Sekretaris') {

        $q1 = $conn->query("SELECT COUNT(*) as total FROM members WHERE status='Waiting'");
        $waiting = $q1->fetch_assoc()['total'];

        $q2 = $conn->query("SELECT COUNT(*) as total FROM members WHERE status='Approved'");
        $active = $q2->fetch_assoc()['total'];

        $q3 = $conn->query("SELECT COUNT(*) as total FROM events");
        $event = $q3->fetch_assoc()['total'];

        require __DIR__ . '/../views/dashboard/sekretaris.php';

    // =========================
    // 🔥 DASHBOARD BENDAHARA
    // =========================
    } elseif ($role == 'Bendahara') {

        // total iuran (lunas saja)
        $q1 = $conn->query("SELECT SUM(jumlah) as total FROM iuran WHERE status='Lunas'");
        $iuran = $q1->fetch_assoc()['total'] ?? 0;

        // kas masuk vendor
        $q2 = $conn->query("SELECT SUM(jumlah) as total FROM kas_masuk");
        $kas_masuk = $q2->fetch_assoc()['total'] ?? 0;

        // pengeluaran
        $q3 = $conn->query("SELECT SUM(jumlah) as total FROM kas_keluar");
        $kas_keluar = $q3->fetch_assoc()['total'] ?? 0;

        // saldo
        $saldo = ($iuran + $kas_masuk) - $kas_keluar;

        require __DIR__ . '/../views/dashboard/bendahara.php';

    // =========================
    // 🔥 DEFAULT (MEMBER)
    // =========================
    } else {

        require __DIR__ . '/../views/dashboard/index.php';
    }

    break;

    /* ================= WAITING ================= */
    case 'waiting':
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Verifikasi Akun</title>
        <link rel="stylesheet" href="/membership/public/assets/css/style.css">
    </head>
    <body class="waiting-page">
    
    <div class="waiting-box">
        <div class="waiting-icon">⏳</div>
    
        <h2>Akun Sedang Diverifikasi</h2>
        <p>Admin sedang meninjau akun Anda.<br>Silakan tunggu beberapa saat.</p>
        <script>
            setTimeout(() => {
                window.location.href = "/membership/login";
            }, 5000);
        </script>
    
        <a href="/membership/login" class="btn-back">Kembali ke Login</a>
    </div>
    
    </body>
    </html>
    <?php
    break;
    
    case 'profile':

    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_SESSION['user']['id'];

    $stmt = $conn->prepare("
        SELECT nama, email, jabatan, no_hp, perusahaan, foto
        FROM members
        WHERE id=?
    ");

    $stmt->bind_param("i", $id);
    $stmt->execute();

    $stmt->bind_result($nama, $email, $jabatan, $no_hp, $perusahaan, $foto);
    $stmt->fetch();

    require __DIR__ . '/../views/member/profile.php';
    break;


    /* ================= LOGOUT ================= */
    case 'logout':

        session_start();
        session_destroy();

        header("Location: /membership/login");
        exit;
        break;
        case 'profile':
    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_SESSION['user']['id'];

    $stmt = $conn->prepare("SELECT * FROM members WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result(
        $id,
        $nomor,
        $nama,
        $jabatan,
        $no_hp,
        $perusahaan,
        $email,
        $username,
        $password,
        $foto,
        $status,
        $created,
        $google_id,
        $role_id
    );

    $stmt->fetch();

    require __DIR__ . '/../views/member/profile.php';
    break;
    
    case 'profile-update':

    session_start();
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    $id = $_SESSION['user']['id'];
    
    $nama       = $_POST['nama'] ?? '';
    $jabatan    = $_POST['jabatan'] ?? '';
    $no_hp      = $_POST['no_hp'] ?? '';
    $perusahaan = $_POST['perusahaan'] ?? '';
    
    $foto = $_SESSION['user']['foto'] ?? null;
    
    // =========================
    // HANDLE CROPPED IMAGE
    // =========================
    if (!empty($_POST['cropped_image'])) {
    
        $image = $_POST['cropped_image'];
    
        $image = str_replace('data:image/jpeg;base64,', '', $image);
        $image = str_replace(' ', '+', $image);
    
        $data = base64_decode($image);
    
        $namaFile = time() . '_profile.jpg';
        $path = __DIR__ . '/../public/assets/uploads/' . $namaFile;
    
        file_put_contents($path, $data);
    
        $foto = $namaFile;
    }
    
    // =========================
    // UPDATE DATABASE
    // =========================
    $stmt = $conn->prepare("
        UPDATE members 
        SET nama=?, jabatan=?, no_hp=?, perusahaan=?, foto=? 
        WHERE id=?
    ");
    
    $stmt->bind_param("sssssi", $nama, $jabatan, $no_hp, $perusahaan, $foto, $id);
    $stmt->execute();
    
    // =========================
    // UPDATE SESSION
    // =========================
    $_SESSION['user']['nama'] = $nama;
    $_SESSION['user']['jabatan'] = $jabatan;
    $_SESSION['user']['no_hp'] = $no_hp;
    $_SESSION['user']['perusahaan'] = $perusahaan;
    $_SESSION['user']['foto'] = $foto;
    
    header("Location: /membership/profile");
    exit;
    
    break;
    case 'iuran':

    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_SESSION['user']['id'];

    $stmt = $conn->prepare("
        SELECT bulan, tahun, jumlah, tanggal_bayar, status, bukti_bayar
        FROM iuran
        WHERE member_id=?
        ORDER BY tahun DESC, bulan DESC
    ");

    $stmt->bind_param("i", $id);
    $stmt->execute();

    $stmt->bind_result($bulan, $tahun, $jumlah, $tanggal_bayar, $status, $bukti);

    $data = [];

    while ($stmt->fetch()) {
        $data[] = [
            'bulan' => $bulan,
            'tahun' => $tahun,
            'jumlah' => $jumlah,
            'tanggal' => $tanggal_bayar,
            'status' => $status,
            'bukti' => $bukti
        ];
    }

    require __DIR__ . '/../views/member/iuran.php';
    break;
    
    case 'iuran-upload':

    session_start();
    

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_SESSION['user']['id'];

    // =========================
    // 🔥 AMBIL INPUT
    // =========================
    $tanggal = $_POST['tanggal_bayar'] ?? '';
    $jumlah  = $_POST['jumlah'] ?? 0;

    if (empty($tanggal) || empty($jumlah)) {
        die("Data tidak lengkap");
    }

    // ambil bulan & tahun otomatis
    $bulan = date('F', strtotime($tanggal)); // contoh: April
    $tahun = date('Y', strtotime($tanggal)); // contoh: 2026

    // =========================
    // 🔥 CEK DUPLIKASI (ANTI BAYAR 2x)
    // =========================
    $cek = $conn->prepare("
        SELECT id FROM iuran 
        WHERE member_id=? AND bulan=? AND tahun=?
    ");
    $cek->bind_param("iss", $id, $bulan, $tahun);
    $cek->execute();
    $cek->store_result();

    if ($cek->num_rows > 0) {
        die("Iuran bulan ini sudah ada!");
    }

    // =========================
    // 🔥 UPLOAD FILE
    // =========================
    if (!isset($_FILES['bukti']) || $_FILES['bukti']['error'] != 0) {
        die("Upload bukti gagal");
    }

    $file = $_FILES['bukti'];

    // validasi tipe file
    $allowed = ['jpg', 'jpeg', 'png'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed)) {
        die("Format file harus JPG / PNG");
    }

    // validasi ukuran (max 2MB)
    if ($file['size'] > 2 * 1024 * 1024) {
        die("Ukuran file maksimal 2MB");
    }

    // nama file unik
    $namaFile = time() . '_' . rand(100,999) . '.' . $ext;

    $uploadPath = __DIR__ . '/../public/assets/uploads/' . $namaFile;

    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        die("Gagal upload file");
    }

    // =========================
    // 🔥 INSERT DATABASE
    // =========================
    $stmt = $conn->prepare("
        INSERT INTO iuran 
        (member_id, bulan, tahun, jumlah, tanggal_bayar, bukti_bayar, status)
        VALUES (?, ?, ?, ?, ?, ?, 'Menunggu Verifikasi')
    ");

    $stmt->bind_param("ississ", $id, $bulan, $tahun, $jumlah, $tanggal, $namaFile);
    $stmt->execute();

    // =========================
    // 🔥 REDIRECT
    // =========================
    header("Location: /membership/iuran");
    exit;

    break;
    
    case 'members':
    
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    $result = $conn->query("
        SELECT 
            m.nama, 
            m.email, 
            m.no_hp,
            m.perusahaan, 
            m.foto,
            IFNULL(r.nama_role, '-') as nama_role
        FROM members m
        LEFT JOIN roles r ON m.role_id = r.id
        WHERE m.status='Approved'
        ORDER BY 
            CASE 
                WHEN LOWER(r.nama_role) = 'ketua' THEN 1
                WHEN LOWER(r.nama_role) = 'sekretaris' THEN 2
                WHEN LOWER(r.nama_role) = 'bendahara' THEN 3
                ELSE 4
            END,
            m.nama ASC
    ");
    
    $members = [];
    
    while ($row = $result->fetch_assoc()) {
        $members[] = $row;
    }
    
    require __DIR__ . '/../views/member/members.php';
    break;
    
    case 'jobs':

    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $result = $conn->query("
        SELECT * FROM jobs 
        ORDER BY created_at DESC
    ");

    $jobs = [];

    while ($row = $result->fetch_assoc()) {
        $jobs[] = $row;
    }

    require __DIR__ . '/../views/member/jobs.php';
    break;
    
    case 'event':

    session_start();

    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }

    require __DIR__ . '/../app/config/database.php';

    $result = $conn->query("
        SELECT * FROM events 
        ORDER BY tanggal DESC
    ");

    $events = [];

    while ($row = $result->fetch_assoc()) {
        $events[] = $row;
    }

    require __DIR__ . '/../views/member/event.php';
    break;
    
    case 'approve-member':

    session_start();
    
    if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    /* =========================
       🔥 MEMBER PENDING
    ========================= */
    $q1 = $conn->query("
        SELECT id, nama, email, perusahaan, created_at
        FROM members
        WHERE status='Waiting'
        ORDER BY created_at DESC
    ");
    
    $members_pending = [];
    
    while ($row = $q1->fetch_assoc()) {
        $members_pending[] = $row;
    }
    
    
    /* =========================
       🔥 MEMBER APPROVED
    ========================= */
    $q2 = $conn->query("
        SELECT id, nama, email, perusahaan, no_hp
        FROM members
        WHERE status='Approved'
        ORDER BY nama ASC
    ");
    
    $members_approved = [];
    
    while ($row = $q2->fetch_assoc()) {
        $members_approved[] = $row;
    }
    
    
    /* =========================
       🔥 LOAD VIEW
    ========================= */
    require __DIR__ . '/../views/sekretaris/approve_member.php';
    break;
    
    case 'approve-member-action':

    session_start();

    if ($_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("
        UPDATE members 
        SET status='Approved'
        WHERE id=?
    ");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: /membership/approve-member");
    exit;
    
    case 'reject-member-action':

    session_start();

    if ($_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("
        UPDATE members 
        SET status='Rejected'
        WHERE id=?
    ");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: /membership/approve-member");
    exit;
    
    case 'event-create':

    session_start();

    if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    // ambil semua event
    $result = $conn->query("SELECT * FROM events ORDER BY tanggal DESC");

    $events = [];

    while ($row = $result->fetch_assoc()) {
        $events[] = $row;
    }

    require __DIR__ . '/../views/sekretaris/event_create.php';
    break;
    
    case 'event-edit':

    session_start();

    if ($_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("SELECT * FROM events WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $result = $stmt->get_result();
    $event = $result->fetch_assoc();

    require __DIR__ . '/../views/sekretaris/event_edit.php';
    break;
    
    case 'event-delete':

    session_start();

    if ($_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("DELETE FROM events WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: /membership/event-create");
    exit;
    
    case 'event-store':

    session_start();

    if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $nama       = $_POST['nama_event'] ?? '';
    $deskripsi  = $_POST['deskripsi'] ?? '';
    $tanggal    = $_POST['tanggal'] ?? '';
    $lokasi     = $_POST['lokasi'] ?? '';

    if (!$nama || !$tanggal || !$lokasi) {
        die("Data tidak lengkap");
    }

    $fotoName = null;

    if (!empty($_FILES['foto']['name'])) {

        if ($_FILES['foto']['error'] !== 0) {
            die("Upload gambar error");
        }

        $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));

        $allowed = ['jpg','jpeg','png'];

        if (!in_array($ext, $allowed)) {
            die("Format gambar harus JPG/PNG");
        }

        $fotoName = time() . '_' . rand(100,999) . '.' . $ext;

        $uploadPath = __DIR__ . '/../public/assets/uploads/' . $fotoName;

        if (!move_uploaded_file($_FILES['foto']['tmp_name'], $uploadPath)) {
            die("Gagal upload gambar");
        }
    }

    $stmt = $conn->prepare("
        INSERT INTO events (nama_event, deskripsi, tanggal, lokasi, foto)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->bind_param("sssss", $nama, $deskripsi, $tanggal, $lokasi, $fotoName);

    if (!$stmt->execute()) {
        die("DB ERROR: " . $stmt->error);
    }

    header("Location: /membership/event-create");
    exit;
    
    case 'lowongan':

    session_start();

    if ($_SESSION['user']['role'] != 'Sekretaris') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $result = $conn->query("SELECT * FROM lowongan ORDER BY id DESC");

    $data = [];

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    require __DIR__ . '/../views/sekretaris/lowongan.php';
    break;
    
    case 'lowongan-store':

    session_start();
    require __DIR__ . '/../app/config/database.php';

    $judul = $_POST['judul'];
    $perusahaan = $_POST['perusahaan'];
    $lokasi = $_POST['lokasi'];
    $deskripsi = $_POST['deskripsi'];
    $deadline = $_POST['deadline'];

    $stmt = $conn->prepare("
        INSERT INTO lowongan (judul, perusahaan, lokasi, deskripsi, deadline)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->bind_param("sssss", $judul, $perusahaan, $lokasi, $deskripsi, $deadline);
    $stmt->execute();

    header("Location: /membership/lowongan");
    exit;
    
    case 'lowongan-delete':

    session_start();
    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("DELETE FROM lowongan WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: /membership/lowongan");
    exit;
    
    case 'bendahara':

    session_start();

    if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    // total iuran
    $q1 = $conn->query("SELECT SUM(jumlah) as total FROM iuran WHERE status='Lunas'");
    $total_iuran = $q1->fetch_assoc()['total'] ?? 0;

    // kas vendor
    $q2 = $conn->query("SELECT SUM(jumlah) as total FROM kas_masuk");
    $total_vendor = $q2->fetch_assoc()['total'] ?? 0;

    // pengeluaran
    $q3 = $conn->query("SELECT SUM(jumlah) as total FROM kas_keluar");
    $total_keluar = $q3->fetch_assoc()['total'] ?? 0;

    // saldo
    $saldo = ($total_iuran + $total_vendor) - $total_keluar;

    // kirim data ke view (tanpa ubah struktur)
    $stats = [
        'iuran' => $total_iuran,
        'vendor' => $total_vendor,
        'keluar' => $total_keluar,
        'saldo' => $saldo
    ];

    require __DIR__ . '/../views/dashboard/bendahara.php';
    break;
    
    case 'iuran-list':

    // =========================
    // SESSION
    // =========================
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    // =========================
    // VALIDASI LOGIN
    // =========================
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    // =========================
    // VALIDASI ROLE
    // =========================
    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }
    
    // =========================
    // DATABASE
    // =========================
    require __DIR__ . '/../app/config/database.php';
    
    // =========================
    // DATA IURAN
    // =========================
    $data = [];
    
   $query = $conn->query("
        SELECT 
            i.id,
            m.id as member_id,
            i.bulan,
            i.tahun,
            i.jumlah,
            i.tanggal_bayar,
            i.bukti_bayar,
            i.status,
            i.created_at,
            m.nama,
            m.created_at AS member_created_at
        FROM members m
        LEFT JOIN iuran i ON m.id = i.member_id
        WHERE m.status='Approved'
        ORDER BY m.nama ASC
    ");
    
    // =========================
    // ERROR HANDLE
    // =========================
    if (!$query) {
        die("Query error: " . $conn->error);
    }
    
    // =========================
    // LOOP DATA
    // =========================
    while ($row = $query->fetch_assoc()) {
    
        // 🔥 JAGA-JAGA BIAR TIDAK ERROR DI VIEW
        if (empty($row['member_created_at'])) {
            $row['member_created_at'] = date('Y-m-01');
        }
    
        $data[] = $row;
    }
    
    // =========================
    // LOAD VIEW
    // =========================
    require __DIR__ . '/../views/bendahara/iuran.php';
    
    break;
    
    case 'iuran-approve':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    if (!isset($_GET['id'])) {
        die("ID tidak ditemukan");
    }
    
    $id = (int) $_GET['id'];
    
    $stmt = $conn->prepare("UPDATE iuran SET status='Lunas' WHERE id=?");
    
    if (!$stmt) {
        die("Prepare gagal: " . $conn->error);
    }
    
    $stmt->bind_param("i", $id);
    
    if (!$stmt->execute()) {
        die("Execute gagal: " . $stmt->error);
    }
    
    header("Location: /membership/iuran-list?tab=approve");
    exit;
    
    break;
    
    case 'iuran-reject':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    if (!isset($_GET['id'])) {
        die("ID tidak ditemukan");
    }
    
    $id = (int) $_GET['id'];
    
    $stmt = $conn->prepare("UPDATE iuran SET status='Belum Bayar' WHERE id=?");
    
    if (!$stmt) {
        die("Prepare gagal: " . $conn->error);
    }
    
    $stmt->bind_param("i", $id);
    
    if (!$stmt->execute()) {
        die("Execute gagal: " . $stmt->error);
    }
    
    header("Location: /membership/iuran-list?tab=approve");
    exit;
    
    break;
    
    case 'iuran-reminder':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    require __DIR__ . '/../app/config/mail.php';
    
    // =========================
    // BULAN SEKARANG
    // =========================
    $bulan = date('F');
    $tahun = date('Y');
    
    // =========================
    // AMBIL MEMBER BELUM BAYAR
    // =========================
    $result = $conn->query("
        SELECT m.id, m.email, m.nama
        FROM members m
        LEFT JOIN iuran i 
            ON m.id = i.member_id 
            AND i.bulan = '$bulan' 
            AND i.tahun = '$tahun'
            AND i.status = 'Lunas'
        WHERE m.status='Approved'
        AND i.id IS NULL
    ");
    
    $berhasil = 0;
    $gagal = 0;
    
    // =========================
    // LOOP KIRIM EMAIL
    // =========================
    while ($row = $result->fetch_assoc()) {
    
        $email = $row['email'];
        $nama  = $row['nama'];
    
        $subject = "Reminder Iuran $bulan $tahun";
    
        $message = '
            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="UTF-8">
            </head>
            <body style="margin:0; padding:0; background:#f4f6f8; font-family:Arial, sans-serif;">
            
            <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f8; padding:20px 0;">
            <tr>
            <td align="center">
            
                <table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff; border-radius:10px; overflow:hidden; box-shadow:0 4px 10px rgba(0,0,0,0.05);">
            
                    <!-- HEADER -->
                    <tr>
                        <td style="background:#0d6efd; padding:20px; text-align:center;">
                            <img src="https://hitasumut.org/membership/public/assets/img/logo.png" alt="HITA SUMUT" width="120" style="margin-bottom:10px;">
                            <h2 style="color:#ffffff; margin:0;">HITA SUMUT</h2>
                        </td>
                    </tr>
            
                    <!-- CONTENT -->
                    <tr>
                        <td style="padding:30px;">
                            <p style="font-size:16px;">Halo <b>'.$nama.'</b>,</p>
            
                            <p style="font-size:15px; line-height:1.6;">
                                Kami ingin mengingatkan bahwa hingga saat ini Anda <b>belum melakukan pembayaran iuran</b> untuk periode:
                            </p>
            
                            <div style="background:#f8f9fa; padding:15px; border-radius:8px; text-align:center; margin:20px 0;">
                                <h3 style="margin:0; color:#dc3545;">'.$bulan.' '.$tahun.'</h3>
                            </div>
            
                            <p style="font-size:15px; line-height:1.6;">
                                Kami mohon kesediaan Anda untuk segera melakukan pembayaran iuran guna mendukung kelancaran kegiatan organisasi.
                            </p>
            
                            <!-- BUTTON -->
                            <div style="text-align:center; margin:30px 0;">
                                <a href="https://hitasumut.org/membership/iuran" 
                                   style="background:#0d6efd; color:#ffffff; padding:12px 25px; text-decoration:none; border-radius:6px; font-size:14px;">
                                   Bayar Sekarang
                                </a>
                            </div>
            
                            <p style="font-size:14px; color:#555;">
                                Jika Anda sudah melakukan pembayaran, silakan abaikan email ini.
                            </p>
            
                            <p style="margin-top:30px; font-size:14px;">
                                Hormat kami,<br>
                                <b>Bendahara HITA SUMUT</b>
                            </p>
                        </td>
                    </tr>
            
                    <!-- FOOTER -->
                    <tr>
                        <td style="background:#f1f1f1; padding:15px; text-align:center; font-size:12px; color:#777;">
                            © '.date('Y').' HITA SUMUT<br>
                            Email ini dikirim otomatis oleh sistem.
                        </td>
                    </tr>
            
                </table>
            
            </td>
            </tr>
            </table>
            
            </body>
            </html>
            ';
    
        $kirim = kirimEmail($email, $nama, $subject, $message);
    
        if ($kirim) {
            $berhasil++;
    
            $conn->query("
                INSERT INTO reminder_log (member_id, jenis, tanggal_kirim, status)
                VALUES ({$row['id']}, 'Reminder Bulanan', NOW(), 'Berhasil')
            ");
    
        } else {
            $gagal++;
    
            $conn->query("
                INSERT INTO reminder_log (member_id, jenis, tanggal_kirim, status)
                VALUES ({$row['id']}, 'Reminder Bulanan', NOW(), 'Gagal')
            ");
        }
    }
    
    header("Location: /membership/iuran-list?tab=tunggakan&ok=$berhasil&fail=$gagal");
    exit;
    
    break;

    
    case 'kas-masuk':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $result = $conn->query("SELECT * FROM kas_masuk ORDER BY tanggal DESC");

    $data = [];

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    require __DIR__ . '/../views/bendahara/kas_masuk.php';
    break;
    
    case 'kas-masuk-store':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    require __DIR__ . '/../app/config/database.php';

    $jumlah = $_POST['jumlah'];
    $keterangan = $_POST['keterangan'];
    $tanggal = $_POST['tanggal'];

    if (!$jumlah || !$tanggal) {
        die("Data tidak lengkap");
    }

    $stmt = $conn->prepare("
        INSERT INTO kas_masuk (jumlah, keterangan, tanggal)
        VALUES (?, ?, ?)
    ");

    $stmt->bind_param("iss", $jumlah, $keterangan, $tanggal);
    $stmt->execute();

    header("Location: /membership/kas-masuk");
    exit;
    
    case 'kas-masuk-delete':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    require __DIR__ . '/../app/config/database.php';

    $id = $_GET['id'];

    $stmt = $conn->prepare("DELETE FROM kas_masuk WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: /membership/kas-masuk");
    exit;
    
    case 'kas-keluar':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }

    require __DIR__ . '/../app/config/database.php';

    $result = $conn->query("SELECT * FROM kas_keluar ORDER BY tanggal DESC");

    $data = [];

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    require __DIR__ . '/../views/bendahara/kas_keluar.php';
    break;
    
    case 'kas-keluar-store':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    require __DIR__ . '/../app/config/database.php';

    $jumlah = $_POST['jumlah'];
    $tanggal = $_POST['tanggal'];
    $keterangan = $_POST['keterangan'];
    $sumber = $_POST['sumber_dana'];

    if (!$jumlah || !$tanggal || !$sumber) {
        die("Data tidak lengkap");
    }

    // =========================
    // VALIDASI SALDO
    // =========================
    if ($sumber == 'iuran') {

        $q = $conn->query("SELECT SUM(jumlah) as total FROM iuran WHERE status='Lunas'");
        $total = $q->fetch_assoc()['total'] ?? 0;

    } else {

        $q = $conn->query("SELECT SUM(jumlah) as total FROM kas_masuk");
        $total = $q->fetch_assoc()['total'] ?? 0;
    }

    $q2 = $conn->query("
        SELECT SUM(jumlah) as total 
        FROM kas_keluar 
        WHERE sumber_dana='$sumber'
    ");
    $terpakai = $q2->fetch_assoc()['total'] ?? 0;

    $saldo = $total - $terpakai;

    if ($jumlah > $saldo) {
        die("Saldo tidak cukup!");
    }

    // =========================
    // UPLOAD FOTO
    // =========================
    $fotoName = null;

    if (!empty($_FILES['foto']['name'])) {

        if ($_FILES['foto']['error'] !== 0) {
            die("Upload foto gagal");
        }

        $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png'];

        if (!in_array($ext, $allowed)) {
            die("Format harus JPG/PNG");
        }

        $fotoName = time() . '_' . rand(100,999) . '.' . $ext;

        $path = __DIR__ . '/../public/assets/uploads/' . $fotoName;

        if (!move_uploaded_file($_FILES['foto']['tmp_name'], $path)) {
            die("Gagal upload foto");
        }
    }

    // =========================
    // INSERT
    // =========================
    $stmt = $conn->prepare("
        INSERT INTO kas_keluar (keterangan, jumlah, sumber_dana, tanggal, foto)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->bind_param("sisss", $keterangan, $jumlah, $sumber, $tanggal, $fotoName);
    $stmt->execute();

    header("Location: /membership/kas-keluar");
    exit;
   
   case 'kas-keluar-delete':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    require __DIR__ . '/../app/config/database.php';

    if (!isset($_GET['id'])) {
        die("ID tidak ditemukan");
    }

    $id = $_GET['id'];

    // OPTIONAL: hapus file foto juga
    $q = $conn->query("SELECT foto FROM kas_keluar WHERE id=$id");
    $data = $q->fetch_assoc();

    if ($data && $data['foto']) {
        $file = __DIR__ . '/../public/assets/uploads/' . $data['foto'];
        if (file_exists($file)) {
            unlink($file);
        }
    }

    // delete data
    $stmt = $conn->prepare("DELETE FROM kas_keluar WHERE id=?");
    $stmt->bind_param("i", $id);

    if (!$stmt->execute()) {
        die("Gagal delete: " . $stmt->error);
    }

    header("Location: /membership/kas-keluar");
    exit;

    break; 
    
    case 'laporan':
    
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    if (strtolower(trim($_SESSION['user']['role'])) != 'bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    // =========================
    // MODE
    // =========================
    $mode = $_GET['mode'] ?? 'bulanan';
    
    $bulan = date('m');
    $tahun = date('Y');
    
    if (isset($_GET['bulan_tahun'])) {
        $split = explode('-', $_GET['bulan_tahun']);
        $tahun = $split[0];
        $bulan = $split[1];
    }
    
    if (isset($_GET['tahun'])) {
        $tahun = $_GET['tahun'];
    }
    
    // =========================
    // SUMMARY IURAN
    // =========================
    if ($mode == 'bulanan') {
    
        $q1 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM iuran 
            WHERE status='Lunas'
            AND MONTH(tanggal_bayar) = '$bulan'
            AND YEAR(tanggal_bayar) = '$tahun'
        ");
    
       $q2 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_keluar 
            WHERE sumber_dana='iuran'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
        ");
        
        } else {
        
        $q1 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM iuran 
            WHERE status='Lunas'
            AND YEAR(tanggal_bayar) = '$tahun'
        ");
        
        $q2 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_keluar 
            WHERE sumber_dana='iuran'
            AND YEAR(tanggal) = '$tahun'
        ");
        }
    
    $iuran_masuk = $q1->fetch_assoc()['total'] ?? 0;
    $iuran_keluar = $q2->fetch_assoc()['total'] ?? 0;
    $saldo_iuran = $iuran_masuk - $iuran_keluar;
    
    
    // =========================
    // SUMMARY VENDOR
    // =========================
    if ($mode == 'bulanan') {
    
        $q3 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_masuk 
            WHERE MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
        ");
    
        $q4 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_keluar 
            WHERE sumber_dana='kas_vendor'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
        ");
    
    } else {
    
        $q3 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_masuk 
            WHERE YEAR(tanggal) = '$tahun'
        ");
    
        $q4 = $conn->query("
            SELECT SUM(jumlah) as total 
            FROM kas_keluar 
            WHERE sumber_dana='kas_vendor'
            AND YEAR(tanggal) = '$tahun'
        ");
    }
    
    $vendor_masuk = $q3->fetch_assoc()['total'] ?? 0;
    $vendor_keluar = $q4->fetch_assoc()['total'] ?? 0;
    $saldo_vendor = $vendor_masuk - $vendor_keluar;
    
    
    // =========================
    // DETAIL IURAN
    // =========================
    $data_iuran = [];
    
    if ($mode == 'bulanan') {
    
        $q_iuran = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal_bayar as tanggal, '-' as keterangan
            FROM iuran
            WHERE status='Lunas'
            AND MONTH(tanggal_bayar) = '$bulan'
            AND YEAR(tanggal_bayar) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, IFNULL(keterangan,'-')
            FROM kas_keluar
            WHERE sumber_dana='iuran'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal DESC
        ");
    
    } else {
    
        $q_iuran = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal_bayar as tanggal, '-' as keterangan
            FROM iuran
            WHERE status='Lunas'
            AND YEAR(tanggal_bayar) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, IFNULL(keterangan,'-')
            FROM kas_keluar
            WHERE sumber_dana='iuran'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal DESC
        ");
    }
    
    while ($row = $q_iuran->fetch_assoc()) {
        $data_iuran[] = $row;
    }
    
    
    // =========================
    // DETAIL VENDOR
    // =========================
    $data_vendor = [];
    
    if ($mode == 'bulanan') {
    
        $q_vendor = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal, IFNULL(keterangan,'-') as keterangan
            FROM kas_masuk
            WHERE MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, IFNULL(keterangan,'-')
            FROM kas_keluar
            WHERE sumber_dana='kas_vendor'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal DESC
        ");
    
    } else {
    
        $q_vendor = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal, IFNULL(keterangan,'-') as keterangan
            FROM kas_masuk
            WHERE YEAR(tanggal) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, IFNULL(keterangan,'-')
            FROM kas_keluar
            WHERE sumber_dana='kas_vendor'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal DESC
        ");
    }
    
    while ($row = $q_vendor->fetch_assoc()) {
        $data_vendor[] = $row;
    }
    
    
    // =========================
    // LOAD VIEW
    // =========================
    require __DIR__ . '/../views/bendahara/laporan.php';
    break;
    
    case 'laporan-pdf-iuran':
    
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (strtolower(trim($_SESSION['user']['role'])) != 'bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    require __DIR__ . '/../public/assets/lib/fpdf/fpdf.php';
    
    // ================= FILTER =================
    $mode = $_GET['mode'] ?? 'bulanan';
    
    $bulan = date('m');
    $tahun = date('Y');
    
    if (isset($_GET['bulan_tahun'])) {
        $split = explode('-', $_GET['bulan_tahun']);
        $tahun = $split[0];
        $bulan = $split[1];
    }
    
    if (isset($_GET['tahun'])) {
        $tahun = $_GET['tahun'];
    }
    
    // ================= DATA =================
    $data = [];
    
    if ($mode == 'bulanan') {
    
        $q = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal_bayar as tanggal, 
            IFNULL(keterangan,'-') as keterangan
            FROM iuran
            WHERE status='Lunas'
            AND MONTH(tanggal_bayar) = '$bulan'
            AND YEAR(tanggal_bayar) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, keterangan
            FROM kas_keluar
            WHERE sumber_dana='iuran'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal ASC
        ");
    
    } else {
    
        $q = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal_bayar as tanggal, '-' as keterangan
            FROM iuran
            WHERE status='Lunas'
            AND YEAR(tanggal_bayar) = '$tahun'
        
            UNION ALL
        
            SELECT 'Keluar', jumlah, tanggal, IFNULL(keterangan,'-')
            FROM kas_keluar
            WHERE sumber_dana='iuran'
            AND YEAR(tanggal) = '$tahun'
        
            ORDER BY tanggal ASC
        ");
    }
    
    while ($row = $q->fetch_assoc()) {
        $data[] = $row;
    }
    
    // ================= PDF =================
    $pdf = new FPDF();
    $pdf->AddPage();
    
    // HEADER
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(0,8,'HITA SUMUT',0,1,'C');
    
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(0,6,'Laporan Keuangan Iuran',0,1,'C');
    $pdf->Cell(0,6,"Periode: $mode - $bulan/$tahun",0,1,'C');
    
    $pdf->Ln(3);
    $pdf->Line(10,30,200,30);
    $pdf->Ln(5);
    
    // TABLE HEADER
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(10,8,'No',1);
    $pdf->Cell(30,8,'Tanggal',1);
    $pdf->Cell(30,8,'Jenis',1);
    $pdf->Cell(80,8,'Keterangan',1);
    $pdf->Cell(40,8,'Jumlah',1);
    $pdf->Ln();
    
    // TABLE DATA
    $pdf->SetFont('Arial','',10);
    
    $no = 1;
    $total = 0;
    
    foreach ($data as $row) {
    
        $pdf->Cell(10,8,$no++,1);
        $pdf->Cell(30,8,$row['tanggal'],1);
        $pdf->Cell(30,8,$row['jenis'],1);
        $pdf->Cell(80,8,$row['keterangan'],1);
        $pdf->Cell(40,8,'Rp '.number_format($row['jumlah']),1,0,'R');
        $pdf->Ln();
    
        if ($row['jenis']=='Keluar') {
            $total -= $row['jumlah'];
        } else {
            $total += $row['jumlah'];
        }
    }
    
    // TOTAL
    $pdf->Ln(5);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(0,10,'Total Saldo Iuran: Rp '.number_format($total),0,1,'R');
    
    // TTD
    $pdf->Ln(10);
    $pdf->Cell(0,6,'Mengetahui,',0,1,'R');
    $pdf->Ln(15);
    $pdf->Cell(0,6,'Bendahara',0,1,'R');
    
    $pdf->Output();
    exit;
    
    case 'laporan-pdf-vendor':
    
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (strtolower(trim($_SESSION['user']['role'])) != 'bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    require __DIR__ . '/../public/assets/lib/fpdf/fpdf.php';
    
    // ================= FILTER =================
    $mode = $_GET['mode'] ?? 'bulanan';
    
    $bulan = date('m');
    $tahun = date('Y');
    
    if (isset($_GET['bulan_tahun'])) {
        $split = explode('-', $_GET['bulan_tahun']);
        $tahun = $split[0];
        $bulan = $split[1];
    }
    
    if (isset($_GET['tahun'])) {
        $tahun = $_GET['tahun'];
    }
    
    // ================= DATA =================
    $data = [];
    
    if ($mode == 'bulanan') {
    
        $q = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal, keterangan
            FROM kas_masuk
            WHERE MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, keterangan
            FROM kas_keluar
            WHERE sumber_dana='kas_vendor'
            AND MONTH(tanggal) = '$bulan'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal ASC
        ");
    
    } else {
    
        $q = $conn->query("
            SELECT 'Masuk' as jenis, jumlah, tanggal, keterangan
            FROM kas_masuk
            WHERE YEAR(tanggal) = '$tahun'
    
            UNION ALL
    
            SELECT 'Keluar', jumlah, tanggal, keterangan
            FROM kas_keluar
            WHERE sumber_dana='kas_vendor'
            AND YEAR(tanggal) = '$tahun'
    
            ORDER BY tanggal ASC
        ");
    }
    
    while ($row = $q->fetch_assoc()) {
        $data[] = $row;
    }
    
    // ================= PDF =================
    $pdf = new FPDF();
    $pdf->AddPage();
    
    // HEADER
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(0,8,'HITA SUMUT',0,1,'C');
    
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(0,6,'Laporan Keuangan Vendor',0,1,'C');
    $pdf->Cell(0,6,"Periode: $mode - $bulan/$tahun",0,1,'C');
    
    $pdf->Ln(3);
    $pdf->Line(10,30,200,30);
    $pdf->Ln(5);
    
    // TABLE
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell(10,8,'No',1);
    $pdf->Cell(30,8,'Tanggal',1);
    $pdf->Cell(30,8,'Jenis',1);
    $pdf->Cell(80,8,'Keterangan',1);
    $pdf->Cell(40,8,'Jumlah',1);
    $pdf->Ln();
    
    $pdf->SetFont('Arial','',10);
    
    $no = 1;
    $total = 0;
    
    foreach ($data as $row) {
    
        $pdf->Cell(10,8,$no++,1);
        $pdf->Cell(30,8,$row['tanggal'],1);
        $pdf->Cell(30,8,$row['jenis'],1);
        $pdf->Cell(80,8,$row['keterangan'],1);
        $pdf->Cell(40,8,'Rp '.number_format($row['jumlah']),1,0,'R');
        $pdf->Ln();
    
        if ($row['jenis']=='Keluar') {
            $total -= $row['jumlah'];
        } else {
            $total += $row['jumlah'];
        }
    }
    
    // TOTAL
    $pdf->Ln(5);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(0,10,'Total Saldo Vendor: Rp '.number_format($total),0,1,'R');
    
    // TTD
    $pdf->Ln(10);
    $pdf->Cell(0,6,'Mengetahui,',0,1,'R');
    $pdf->Ln(15);
    $pdf->Cell(0,6,'Bendahara',0,1,'R');
    
    $pdf->Output();
    exit;
    
    case 'kas-masuk-edit':

    // WAJIB paling atas (sebelum apapun)
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    
    // DEBUG (sementara)
    if (!isset($_SESSION['user'])) {
        die("SESSION HILANG");
    }
    
    // VALIDASI ROLE
    if (strtolower(trim($_SESSION['user']['role'])) != 'bendahara') {
        die("Bukan bendahara: " . $_SESSION['user']['role']);
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    $id = $_GET['id'];
    
    $q = $conn->query("SELECT * FROM kas_masuk WHERE id=$id");
    $data = $q->fetch_assoc();
    
    require __DIR__ . '/../views/bendahara/kas_masuk_edit.php';
    break;
    
    case 'kas-keluar-edit':

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['user'])) {
        header("Location: /membership/login");
        exit;
    }
    
    if ($_SESSION['user']['role'] != 'Bendahara') {
        die("Akses ditolak");
    }
    
    require __DIR__ . '/../app/config/database.php';
    
    $id = $_GET['id'];
    
    $q = $conn->query("SELECT * FROM kas_keluar WHERE id=$id");
    $data = $q->fetch_assoc();
    
    require __DIR__ . '/../views/bendahara/kas_keluar_edit.php';
    break;
    
    case 'kas-keluar-update':

    require __DIR__ . '/../app/config/database.php';
    
    $id = $_POST['id'];
    $jumlah = $_POST['jumlah'];
    $tanggal = $_POST['tanggal'];
    $keterangan = $_POST['keterangan'];
    $sumber = $_POST['sumber_dana'];
    
    $stmt = $conn->prepare("
        UPDATE kas_keluar 
        SET jumlah=?, tanggal=?, keterangan=?, sumber_dana=?
        WHERE id=?
    ");
    
    $stmt->bind_param("isssi", $jumlah, $tanggal, $keterangan, $sumber, $id);
    $stmt->execute();
    
    header("Location: /membership/kas-keluar");
    exit;
    
    case 'kas-masuk-update':

    require __DIR__ . '/../app/config/database.php';
    
    $id = $_POST['id'];
    $jumlah = $_POST['jumlah'];
    $tanggal = $_POST['tanggal'];
    $keterangan = $_POST['keterangan'];
    
    $stmt = $conn->prepare("
        UPDATE kas_masuk 
        SET jumlah=?, tanggal=?, keterangan=?
        WHERE id=?
    ");
    
    $stmt->bind_param("issi", $jumlah, $tanggal, $keterangan, $id);
    $stmt->execute();
    
    header("Location: /membership/kas-masuk");
    exit;
    
    case 'member-card':
    
    require __DIR__ . '/../app/config/database.php';
    
    $id = $_GET['id'] ?? 0;
    
    /* ===============================
       1. AMBIL DATA MEMBER
    ================================ */
    $stmt = $conn->prepare("
        SELECT 
            m.id,
            m.nama, 
            m.perusahaan, 
            m.foto, 
            m.status,
            m.created_at,
            r.nama_role
        FROM members m
        LEFT JOIN roles r ON m.role_id = r.id
        WHERE m.id=?
    ");
    
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($id, $nama, $perusahaan, $foto, $status, $created, $role);
    $stmt->fetch();
    $stmt->close();
    
    /* ===============================
       2. FORMAT MEMBER ID
    ================================ */
    $member_code = "HITASUMUT-" . str_pad($id, 4, "0", STR_PAD_LEFT);
    
    /* ===============================
       3. MAP BULAN INDONESIA
    ================================ */
    $map_bulan = [
        'January' => 'Januari',
        'February' => 'Februari',
        'March' => 'Maret',
        'April' => 'April',
        'May' => 'Mei',
        'June' => 'Juni',
        'July' => 'Juli',
        'August' => 'Agustus',
        'September' => 'September',
        'October' => 'Oktober',
        'November' => 'November',
        'December' => 'Desember'
    ];
    
    /* ===============================
       4. CEK BAYAR BULAN SEKARANG (WAJIB)
    ================================ */
    $bulan_now_en = date('F');
    $bulan_now = $map_bulan[$bulan_now_en];
    $tahun_now = date('Y');
    
    $cek_now = $conn->prepare("
        SELECT id FROM iuran
        WHERE member_id=? 
        AND bulan=? 
        AND tahun=? 
        AND status='Lunas'
    ");
    
    $cek_now->bind_param("iss", $id, $bulan_now, $tahun_now);
    $cek_now->execute();
    $cek_now->store_result();
    
    /* ===============================
       5. JIKA BELUM BAYAR BULAN INI
    ================================ */
    if ($cek_now->num_rows == 0) {
    
        $today = date('d');
    
        // 🔥 Grace period sampai tanggal 7
        if ($today > 7) {
            $status_label = 'NONAKTIF';
            $status_color = 'red';
    
            require __DIR__ . '/../views/member/card.php';
            exit;
        }
    }
    
    /* ===============================
       6. CEK TUNGGAKAN DARI AWAL JOIN
    ================================ */
    $join_date = new DateTime($created ?? date('Y-m-01'));
    $now = new DateTime();
    
    // 🔥 jika masih tgl ≤7, tidak hitung bulan sekarang
    if (date('d') <= 7) {
        $now->modify('-1 month');
    }
    
    $is_active = true;
    
    while ($join_date <= $now) {
    
        $bulan_en = $join_date->format('F');
        $bulan = $map_bulan[$bulan_en];
        $tahun = $join_date->format('Y');
    
        $cek = $conn->prepare("
            SELECT id FROM iuran
            WHERE member_id=? 
            AND bulan=? 
            AND tahun=? 
            AND status='Lunas'
        ");
    
        $cek->bind_param("iss", $id, $bulan, $tahun);
        $cek->execute();
        $cek->store_result();
    
        if ($cek->num_rows == 0) {
            $is_active = false;
            break;
        }
    
        $join_date->modify('+1 month');
    }
    
    /* ===============================
       7. STATUS FINAL
    ================================ */
    if ($is_active) {
        $status_label = 'AKTIF';
        $status_color = 'green';
    } else {
        $status_label = 'NONAKTIF';
        $status_color = 'red';
    }
    
    /* ===============================
       8. LOAD VIEW
    ================================ */
    require __DIR__ . '/../views/member/card.php';
    break;
    
    case 'event-peserta':

    session_start();
    require __DIR__ . '/../app/config/database.php';

    if(!isset($_GET['id'])){
        die("ID event tidak ditemukan");
    }

    $event_id = (int) $_GET['id'];

    $data = $conn->query("
        SELECT er.*, m.nama, m.no_hp
        FROM event_registrations er
        JOIN members m ON m.id = er.member_id
        WHERE er.event_id = $event_id
    ");

    require __DIR__ . '/../views/sekretaris/event_peserta.php';
    break;
    
    case 'event-approve':

    session_start();
    require __DIR__ . '/../app/config/database.php';

    if(!isset($_GET['id'], $_GET['status'])){
        die("Data tidak lengkap");
    }

    $id = (int) $_GET['id'];
    $status = $_GET['status'];

    $conn->query("
        UPDATE event_registrations 
        SET status='$status'
        WHERE id=$id
    ");

    header("Location: " . $_SERVER['HTTP_REFERER']);
    exit;

    break;
    
    case 'event-qr':

    require __DIR__ . '/../app/config/database.php';

    if(!isset($_GET['id'])){
        die("ID tidak ditemukan");
    }

    $event_id = (int) $_GET['id'];

    // 🔥 QR sekarang pakai event_id
    $url = "https://hitasumut.org/membership/event-checkin?event_id=" . $event_id;

    require __DIR__ . '/../views/sekretaris/event_qr.php';
    break;
    
    case 'event-checkin':
    
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    
        require __DIR__ . '/../app/config/database.php';
    
        if(!isset($_GET['event_id'])){
            die("Event tidak ditemukan");
        }
    
        $event_id = (int) $_GET['event_id'];
    
        if(!isset($_SESSION['user'])){
            $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
            header("Location: /membership/login-google");
            exit;
        }
    
        $member_id = $_SESSION['user']['id'];
    
        // ambil data user
        $user = $conn->query("SELECT nama FROM members WHERE id=$member_id")->fetch_assoc();
    
        // ambil event
        $event = $conn->query("SELECT nama_event FROM events WHERE id=$event_id")->fetch_assoc();
    
        // cek terdaftar
        $cek = $conn->query("
            SELECT id, checkin FROM event_registrations
            WHERE event_id = $event_id
            AND member_id = $member_id
        ");
    
        $status = "error";
        $message = "Anda tidak terdaftar";
    
        if($cek->num_rows > 0){
            $row = $cek->fetch_assoc();
    
            if($row['checkin'] == 1){
                $status = "warning";
                $message = "Anda sudah check-in sebelumnya";
            } else {
                $conn->query("
                    UPDATE event_registrations
                    SET checkin = 1
                    WHERE id = {$row['id']}
                ");
    
                $status = "success";
                $message = "Check-in berhasil";
            }
        }
    
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Check-in Event</title>
    
    <style>
    body {
        margin:0;
        font-family:sans-serif;
        background: linear-gradient(135deg,#1e3a8a,#3b82f6);
        display:flex;
        justify-content:center;
        align-items:center;
        height:100vh;
        color:white;
    }
    
    .card {
        background:white;
        color:#111;
        padding:30px;
        border-radius:20px;
        width:90%;
        max-width:400px;
        text-align:center;
        box-shadow:0 10px 30px rgba(0,0,0,0.2);
    }
    
    .icon {
        font-size:60px;
        margin-bottom:10px;
    }
    
    .success { color:#22c55e; }
    .error { color:#ef4444; }
    .warning { color:#f59e0b; }
    
    h2 {
        margin:10px 0;
    }
    
    .info {
        margin-top:15px;
        font-size:14px;
        color:#555;
    }
    
    .btn {
        margin-top:20px;
        display:inline-block;
        padding:10px 15px;
        background:#3b82f6;
        color:white;
        border-radius:8px;
        text-decoration:none;
    }
    </style>
    </head>
    
    <body>
    
    <div class="card">
    
        <div class="icon <?= $status ?>">
            <?php if($status == 'success') echo "✔"; ?>
            <?php if($status == 'error') echo "✖"; ?>
            <?php if($status == 'warning') echo "⚠"; ?>
        </div>
    
        <h2><?= $message ?></h2>
    
        <div class="info">
            <strong><?= htmlspecialchars($user['nama'] ?? '-') ?></strong><br>
            <?= htmlspecialchars($event['nama_event'] ?? '-') ?>
        </div>
    
        <a href="/membership/dashboard" class="btn">Kembali</a>
    
    </div>
    
    </body>
    </html>
    
    <?php
    exit;
    break;
    
    case 'event-export':

    require __DIR__ . '/../app/config/database.php';

    if(!isset($_GET['id'])){
        die("ID event tidak ditemukan");
    }

    $event_id = (int) $_GET['id'];

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=peserta_event.xls");

    echo "<table border='1'>";
    echo "<tr><th>Nama</th><th>No HP</th><th>Status</th><th>Checkin</th></tr>";

    $data = $conn->query("
        SELECT m.nama, m.no_hp, er.status, er.checkin
        FROM event_registrations er
        JOIN members m ON m.id = er.member_id
        WHERE er.event_id = $event_id
    ");

    while($row = $data->fetch_assoc()){
        echo "<tr>
            <td>{$row['nama']}</td>
            <td>{$row['no_hp']}</td>
            <td>{$row['status']}</td>
            <td>".($row['checkin'] ? 'Hadir' : 'Belum')."</td>
        </tr>";
    }

    echo "</table>";
    exit;

    break;
}