<?php
require_once 'config.php';
require_once 'auth_helper.php';

requireRole(['admin_paroki', 'ketua_wilayah', 'ketua_kub']);

$current_role = $_SESSION['role'];
$is_logged_in = isset($_SESSION['user_id']);
$user_name = $_SESSION['username'] ?? '';
$role_label = $is_logged_in ? getRoleName($current_role) : '';

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

    try {
        if ($action === 'create') {
            $target_role = $_POST['role'];
            if ($current_role !== 'admin_paroki' && $current_role !== 'ketua_wilayah') {
            }

            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO user (username, password, role, nama_lengkap) VALUES (:user, :pass, :role, :nama)");
            $stmt->execute([
                ':user' => $_POST['username'],
                ':pass' => $password,
                ':role' => $_POST['role'],
                ':nama' => $_POST['nama']
            ]);
            $_SESSION['message'] = ['type' => 'success', 'text' => "User berhasil ditambahkan!"];
        } elseif ($action === 'delete') {
            if ($_POST['id_user'] == $_SESSION['user_id']) {
                $_SESSION['message'] = ['type' => 'error', 'text' => "Tidak bisa menghapus akun sendiri!"];
            } else {
                $stmt = $pdo->prepare("DELETE FROM user WHERE id_user = :id");
                $stmt->execute([':id' => $_POST['id_user']]);
                $_SESSION['message'] = ['type' => 'success', 'text' => "User berhasil dihapus!"];
            }
        } elseif ($action === 'edit_user') {
            $id_user = (int)$_POST['id_user'];
            $username = $_POST['username'];
            $nama = $_POST['nama'];
            $role = $_POST['role'];
            $new_password = $_POST['new_password'] ?? '';

            if (!empty($new_password)) {
                $hashed_pass = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE user SET username = :username, nama_lengkap = :nama, role = :role, password = :pass WHERE id_user = :id");
                $stmt->execute([':username' => $username, ':nama' => $nama, ':role' => $role, ':pass' => $hashed_pass, ':id' => $id_user]);
            } else {
                $stmt = $pdo->prepare("UPDATE user SET username = :username, nama_lengkap = :nama, role = :role WHERE id_user = :id");
                $stmt->execute([':username' => $username, ':nama' => $nama, ':role' => $role, ':id' => $id_user]);
            }
            
            if ($id_user == $_SESSION['user_id']) {
                $_SESSION['nama_lengkap'] = $nama;
                $_SESSION['role'] = $role;
            }
            $_SESSION['message'] = ['type' => 'success', 'text' => "Data user berhasil diperbarui!"];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ['type' => 'error', 'text' => "Error: " . $e->getMessage()];
    }

    header('Location: user.php');
    exit;
}

