<?php
// admin/users/index.php
$pageTitle = 'Manajemen User';
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 admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin 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'];
    
    // Jangan hapus diri sendiri
    if ($id == $_SESSION['user_id']) {
        setFlash('user', 'Anda tidak dapat menghapus akun Anda sendiri', 'danger');
        header('Location: ' . SITE_URL . '/admin/users/index.php');
        exit;
    }
    
    // Cek apakah user memiliki donasi
    $db->query("SELECT COUNT(*) as jumlah FROM donasi WHERE user_id = :id");
    $db->bind(':id', $id);
    $result = $db->single();
    
    // Cek apakah user membuat kampanye atau berita
    $db->query("SELECT COUNT(*) as jumlah FROM kampanye WHERE created_by = :id");
    $db->bind(':id', $id);
    $result_kampanye = $db->single();
    
    $db->query("SELECT COUNT(*) as jumlah FROM berita WHERE created_by = :id");
    $db->bind(':id', $id);
    $result_berita = $db->single();
    
    if ($result->jumlah > 0 || $result_kampanye->jumlah > 0 || $result_berita->jumlah > 0) {
        setFlash('user', 'User tidak dapat dihapus karena memiliki donasi/kampanye/berita terkait', 'danger');
    } else {
        // Ambil informasi user sebelum dihapus untuk log
        $db->query("SELECT username, nama_lengkap, role FROM users WHERE id = :id");
        $db->bind(':id', $id);
        $user = $db->single();
        
        // Hapus user dari database
        $db->query("DELETE FROM users WHERE id = :id");
        $db->bind(':id', $id);
        
        if ($db->execute()) {
            // Log aktivitas
            logActivity('Menghapus user', 'user', $id, "Admin menghapus user: {$user->username} ({$user->nama_lengkap}) dengan role {$user->role}");
            
            setFlash('user', 'User berhasil dihapus', 'success');
        } else {
            setFlash('user', 'User gagal dihapus', 'danger');
        }
    }
    
    // Redirect ke halaman users
    header('Location: ' . SITE_URL . '/admin/users/index.php');
    exit;
}

// Pagination
$current_page = isset($_GET['page']) ? $_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 users
$query_count = "SELECT COUNT(*) as total FROM users WHERE 1=1";
$query_params = [];

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

if (!empty($search)) {
    $query_count .= " AND (username LIKE :search OR nama_lengkap 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 users
$query = "SELECT * FROM users WHERE 1=1";

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

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

$query .= " ORDER BY id DESC 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);
$users_list = $db->resultSet();

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

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.php'; ?>
        
        <!-- 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 User</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/admin/users/tambah.php" class="btn btn-sm btn-success">
                        <i class="fas fa-plus me-1"></i> Tambah User
                    </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-4">
                            <label for="search" class="form-label">Cari</label>
                            <input type="text" class="form-control" id="search" name="search" placeholder="Cari username, nama 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 Yayasan</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>
                                <option value="donatur" <?= $role_filter == 'donatur' ? 'selected' : '' ?>>Donatur</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 ?>/admin/users/index.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Users -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th scope="col" width="5%">#</th>
                                    <th scope="col" width="15%">Username</th>
                                    <th scope="col" width="20%">Nama</th>
                                    <th scope="col" width="20%">Email</th>
                                    <th scope="col" width="15%">Role</th>
                                    <th scope="col" width="15%">Dibuat Pada</th>
                                    <th scope="col" width="10%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($users_list)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-4">Tidak ada data user</td>
                                    </tr>
                                <?php else: ?>
                                    <?php $no = $offset + 1; ?>
                                    <?php foreach ($users_list as $user): ?>
                                        <tr>
                                            <th scope="row"><?= $no++ ?></th>
                                            <td><?= $user->username ?></td>
                                            <td><?= $user->nama_lengkap ?></td>
                                            <td><?= $user->email ?></td>
                                            <td>
                                                <?php
                                                switch ($user->role) {
                                                    case 'admin':
                                                        echo '<span class="badge bg-danger">Admin</span>';
                                                        break;
                                                    case 'ketua':
                                                        echo '<span class="badge bg-primary">Ketua Yayasan</span>';
                                                        break;
                                                    case 'bendahara':
                                                        echo '<span class="badge bg-info text-dark">Bendahara</span>';
                                                        break;
                                                    case 'sekretaris':
                                                        echo '<span class="badge bg-warning text-dark">Sekretaris</span>';
                                                        break;
                                                    case 'pengawas':
                                                        echo '<span class="badge bg-secondary">Pengawas</span>';
                                                        break;
                                                    case 'donatur':
                                                        echo '<span class="badge bg-success">Donatur</span>';
                                                        break;
                                                    default:
                                                        echo '<span class="badge bg-light text-dark">' . ucfirst($user->role) . '</span>';
                                                }
                                                ?>
                                            </td>
                                            <td><?= date('d/m/Y H:i', strtotime($user->created_at)) ?></td>
                                            <td>
                                                <a href="<?= SITE_URL ?>/admin/users/edit.php?id=<?= $user->id ?>" class="btn btn-sm btn-primary mb-1 w-100">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                                <?php if ($user->id != $_SESSION['user_id']): ?>
                                                    <a href="<?= SITE_URL ?>/admin/users/index.php?action=delete&id=<?= $user->id ?>" class="btn btn-sm btn-danger w-100" onclick="return confirm('Yakin ingin menghapus user 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> Anda
                                                    </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 ?>/admin/users/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 ?>/admin/users/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 ?>/admin/users/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>

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