<?php
/**
 * Users List Endpoint (Role-Based, Tenant-Aware, Paginated)
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Middleware\AuthMiddleware;

// 1. Auth Check
$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$role = $decoded['role'];
$tenantId = $decoded['tenant_id'] ?? null;

if ($role !== 'super_admin' && $role !== 'admin') {
    json_error('Unauthorized', 403);
}

try {
    $pagination = paginate_params(25, 100);

    // 2. Build WHERE clause based on Role
    $where = '';
    $params = [];

    if ($role === 'super_admin') {
        $where = '1=1';
    } else {
        $where = 'u.tenant_id = ?';
        $params = [$tenantId];
    }

    // Optional filters
    $roleFilter = $_GET['role'] ?? null;
    $activeFilter = $_GET['is_active'] ?? null;

    if ($roleFilter) {
        $where .= ' AND u.role = ?';
        $params[] = $roleFilter;
    }
    if ($activeFilter !== null && $activeFilter !== '') {
        $where .= ' AND u.is_active = ?';
        $params[] = (int)$activeFilter;
    }

    // 3. Count total
    $countStmt = $db->prepare("SELECT COUNT(*) FROM users u WHERE $where");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    // 4. Fetch page
    $stmt = $db->prepare("
        SELECT u.id, u.name, u.email, u.phone, u.role, u.is_active, u.created_at, t.name as tenant_name
        FROM users u
        LEFT JOIN tenants t ON u.tenant_id = t.id
        WHERE $where
        ORDER BY u.created_at DESC
        LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}
    ");
    $stmt->execute($params);
    $users = $stmt->fetchAll();

    // 5. Decrypt data
    $dec = function($val) {
        if (empty($val)) return '';
        $result = Encryption::decrypt((string)$val);
        return ($result !== false && $result !== null) ? $result : (string)$val;
    };

    foreach ($users as &$user) {
        $user['name'] = $dec($user['name']);
        $user['email'] = $dec($user['email']);
        if (!empty($user['phone'])) {
            $user['phone'] = $dec($user['phone']);
        }
        if (!empty($user['tenant_name'])) {
            $user['tenant_name'] = $dec($user['tenant_name']);
        }
    }

    json_paginated($users, $total, $pagination);

} catch (\Exception $e) {
    safe_error($e, 'users/index');
}
