<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Check admin login
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filters
$role = isset($_GET['role']) ? $_GET['role'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query conditions
$conditions = [];
$params = [];

if (!empty($role) && in_array($role, ['admin', 'customer'])) {
    $conditions[] = "role = ?";
    $params[] = $role;
}

if (!empty($status) && in_array($status, ['active', 'inactive'])) {
    $conditions[] = "status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $conditions[] = "(name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Count total users
$total_users_query = "SELECT COUNT(*) as count FROM users $where_clause";
$total_users = get_row($total_users_query, $params)['count'];

// Get users for current page
$sql = "
    SELECT 
        u.id, u.name, u.email, u.phone, 
        u.role, u.status, u.created_at,
        (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as order_count
    FROM 
        users u
    {$where_clause}
    ORDER BY u.id DESC
    LIMIT ? OFFSET ?
";

$params[] = $per_page;
$params[] = $offset;

$users = get_rows($sql, $params);

// Prepare page metadata
$title = 'Korisnici - Admin';
require_once '../includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4">Pregled korisnika</h1>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" action="">
                <div class="row">
                    <div class="col-md-3">
                        <input type="text" name="search" class="form-control" 
                               placeholder="Pretraga (ime, email, telefon)" 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <select name="role" class="form-control">
                            <option value="">Sve uloge</option>
                            <option value="admin" <?php echo $role == 'admin' ? 'selected' : ''; ?>>Administratori</option>
                            <option value="customer" <?php echo $role == 'customer' ? 'selected' : ''; ?>>Kupci</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select name="status" class="form-control">
                            <option value="">Svi statusi</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Aktivni</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Neaktivni</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary">Pretraži</button>
                        <a href="?" class="btn btn-secondary">Resetuj</a>
                    </div>
                    <div class="col-md-3 text-right">
                        <a href="export.php?<?php echo $_SERVER['QUERY_STRING']; ?>" class="btn btn-success">
                            Izvoz korisnika
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Users Table -->
    <div class="card">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Ime</th>
                        <th>Email</th>
                        <th>Telefon</th>
                        <th>Uloga</th>
                        <th>Status</th>
                        <th>Broj porudžbina</th>
                        <th>Registrovan</th>
                        <th>Akcije</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo $user['id']; ?></td>
                        <td><?php echo htmlspecialchars($user['name']); ?></td>
                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                        <td><?php echo htmlspecialchars($user['phone']); ?></td>
                        <td><?php echo $user['role'] == 'admin' ? 'Administrator' : 'Kupac'; ?></td>
                        <td>
                            <span class="badge <?php echo $user['status'] == 'active' ? 'badge-success' : 'badge-danger'; ?>">
                                <?php echo $user['status'] == 'active' ? 'Aktivan' : 'Neaktivan'; ?>
                            </span>
                        </td>
                        <td><?php echo $user['order_count']; ?></td>
                        <td><?php echo date('d.m.Y', strtotime($user['created_at'])); ?></td>
                        <td>
                            <a href="edit.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-primary">Uredi</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    <?php 
    $total_pages = ceil($total_users / $per_page);
    include '../includes/pagination.php'; 
    ?>
</div>

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