<?php
require_once '../../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

$pageTitle = "Kelola Pengguna";

// Delete user if requested
if (isset($_GET['delete'])) {
    $user_id = (int)$_GET['delete'];
    
    try {
        $conn = connectDB();
        
        // Check if the user exists
        $stmt = $conn->prepare("SELECT * FROM users WHERE user_id = :user_id");
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        
        if ($stmt->fetch(PDO::FETCH_ASSOC)) {
            // Delete user (orders will have their user_id set to NULL due to foreign key constraint)
            $stmt = $conn->prepare("DELETE FROM users WHERE user_id = :user_id");
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();
            
            $success = "Pengguna berhasil dihapus";
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get users with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Search functionality
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

try {
    $conn = connectDB();
    
    // Build query based on search
    $query = "SELECT * FROM users";
    $countQuery = "SELECT COUNT(*) as total FROM users";
    $params = [];
    
    if (!empty($search)) {
        $query .= " WHERE name LIKE :search OR email LIKE :search OR username LIKE :search";
        $countQuery .= " WHERE name LIKE :search OR email LIKE :search OR username LIKE :search";
        $params[':search'] = '%' . $search . '%';
    }
    
    $query .= " ORDER BY created_at DESC LIMIT :offset, :limit";
    
    // Count total users
    $stmt = $conn->prepare($countQuery);
    if (!empty($params)) {
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
    }
    $stmt->execute();
    $totalUsers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalUsers / $limit);
    
    // Get users for current page
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
    }
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Kelola Pengguna</h1>
    <div class="search-form">
        <form action="<?php echo SITE_URL; ?>admin/users/index.php" method="get">
            <input type="text" name="search" placeholder="Cari pengguna..." value="<?php echo $search; ?>">
            <button type="submit" class="search-btn"><i class="fas fa-search"></i></button>
        </form>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<div class="admin-content-box">
    <div class="user-stats">
        <div class="stat-box">
            <div class="stat-number"><?php echo $totalUsers; ?></div>
            <div class="stat-label">Total Pengguna</div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Tanggal Daftar</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="6" class="text-center">Belum ada pengguna</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo $user['user_id']; ?></td>
                            <td><?php echo $user['name']; ?></td>
                            <td><?php echo $user['username']; ?></td>
                            <td><?php echo $user['email']; ?></td>
                            <td><?php echo date('d/m/Y', strtotime($user['created_at'])); ?></td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>admin/users/view.php?id=<?php echo $user['user_id']; ?>" class="action-btn view-btn" title="Detail">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="<?php echo SITE_URL; ?>admin/users/edit.php?id=<?php echo $user['user_id']; ?>" class="action-btn edit-btn" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="<?php echo SITE_URL; ?>admin/users/index.php?delete=<?php echo $user['user_id']; ?>" class="action-btn delete-btn delete-confirm" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php
            $queryParams = [];
            if (!empty($search)) {
                $queryParams[] = "search=$search";
            }
            $queryString = !empty($queryParams) ? '&' . implode('&', $queryParams) : '';
            ?>
            
            <?php if ($page > 1): ?>
                <a href="<?php echo SITE_URL; ?>admin/users/index.php?page=<?php echo $page - 1; ?><?php echo $queryString; ?>" class="page-link">&laquo; Sebelumnya</a>
            <?php endif; ?>
            
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="<?php echo SITE_URL; ?>admin/users/index.php?page=<?php echo $i; ?><?php echo $queryString; ?>" class="page-link <?php echo ($page == $i) ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
                <a href="<?php echo SITE_URL; ?>admin/users/index.php?page=<?php echo $page + 1; ?><?php echo $queryString; ?>" class="page-link">Berikutnya &raquo;</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
    .search-form {
        display: flex;
        align-items: center;
    }
    
    .search-form input[type="text"] {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        width: 250px;
    }
    
    .search-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        border-radius: 4px;
        padding: 8px 12px;
        margin-left: 5px;
        cursor: pointer;
    }
    
    .user-stats {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .stat-box {
        background-color: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        text-align: center;
        flex: 1;
    }
    
    .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: var(--primary-color);
    }
    
    .stat-label {
        color: var(--dark-gray);
        margin-top: 5px;
    }
</style>

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