<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/auth/get_users.php
 * Secure User List Endpoint — TEST Environment
 */

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

function get_users_response(
    int $httpCode,
    bool $success,
    string $message,
    ?array $data = null
): void {
    http_response_code($httpCode);

    echo json_encode([
        'status'  => $success,
        'success' => $success,
        'ok'      => $success,
        'code'    => $httpCode,
        'message' => $message,
        'data'    => $data,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    exit;
}

/*
|--------------------------------------------------------------------------
| Login Verification
|--------------------------------------------------------------------------
*/

$currentUserId = (int) ($_SESSION['user_id'] ?? 0);

if ($currentUserId <= 0) {
    get_users_response(
        401,
        false,
        'প্রথমে লগইন করুন'
    );
}

$currentRole = strtolower(
    trim(
        (string) (
            $_SESSION['user_role']
            ?? $_SESSION['role']
            ?? ''
        )
    )
);

if (!in_array($currentRole, ['admin', 'manager'], true)) {
    get_users_response(
        403,
        false,
        'ইউজার তালিকা দেখার অনুমতি নেই'
    );
}

/*
|--------------------------------------------------------------------------
| Database Verification
|--------------------------------------------------------------------------
*/

if (!isset($pdo) || !($pdo instanceof PDO)) {
    get_users_response(
        500,
        false,
        'ডাটাবেস সংযোগ পাওয়া যায়নি'
    );
}

/*
|--------------------------------------------------------------------------
| User List
|--------------------------------------------------------------------------
*/

try {
    $stmt = $pdo->prepare(
        "SELECT
            id,
            name,
            email,
            role,
            status,
            last_login_at,
            created_at
         FROM users
         ORDER BY id ASC"
    );

    $stmt->execute();

    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($users as &$user) {
        $user['id'] = (int) ($user['id'] ?? 0);

        /*
         * পুরোনো UI compatibility-এর জন্য alias।
         */
        $user['last_login'] = $user['last_login_at'] ?? null;
    }

    unset($user);

    get_users_response(
        200,
        true,
        'সফল',
        [
            'users' => $users,
            'total' => count($users),
        ]
    );

} catch (Throwable $exception) {
    get_users_response(
        500,
        false,
        'সার্ভার সমস্যা হয়েছে, আবার চেষ্টা করুন'
    );
}