<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$currentUser = current_user() ?: [];
if ((int)($currentUser['role_id'] ?? 0) !== 1) {
    http_response_code(403);
    exit('Access denied.');
}

function ums_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Unable to prepare user manager setup query.');
    }
    return $stmt;
}

function ums_col_exists(mysqli $con, string $table, string $column): bool
{
    $stmt = ums_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?');
    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function ums_table_exists(mysqli $con, string $table): bool
{
    $stmt = ums_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?');
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function ums_ensure_menu_columns(mysqli $con): void
{
    $columns = [
        'parent_id' => 'INT UNSIGNED NOT NULL DEFAULT 0',
        'show_in_menu' => 'TINYINT(1) NOT NULL DEFAULT 1',
        'url' => 'VARCHAR(255) NULL',
        'section' => 'VARCHAR(100) NULL',
        'sort_order' => 'INT NOT NULL DEFAULT 0',
    ];
    foreach ($columns as $column => $definition) {
        if (!ums_col_exists($con, 'jos_admin_menus', $column)) {
            $con->query('ALTER TABLE jos_admin_menus ADD COLUMN `' . $column . '` ' . $definition);
        }
    }
}

function ums_ensure_user_columns(mysqli $con): void
{
    $columns = [
        'payroll_access' => 'TEXT NULL',
        'additional_payroll_access' => 'TEXT NULL',
        'branch_access' => 'TEXT NULL',
        'terminal_access' => 'TEXT NULL',
        'subbranch_access' => 'TEXT NULL',
        'department_access' => 'TEXT NULL',
        'report_filter_access' => 'TEXT NULL',
        'payscale_access' => 'TEXT NULL',
        'attendance_editlog_user_access' => 'TEXT NULL',
        'identified_img_status' => 'TINYINT(1) NOT NULL DEFAULT 0',
    ];
    foreach ($columns as $column => $definition) {
        if (!ums_col_exists($con, 'jos_admin_users', $column)) {
            $con->query('ALTER TABLE jos_admin_users ADD COLUMN `' . $column . '` ' . $definition);
        }
    }
}

function ums_upsert_menu(mysqli $con, string $name, int $parentId, string $link, string $remarks, string $icon, int $sort): int
{
    $stmt = ums_stmt($con, 'SELECT id FROM jos_admin_menus WHERE menu_name=? OR menu_link=? OR url=? ORDER BY id ASC LIMIT 1');
    $stmt->bind_param('sss', $name, $link, $link);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $id = (int)$row['id'];
        $stmt = ums_stmt($con, 'UPDATE jos_admin_menus SET menu_name=?, parent_id=?, menu_link=?, url=?, icon=?, remarks=?, status=1, show_in_menu=1, sort_order=? WHERE id=?');
        $stmt->bind_param('sissssii', $name, $parentId, $link, $link, $icon, $remarks, $sort, $id);
        $stmt->execute();
        $stmt->close();
        return $id;
    }

    $stmt = ums_stmt($con, 'INSERT INTO jos_admin_menus (menu_name, parent_id, menu_link, url, icon, remarks, status, show_in_menu, sort_order) VALUES (?,?,?,?,?,?,1,1,?)');
    $stmt->bind_param('sissssi', $name, $parentId, $link, $link, $icon, $remarks, $sort);
    $stmt->execute();
    $id = (int)$con->insert_id;
    $stmt->close();
    return $id;
}

function ums_grant(mysqli $con, int $roleId, int $menuId): void
{
    $stmt = ums_stmt($con, 'SELECT id FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1');
    $stmt->bind_param('ii', $roleId, $menuId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($row) {
        $id = (int)$row['id'];
        $stmt = ums_stmt($con, 'UPDATE jos_admin_rolemenus SET can_view=1, can_add=1, can_edit=1, can_delete=1, status=1 WHERE id=?');
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        return;
    }
    $stmt = ums_stmt($con, 'INSERT INTO jos_admin_rolemenus (role_id, menu_id, can_view, can_add, can_edit, can_delete, status) VALUES (?, ?, 1, 1, 1, 1, 1)');
    $stmt->bind_param('ii', $roleId, $menuId);
    $stmt->execute();
    $stmt->close();
}

function ums_sync_legacy_user_groups(mysqli $con): void
{
    if (!ums_table_exists($con, 'jos_usergroups')) {
        return;
    }
    $roles = [];
    $maxOrder = 0;
    $stmt = ums_stmt($con, 'SELECT id,name,orderby FROM jos_admin_roles ORDER BY orderby ASC,id ASC');
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $roles[strtolower(trim((string)$row['name']))] = true;
        $maxOrder = max($maxOrder, (int)$row['orderby'], (int)$row['id']);
    }
    $stmt->close();

    $stmt = ums_stmt($con, "SELECT title FROM jos_usergroups WHERE LOWER(title) NOT IN ('public','guest','registered','author','editor','publisher','manager','administrator','super users') ORDER BY id ASC");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $name = trim((string)$row['title']);
        $key = strtolower($name);
        if ($name === '' || isset($roles[$key])) {
            continue;
        }
        ++$maxOrder;
        $status = 1;
        $insert = ums_stmt($con, 'INSERT INTO jos_admin_roles (name, status, orderby) VALUES (?, ?, ?)');
        $insert->bind_param('sii', $name, $status, $maxOrder);
        $insert->execute();
        $insert->close();
        $roles[$key] = true;
    }
    $stmt->close();
}

