<?php
// ketua/staff/index.php
$pageTitle = 'Manajemen Staff';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya ketua
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'ketua') {
    // Redirect ke halaman login jika belum login atau bukan ketua
    setFlash('login_required', 'Anda harus login sebagai ketua yayasan untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Handle aksi delete jika ada
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    // Cek apakah bukan user sendiri yang dihapus
    if ($id == $_SESSION['user_id']) {
        setFlash('staff', 'Anda tidak dapat menghapus akun Anda sendiri', 'danger');
        header('Location: ' . SITE_URL . '/ketua/staff/index.php');
        exit;
    }
    
    // Hapus user
    $db->query("DELETE FROM users WHERE id = :id AND role != 'donatur'");
    $db->bind(':id', $id);
    
    if ($db->execute()) {
        // Log aktivitas
        logActivity('Menghapus staff', 'user', $id, 'Ketua menghapus staff');
        
        setFlash('staff', 'Staff berhasil dihapus', 'success');
    } else {
        setFlash('staff', 'Staff gagal dihapus', 'danger');
    }
    
    // Redirect ke halaman staff
    header('Location: ' . SITE_URL . '/ketua/staff/index.php');
    exit;
}

// Pagination
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($current_page - 1) * $limit;

// Filter
$role_filter = isset($_GET['role']) ? $_GET['role'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Query untuk menghitung total staff
$query_count = "SELECT COUNT(*) as total FROM users WHERE role != 'donatur'";
$query_params = [];

if (!empty($role_filter)) {
    $query_count .= " AND role = :role";
    $query_params[':role'] = $role_filter;
}

if (!empty($search)) {
    $query_count .= " AND (nama_lengkap LIKE :search OR username LIKE :search OR email LIKE :search)";
    $query_params[':search'] = "%$search%";
}

$db->query($query_count);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;
$total_pages = ceil($total_rows / $limit);

// Query untuk mengambil data staff
$query = "SELECT * FROM users WHERE role != 'donatur'";

if (!empty($role_filter)) {
    $query .= " AND role = :role";
}

if (!empty($search)) {
    $query .= " AND (nama_lengkap LIKE :search OR username LIKE :search OR email LIKE :search)";
}

$query .= " ORDER BY role, nama_lengkap ASC LIMIT :offset, :limit";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':limit', $limit, PDO::PARAM_INT);
$staff_list = $db->resultSet();

// Include header
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Persetujuan Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/laporan/index.php">
                            <i class="fas fa-chart-line me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kegiatan/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Kegiatan Yayasan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/ketua/staff/index.php">
                            <i class="fas fa-users-cog me-2"></i>
                            Manajemen Staff
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Manajemen Staff</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/ketua/staff/tambah.php" class="btn btn-sm btn-success">
                        <i class="fas fa-plus me-1"></i> Tambah Staff
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Filter & Search -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-6">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari nama, username, atau email..." value="<?= $search ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="role" class="form-label">Role</label>
                            <select class="form-select" id="role" name="role">
                                <option value="">Semua Role</option>
                                <option value="admin" <?= $role_filter == 'admin' ? 'selected' : '' ?>>Admin</option>
                                <option value="ketua" <?= $role_filter == 'ketua' ? 'selected' : '' ?>>Ketua</option>
                                <option value="bendahara" <?= $role_filter == 'bendahara' ? 'selected' : '' ?>>Bendahara</option>
                                <option value="sekretaris" <?= $role_filter == 'sekretaris' ? 'selected' : '' ?>>Sekretaris</option>
                                <option value="pengawas" <?= $role_filter == 'pengawas' ? 'selected' : '' ?>>Pengawas</option>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">Filter</button>
                            <a href="<?= SITE_URL ?>/ketua/staff/index.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Statistik Staff -->
            <div class="row mb-4">
                <?php
                // Hitung jumlah staff per role
                $roles = ['admin', 'ketua', 'bendahara', 'sekretaris', 'pengawas'];
                $role_colors = [
                    'admin' => 'primary',
                    'ketua' => 'success',
                    'bendahara' => 'info',
                    'sekretaris' => 'warning',
                    'pengawas' => 'secondary'
                ];
                
                foreach ($roles as $role) {
                    $db->query("SELECT COUNT(*) as count FROM users WHERE role = :role");
                    $db->bind(':role', $role);
                    $count = $db->single()->count;
                    
                    echo '<div class="col">
                            <div class="card text-white bg-' . $role_colors[$role] . ' mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">' . getRoleName($role) . '</h5>
                                    <p class="card-text display-4">' . $count . '</p>
                                </div>
                            </div>
                          </div>';
                }
                ?>
            </div>

            <!-- Tabel Staff -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th scope="col" width="5%">#</th>
                                    <th scope="col" width="25%">Nama Lengkap</th>
                                    <th scope="col" width="15%">Username</th>
                                    <th scope="col" width="20%">Email</th>
                                    <th scope="col" width="10%">No. Telp</th>
                                    <th scope="col" width="10%">Role</th>
                                    <th scope="col" width="15%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($staff_list)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-4">Tidak ada data staff</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($staff_list as $staff): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="avatar-sm bg-light rounded-circle me-2 d-flex align-items-center justify-content-center">
                                                        <i class="fas fa-user text-secondary"></i>
                                                    </div>
                                                    <div>
                                                        <?= $staff->nama_lengkap ?>
                                                        <?php if ($staff->id == $_SESSION['user_id']): ?>
                                                            <span class="badge bg-success">Anda</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td><?= $staff->username ?></td>
                                            <td><?= $staff->email ?></td>
                                            <td><?= $staff->no_telp ?? '-' ?></td>
                                            <td>
                                                <?php
                                                $badges = [
                                                    'admin' => 'primary',
                                                    'ketua' => 'success',
                                                    'bendahara' => 'info',
                                                    'sekretaris' => 'warning',
                                                    'pengawas' => 'secondary'
                                                ];
                                                
                                                $badge_color = $badges[$staff->role] ?? 'secondary';
                                                echo '<span class="badge bg-' . $badge_color . '">' . getRoleName($staff->role) . '</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/ketua/staff/edit.php?id=<?= $staff->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                                
                                                <?php if ($staff->id != $_SESSION['user_id']): ?>
                                                    <a href="<?= SITE_URL ?>/ketua/staff/index.php?action=delete&id=<?= $staff->id ?>" class="btn btn-sm btn-danger w-100" onclick="return confirm('Yakin ingin menghapus staff ini?')">
                                                        <i class="fas fa-trash"></i> Hapus
                                                    </a>
                                                <?php else: ?>
                                                    <button type="button" class="btn btn-sm btn-secondary w-100" disabled>
                                                        <i class="fas fa-user"></i> Akun Aktif
                                                    </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/ketua/staff/index.php?page=<?= $current_page - 1 ?><?= !empty($role_filter) ? '&role=' . $role_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Previous</a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= ($current_page == $i) ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= SITE_URL ?>/ketua/staff/index.php?page=<?= $i ?><?= !empty($role_filter) ? '&role=' . $role_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/ketua/staff/index.php?page=<?= $current_page + 1 ?><?= !empty($role_filter) ? '&role=' . $role_filter : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<style>
.avatar-sm {
    width: 36px;
    height: 36px;
}
</style>

<?php require_once '../../includes/footer.php'; ?>