// Get Users List
/* Mengambil seluruh daftar akun/pengguna dari database MySQL secara descending (dari akun terbaru ke terlama) */
$users = $pdo->query("SELECT * FROM user ORDER BY created_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manajemen User - Sistem Informasi KUB</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
    <script src="https://unpkg.com/lenis@1/dist/lenis.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/lenis@1/dist/lenis.css">
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <style>
        /* THEME OVERRIDES: Maroon, Gold, Cream, White */
        .btn-primary,
        .btn-success,
        .btn-info,
        .btn-danger {
            background-color: #800000 !important;
            /* Maroon */
            border-color: #800000 !important;
            color: #ffffff !important;
        }

        .btn-primary:hover,
        .btn-success:hover,
        .btn-info:hover,
        .btn-danger:hover {
            background-color: #5c0000 !important;
            /* Darker Maroon */
            border-color: #5c0000 !important;
        }

        .btn-warning,
        .btn-edit {
            background-color: #DAA520 !important;
            /* Gold */
            border-color: #DAA520 !important;
            color: #ffffff !important;
        }

        .btn-warning:hover,
        .btn-edit:hover {
            background-color: #b8860b !important;
            /* Darker Gold */
            border-color: #b8860b !important;
        }

        .modal-header {
            background-color: #800000 !important;
            /* Maroon */
            color: #ffffff !important;
        }

        .table thead tr {
            background-color: #FFFDD0 !important;
            /* Cream */
            color: #800000 !important;
            /* Maroon text for header */
        }

        .pagination .page-link {
            color: #800000 !important;
        }

        .pagination .active .page-link {
            background-color: #800000 !important;
            border-color: #800000 !important;
            color: #ffffff !important;
        }


        /* CSS Override for Edit Button as requested */
        .card .btn-warning {
            background-color: #C83F12 !important;
            border-color: #C83F12 !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }

        .card .btn-warning:hover {
            background-color: #a6340e !important;
            border-color: #a6340e !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(200, 63, 18, 0.45) !important;
            transform: translateY(-2px);
        }

        .card .btn-danger {
            background-color: var(--primary-light) !important;
            border-color: var(--primary-light) !important;
            color: #ffffff !important;
            box-shadow: none !important;
            transition: all 0.3s ease !important;
        }

        .card .btn-danger:hover {
            background-color: var(--primary) !important;
            border-color: var(--primary) !important;
            color: #ffffff !important;
            box-shadow: 0 6px 15px rgba(139, 26, 26, 0.45) !important;
            transform: translateY(-2px);
        }

        /* Hide scrollbar completely but keep scrolling functional */
        ::-webkit-scrollbar {
            display: none;
        }

        body {
            -ms-overflow-style: none;
            /* IE and Edge */
            scrollbar-width: none;
            /* Firefox */
        }

        /* Scroll-reveal animation for stat cards */
        .stat-card {
            opacity: 0;
            transform: translateY(40px);
        }

        .stat-card.stat-visible {
            animation: statFadeUp 0.6s ease-out forwards;
        }

        /* Stagger using nth-child */
        .stat-card:nth-child(2).stat-visible {
            animation-delay: 0.1s;
        }

        .stat-card:nth-child(3).stat-visible {
            animation-delay: 0.2s;
        }

        .stat-card:nth-child(4).stat-visible {
            animation-delay: 0.3s;
        }

        @keyframes statFadeUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>

<body>
    <!-- Header -->
    <?php $active_page = 'user.php';
    include 'navbar.php'; ?>

    <!-- Spacer to prevent overlap -->
    <div style="height: 80px; width: 100%; display: block;"></div>
    <div class="container">
        <!-- Messages -->
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert <?= $_SESSION['message']['type'] ?>">
                <span><?= $_SESSION['message']['text'] ?></span>
                <span class="close-alert" onclick="this.parentElement.remove()">×</span>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>

        <!-- Page Header -->
        <!-- Table Card -->
        <div class="card" style="transition: box-shadow 0.3s ease;" 
             onmouseover="this.style.boxShadow='0 10px 30px rgba(168, 139, 61, 0.15)'" 
             onmouseout="this.style.boxShadow=''">
            <div class="page-header" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
                <h2 style="margin: 0;">Daftar User Sistem</h2>
                <div class="header-actions">
                    <div style="position: relative; display: inline-block;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--text-muted); position: absolute; left: 12px; top: 50%; transform: translateY(-50%); pointer-events: none;">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                        <input type="text" class="search-box" id="searchBox" placeholder="Cari user..."
                            style="width: 250px; padding-left: 35px; border: 1px solid rgba(168, 139, 61, 0.1); background: rgba(168, 139, 61, 0.02); box-shadow: 0 2px 5px rgba(168, 139, 61, 0.05); transition: box-shadow 0.3s ease;" 
                            onmouseover="this.style.boxShadow='0 5px 15px rgba(168, 139, 61, 0.15)'" 
                            onmouseout="this.style.boxShadow='0 2px 5px rgba(168, 139, 61, 0.05)'"
                            onkeyup="searchTable()">
                    </div>
                    <button class="btn btn-primary" onclick="openModal('create')" style="display: inline-flex; align-items: center; gap: 6px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19"></line>
                            <line x1="5" y1="12" x2="19" y2="12"></line>
                        </svg> Tambah User
                    </button>
                </div>
            </div>
            <div class="table-wrapper user-scroll-container" data-lenis-prevent="true" style="max-height: 500px; overflow-y: auto;">
                <table class="table" id="userTable">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Lengkap</th>
                            <th>Username</th>
                            <th>Role</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Melakukan perulangan (looping) pada array data akun untuk mencetak strukturnya satu per satu menjadi baris <tr> dalam tabel -->
                        <?php $no = 1;
                        foreach ($users as $u): ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><strong>
                                    <?php if (!empty($u['nama_lengkap'])): ?>
                                        <?= htmlspecialchars($u['nama_lengkap']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </strong></td>
                                <td>
                                    <?php if (!empty($u['username'])): ?>
                                        <?= htmlspecialchars($u['username']) ?>
                                    <?php else: ?>
                                        <span style="color: #999; font-size: 12px; font-style: italic;">Belum diisi</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge">
                                        <?= getRoleName($u['role']) ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-warning"
                                        onclick="openEdit(<?= $u['id_user'] ?>, '<?= htmlspecialchars(addslashes($u['nama_lengkap']), ENT_QUOTES) ?>', '<?= htmlspecialchars(addslashes($u['username']), ENT_QUOTES) ?>', '<?= htmlspecialchars($u['role'], ENT_QUOTES) ?>')">
                                        Edit
                                    </button>
                                    <?php if ($u['id_user'] != $_SESSION['user_id']): ?>
                                        <button class="btn btn-sm btn-danger"
                                            onclick="deleteUser(<?= $u['id_user'] ?>, '<?= htmlspecialchars($u['username']) ?>')">
                                            Hapus
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Create User Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Tambah User Baru</h3>
                <button class="close" onclick="closeModal('create')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create">
                    <div class="form-group">
                        <label>Nama Lengkap *</label>
                        <input type="text" name="nama" required placeholder="Nama lengkap user" required>  
                    </div>
                    <div class="form-group">
                        <label>Username *</label>
                        <input type="text" name="username" required placeholder="Untuk login" required>
                    </div>
                    <div class="form-group">
                        <label>Password *</label>
                        <input type="password" name="password" required placeholder="Minimal 6 karakter" required>
                    </div>
                    <div class="form-group">
                        <label>Role *</label>
                        <select name="role" required>
                            <option value="">-- Pilih Role --</option>
                            <option value="anggota_kub">Anggota KUB</option>
                            <option value="ketua_kub">Ketua KUB</option>
                            <option value="ketua_wilayah">Ketua Wilayah</option>
                            <option value="admin_paroki">Admin Paroki</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print"
                        onclick="closeModal('create')">Batal</button>
                    <button type="submit" class="btn btn-export">Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content" style="max-width:400px">
            <div class="modal-header">
                <h3>Hapus User</h3>
                <button class="close" onclick="closeModal('delete')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id_user" id="delId">
                    <p>Anda yakin ingin menghapus user <strong id="delUser"></strong>?</p>
                    <p style="color:red; font-size:12px; margin-top:5px;">Tindakan ini tidak dapat dibatalkan.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print"
                        onclick="closeModal('delete')">Batal</button>
                    <button type="submit" class="btn btn-export">Hapus</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Edit User</h3>
                <button class="close" onclick="closeModal('edit')">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="id_user" id="editId">
                    <div class="form-group">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama" id="editNama" required placeholder="Nama lengkap user">
                    </div>
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" name="username" id="editUsername" required placeholder="Untuk login">
                    </div>
                    <div class="form-group">
                        <label>Role</label>
                        <select name="role" id="editRole" required>
                            <option value="">-- Pilih Role --</option>
                            <option value="anggota_kub">Anggota KUB</option>
                            <option value="ketua_kub">Ketua KUB</option>
                            <option value="ketua_wilayah">Ketua Wilayah</option>
                            <option value="admin_paroki">Admin Paroki</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Password Baru <span style="font-size:11px;font-weight:normal;color:#666;">(Kosongkan bila tidak mengubah)</span></label>
                        <input type="password" name="new_password" id="editPassword" placeholder="Masukkan password baru">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-print"
                        onclick="closeModal('edit')">Batal</button>
                    <button type="submit" class="btn btn-export">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openModal(type) {
            document.body.style.overflow = 'hidden';
            if (window.lenis) window.lenis.stop();
            document.getElementById(type + 'Modal').style.display = 'block';
            if (window.initModalLenis) window.initModalLenis(type + 'Modal');
        }

        function closeModal(type) {
            if (window.modalLenis) {
                window.modalLenis.destroy();
                window.modalLenis = null;
            }
            document.getElementById(type + 'Modal').style.display = 'none';
            document.body.style.overflow = '';
            if (window.lenis) window.lenis.start();
        }

        /* Fungsi verifikasi tindakan sebelum admin mencabut hak akses User (Penghapusan Data Akun) */
        function deleteUser(id, name) {
            document.getElementById('delId').value = id;
            document.getElementById('delUser').innerText = name;
            openModal('delete');
        }

        /* Fungsi melimpahkan data user tabel ke field pop-up secara langsung sesuai parameter (Mode Edit) */
        function openEdit(id, nama, username, role) {
            document.getElementById('editId').value = id;
            document.getElementById('editNama').value = nama;
            document.getElementById('editUsername').value = username;
            document.getElementById('editRole').value = role;
            document.getElementById('editPassword').value = '';
            openModal('edit');
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Simple Search Function
        function searchTable() {
            let input = document.getElementById("searchBox");
            let filter = input.value.toLowerCase();
            let table = document.getElementById("userTable");
            let tr = table.getElementsByTagName("tr");

            for (let i = 1; i < tr.length; i++) {
                let tdName = tr[i].getElementsByTagName("td")[1];
                let tdUser = tr[i].getElementsByTagName("td")[2];
                if (tdName || tdUser) {
                    let txtValueName = tdName.textContent || tdName.innerText;
                    let txtValueUser = tdUser.textContent || tdUser.innerText;
                    if (txtValueName.toLowerCase().indexOf(filter) > -1 || txtValueUser.toLowerCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
            }
        }
    </script>

    <script src="navbar.js?v=6"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // ========== SCROLL-TRIGGERED ANIMATIONS ==========
            gsap.registerPlugin(ScrollTrigger);

            // Stat cards — CSS class toggle (no inline styles = no hover bug)
            ScrollTrigger.create({
                trigger: '.stats-grid',
                start: 'top 85%',
                onEnter: () => {
                    document.querySelectorAll('.stat-card').forEach(card => card.classList.add('stat-visible'));
                }
            });

            // Grid-2 cards (iuran + kegiatan) — slide from sides
            const gridCards = document.querySelectorAll('.grid-2 > .card');
            gridCards.forEach((card, i) => {
                gsap.from(card, {
                    x: i === 0 ? -80 : 80,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 80%'
                    }
                });
            });

            // Standalone cards (financial chart, jadwal misa, etc.) — fade up
            document.querySelectorAll('.container > .card').forEach(card => {
                gsap.from(card, {
                    y: 50,
                    opacity: 0,
                    duration: 0.8,
                    ease: 'power3.out',
                    scrollTrigger: {
                        trigger: card,
                        start: 'top 80%'
                    }
                });
            });

            // Activity items — stagger slide in
            gsap.from('.activity-item', {
                x: 60,
                opacity: 0,
                duration: 0.6,
                stagger: 0.1,
                ease: 'power3.out',
                scrollTrigger: {
                    trigger: '.activity-item',
                    start: 'top 85%'
                }
            });

            // KUB stat items — stagger
            gsap.from('.kub-stat-item', {
                y: 30,
                opacity: 0,
                duration: 0.5,
                stagger: 0.08,
                ease: 'power3.out',
                scrollTrigger: {
                    trigger: '.kub-stat-item',
                    start: 'top 85%'
                }
            });

        });
    </script>
    <script src="navbar.js?v=6"></script>
</body>

</html>
