<?php
require_once __DIR__ . '/auth.php';
require_admin();

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

$adminUsersTitle = app_setting($pdo, 'admin_label_users', 'Registered Members');
$pageTitle = $adminUsersTitle;

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

$accessLevels = [
    'guest' => 'Guest',
    'member' => 'Member',
    'training' => 'Training',
    'leader' => 'Leader',
    'premium' => 'Premium',
    'admin' => 'Admin',
    'founder' => 'Founder'
];

$membershipTypes = [
    'free' => 'Free',
    'standard' => 'Standard',
    'partner' => 'Partner',
    'training' => 'Training',
    'premium' => 'Premium',
    'lifetime' => 'Lifetime',
    'staff' => 'Staff'
];

$visibilityOptions = [
    'private' => 'Private',
    'members' => 'Members Only',
    'public' => 'Public'
];

try {
    $cols = [];
    $stmt = $pdo->query("SHOW COLUMNS FROM users");
    foreach ($stmt->fetchAll() as $row) {
        $cols[] = $row['Field'];
    }

    $adds = [];
    if (!in_array('access_level', $cols, true)) $adds[] = "ADD COLUMN access_level VARCHAR(50) NOT NULL DEFAULT 'member'";
    if (!in_array('membership_type', $cols, true)) $adds[] = "ADD COLUMN membership_type VARCHAR(50) NOT NULL DEFAULT 'standard'";
    if (!in_array('profile_visibility', $cols, true)) $adds[] = "ADD COLUMN profile_visibility VARCHAR(30) NOT NULL DEFAULT 'members'";

    if ($adds) {
        $pdo->exec("ALTER TABLE users " . implode(", ", $adds));
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    try {
        $id = (int)($_POST['id'] ?? 0);
        $access = trim($_POST['access_level'] ?? 'member');
        $membership = trim($_POST['membership_type'] ?? 'standard');
        $visibility = trim($_POST['profile_visibility'] ?? 'members');

        if (!array_key_exists($access, $accessLevels)) $access = 'member';
        if (!array_key_exists($membership, $membershipTypes)) $membership = 'standard';
        if (!array_key_exists($visibility, $visibilityOptions)) $visibility = 'members';

        if ($id > 0) {
            $stmt = $pdo->prepare("
                UPDATE users
                SET access_level = ?,
                    membership_type = ?,
                    profile_visibility = ?
                WHERE id = ?
            ");
            $stmt->execute([$access, $membership, $visibility, $id]);
            $notice = 'User account settings updated.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

try {
    $stmt = $pdo->query("
        SELECT id, username, email, role, access_level, membership_type, profile_visibility, created_at
        FROM users
        ORDER BY created_at DESC, id DESC
    ");
    $users = $stmt->fetchAll();
} catch (Throwable $e) {
    $users = [];
    $error = $e->getMessage();
}

require_once __DIR__ . '/includes/header.php';
?>

<main>
<section class="section">
<div class="container">
<div class="panel">

<h1><?php echo h($adminUsersTitle); ?></h1>
<p class="muted">Basic User Account Architecture: Access Level, Membership Type, and Profile Visibility.</p>

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

<table class="module-table">
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Access Level</th>
<th>Membership Type</th>
<th>Profile Visibility</th>
<th>Joined</th>
<th>Action</th>
</tr>

<?php foreach ($users as $u): ?>
<tr>
<form method="post">
<input type="hidden" name="id" value="<?php echo h($u['id']); ?>">

<td><?php echo h($u['username']); ?></td>
<td><?php echo h($u['email']); ?></td>
<td><?php echo h($u['role']); ?></td>

<td>
<select name="access_level">
<?php foreach ($accessLevels as $key => $label): ?>
<option value="<?php echo h($key); ?>" <?php echo (($u['access_level'] ?? 'member') === $key) ? 'selected' : ''; ?>>
<?php echo h($label); ?>
</option>
<?php endforeach; ?>
</select>
</td>

<td>
<select name="membership_type">
<?php foreach ($membershipTypes as $key => $label): ?>
<option value="<?php echo h($key); ?>" <?php echo (($u['membership_type'] ?? 'standard') === $key) ? 'selected' : ''; ?>>
<?php echo h($label); ?>
</option>
<?php endforeach; ?>
</select>
</td>

<td>
<select name="profile_visibility">
<?php foreach ($visibilityOptions as $key => $label): ?>
<option value="<?php echo h($key); ?>" <?php echo (($u['profile_visibility'] ?? 'members') === $key) ? 'selected' : ''; ?>>
<?php echo h($label); ?>
</option>
<?php endforeach; ?>
</select>
</td>

<td><?php echo !empty($u['created_at']) ? h(date("M d, Y", strtotime($u['created_at']))) : ''; ?></td>
<td><button class="btn btn-secondary btn-small" type="submit">Save</button></td>
</form>
</tr>
<?php endforeach; ?>

</table>

</div>
</div>
</section>
</main>

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