$notice = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $error = 'Security token expired. Please refresh and try again.';
    } else {
        try {
            ums_ensure_menu_columns($con);
            ums_ensure_user_columns($con);
            ums_sync_legacy_user_groups($con);

            $parentId = ums_upsert_menu($con, 'D. Masters', 0, '#d-masters', 'Daily attendance masters', 'fa-solid fa-layer-group', 20);
            $menuId = ums_upsert_menu($con, 'User Manager', $parentId, 'settings/user-manager.php', 'Manage ABox Console users and access assignments.', 'fa-solid fa-user-shield', 25);

            $roleIds = [1];
            $stmt = ums_stmt($con, "SELECT id FROM jos_admin_roles WHERE status=1 AND (LOWER(name) IN ('administrator','admin','super admin') OR id=1)");
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $roleIds[] = (int)$row['id'];
            }
            $stmt->close();
            foreach (array_values(array_unique($roleIds)) as $roleId) {
                ums_grant($con, $roleId, $menuId);
            }
            audit_log('menu.setup', 'jos_admin_menus', (string)$menuId, 'User Manager');
            $notice = 'User Manager menu, ACL, and required user access columns are ready.';
        } catch (Throwable $e) {
            $error = 'Unable to complete setup.';
        }
    }
}

console_header('User Manager Setup', 'settings/user-manager.php');
?>
<div class="mb-4">
  <div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">User Manager Setup</span></div>
  <h1 class="text-2xl font-bold text-slate-900">User Manager Setup</h1>
  <p class="mt-1 text-sm text-slate-500">Run once to create or update the User Manager menu and Administrator ACL permissions.</p>
</div>
<?php if ($notice): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($notice) ?></div><?php endif; ?>
<?php if ($error): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><?= h($error) ?></div><?php endif; ?>
<section class="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
  <div class="mb-4 flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-brand-600"><i class="fa-solid fa-screwdriver-wrench"></i></span><div><h2 class="font-bold text-slate-800">Apply Setup</h2><p class="text-xs text-slate-400">No duplicate menu or role-permission rows will be created.</p></div></div>
  <form method="post" class="flex flex-wrap gap-2"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><button class="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-check mr-2"></i>Run Setup</button><a href="/settings/user-manager.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600">Open User Manager</a></form>
</section>
<?php console_footer(); ?>
