<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Users';
verify_csrf();
$isSuper = is_super_admin($admin);
mj_user_limits_ensure_schema();
mj_user_access_ensure_schema();

if (!function_exists('mj_admin_user_access_badge')) {
function mj_admin_user_access_badge(array $access, string $key, string $label): string {
    $on = !empty($access[$key]);
    return '<span class="badge badge-'.($on ? 'success' : 'secondary').' mr-1 mb-1">'.e($label).'</span>';
}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'add') {
        $name = trim((string)($_POST['name'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $pass = (string)($_POST['password'] ?? '');
        if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($pass) >= 8) {
            q('INSERT INTO mj_users(name,email,mobile,password_hash,country_id,timezone,preferred_currency,is_active,created_at) VALUES(?,?,?,?,?,?,?,?,NOW())', [
                $name, $email, $_POST['mobile'] ?? '', password_hash($pass, PASSWORD_DEFAULT), $_POST['country_id'] ?: null, $_POST['timezone'] ?: 'UTC', $_POST['currency'] ?: 'USD', 1
            ]);
            $newUserId = (int)db()->lastInsertId();
            mj_user_access_save($newUserId, array_fill_keys(array_keys(mj_user_access_feature_defs()), 1), (int)$admin['id'], 'Default access enabled when admin created user.');
            admin_log('create_user', 'mj_users', $newUserId, ['email'=>$email]);
            flash('success', 'User created. Default account/payment access enabled.');
        } else {
            flash('error', 'Please enter valid user details. Password min 8 characters.');
        }
    } elseif ($action === 'save_user_access' && $id > 0) {
        $target = one('SELECT * FROM mj_users WHERE id=? LIMIT 1', [$id]);
        if (!$target || !admin_can_manage_user($admin, $target)) {
            flash('error', 'You cannot manage this user.');
            redirect('users.php');
        }
        $accessPost = (array)($_POST['access'] ?? []);
        mj_user_access_save($id, $accessPost, (int)$admin['id'], trim((string)($_POST['access_note'] ?? '')));

        $maxListings = trim((string)($_POST['max_listings'] ?? ''));
        $maxCompanies = trim((string)($_POST['max_companies'] ?? ''));
        $limitNote = trim((string)($_POST['limit_note'] ?? ''));
        $ml = $maxListings === '' ? null : max(0, (int)$maxListings);
        $mc = $maxCompanies === '' ? null : max(0, (int)$maxCompanies);
        q('INSERT INTO mj_user_limits(user_id,max_listings,max_companies,note,updated_by,updated_at) VALUES(?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE max_listings=VALUES(max_listings), max_companies=VALUES(max_companies), note=VALUES(note), updated_by=VALUES(updated_by), updated_at=NOW()', [
            $id, $ml, $mc, $limitNote, (int)$admin['id']
        ]);
        admin_log('save_user_access', 'mj_user_feature_access', $id);
        flash('success', 'Access, payment controls and limits updated for '.$target['email'].'.');
    } elseif ($id > 0 && in_array($action, ['activate','suspend','verify_email','verify_mobile','reset_password','login_as'], true)) {
        $target = one('SELECT * FROM mj_users WHERE id=? LIMIT 1', [$id]);
        if (!$target || !admin_can_manage_user($admin, $target)) { flash('error', 'You cannot manage this user.'); redirect('users.php'); }
        if ($action === 'activate' || $action === 'suspend') {
            q('UPDATE mj_users SET is_active=? WHERE id=?', [$action === 'activate' ? 1 : 0, $id]);
            admin_log($action.'_user', 'mj_users', $id);
            flash('success', 'User status updated.');
        } elseif ($action === 'verify_email') {
            q('UPDATE mj_users SET is_email_verified=1 WHERE id=?', [$id]);
            admin_log('verify_email', 'mj_users', $id);
            flash('success', 'Email marked verified.');
        } elseif ($action === 'verify_mobile') {
            q('UPDATE mj_users SET is_mobile_verified=1 WHERE id=?', [$id]);
            admin_log('verify_mobile', 'mj_users', $id);
            flash('success', 'Mobile marked verified.');
        } elseif ($action === 'reset_password') {
            if (!$isSuper) { flash('error', 'Only Super Admin can reset user password.'); redirect('users.php'); }
            $newPass = safe_random_password(12);
            q('UPDATE mj_users SET password_hash=? WHERE id=?', [password_hash($newPass, PASSWORD_DEFAULT), $id]);
            admin_log('reset_user_password', 'mj_users', $id);
            flash('warning', 'Temporary password for '.e($target['email']).': '.$newPass.' — copy it now.');
        } elseif ($action === 'login_as') {
            if (!$isSuper) { flash('error', 'Only Super Admin can login as user.'); redirect('users.php'); }
            $_SESSION['impersonator_admin_id'] = (int)$admin['id'];
            $_SESSION['user_id'] = $id;
            admin_log('login_as_user', 'mj_users', $id);
            redirect('../my-account.php');
        }
    }
    redirect('users.php'.(!empty($_POST['q_keep']) ? '?q='.rawurlencode((string)$_POST['q_keep']) : ''));
}

$where = [];
$params = [];
if (!$isSuper && !empty($admin['country_id'])) { $where[] = 'u.country_id=?'; $params[] = (int)$admin['country_id']; }
if (!empty($_GET['q'])) { $q = '%'.trim((string)$_GET['q']).'%'; $where[] = '(u.name LIKE ? OR u.email LIKE ? OR u.mobile LIKE ?)'; array_push($params, $q, $q, $q); }
if (isset($_GET['status']) && $_GET['status'] !== '') { $where[] = 'u.is_active=?'; $params[] = (int)$_GET['status']; }

$featureKeys = array_keys(mj_user_access_feature_defs());
$featureSelect = '';
foreach ($featureKeys as $key) { $featureSelect .= ', fa.`'.$key.'` AS access_'.$key; }
$sql = 'SELECT u.*, c.name country, c.flag_emoji, ul.max_listings, ul.max_companies, ul.note limit_note, fa.admin_note access_note'.$featureSelect.',
        (SELECT COUNT(*) FROM mj_listings l WHERE l.user_id=u.id AND IFNULL(l.is_deleted,0)=0 AND l.status NOT IN ("deleted","rejected")) listing_count,
        (SELECT COUNT(*) FROM mj_companies co WHERE co.user_id=u.id AND co.status NOT IN ("deleted","rejected")) company_count
    FROM mj_users u
    LEFT JOIN mj_countries c ON c.id=u.country_id
    LEFT JOIN mj_user_limits ul ON ul.user_id=u.id
    LEFT JOIN mj_user_feature_access fa ON fa.user_id=u.id'.
    ($where ? ' WHERE '.implode(' AND ', $where) : '').' ORDER BY u.id DESC LIMIT 1000';
$rows = all_rows($sql, $params);
$countries = all_rows('SELECT id,name,flag_emoji,currency_code,timezone_default FROM mj_countries WHERE is_active=1 ORDER BY name');
$counts = [
    'total'=>safe_count('SELECT COUNT(*) c FROM mj_users'),
    'active'=>safe_count('SELECT COUNT(*) c FROM mj_users WHERE is_active=1'),
    'verified'=>safe_count('SELECT COUNT(*) c FROM mj_users WHERE is_email_verified=1 OR is_mobile_verified=1'),
    'suspended'=>safe_count('SELECT COUNT(*) c FROM mj_users WHERE is_active=0')
];
$defaultListing = (int)setting('default_max_listings_per_user', '5');
$defaultCompany = (int)setting('default_max_companies_per_user', '1');
$accessDefs = mj_user_access_feature_defs();
$accessGroups = mj_user_access_grouped_defs();
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-lg-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=number_format($counts['total'])?></h3><p>Total Users</p></div><div class="icon"><i class="fas fa-users"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=number_format($counts['active'])?></h3><p>Active</p></div><div class="icon"><i class="fas fa-user-check"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?=number_format($counts['verified'])?></h3><p>Verified</p></div><div class="icon"><i class="fas fa-badge-check"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?=number_format($counts['suspended'])?></h3><p>Suspended</p></div><div class="icon"><i class="fas fa-user-slash"></i></div></div></div>
</div>
<div class="row">
  <div class="col-lg-4">
    <div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-user-plus mr-2"></i>Add User Login</h3></div><form method="post"><div class="card-body"><?=csrf_input()?><input type="hidden" name="action" value="add"><div class="form-group"><label>Name</label><input class="form-control" name="name" required></div><div class="form-group"><label>Email</label><input class="form-control" type="email" name="email" required></div><div class="form-group"><label>Mobile</label><input class="form-control" name="mobile"></div><div class="form-group"><label>Country</label><select class="form-control" name="country_id"><option value="">Select</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>"><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?></select></div><div class="form-row"><div class="form-group col-md-6"><label>Timezone</label><input class="form-control" name="timezone" value="Asia/Singapore"></div><div class="form-group col-md-6"><label>Currency</label><input class="form-control" name="currency" value="SGD"></div></div><div class="form-group"><label>Password</label><input class="form-control" type="password" name="password" required minlength="8"></div></div><div class="card-footer"><button class="btn btn-primary btn-block">Create User</button></div></form></div>
    <div class="card card-warning card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-tools mr-2"></i>Quick User Controls</h3></div><div class="card-body"><p class="text-muted mb-2">Open <b>Access</b> from any user row to enable/disable wallet, billing, proof upload, renew, sponsored, featured and extra slots without leaving the user list.</p><?php if($isSuper): ?><a href="super-admin.php" class="btn btn-warning btn-block"><i class="fas fa-user-shield mr-1"></i>Open Super Admin Center</a><?php else: ?><div class="alert alert-info">Country admins can manage only users in assigned country.</div><?php endif; ?></div></div>
  </div>
  <div class="col-lg-8">
    <div class="card"><div class="card-header"><h3 class="card-title"><i class="fas fa-users mr-2"></i>User Accounts</h3><div class="card-tools"><form class="form-inline" method="get"><input class="form-control form-control-sm mr-2" name="q" value="<?=e($_GET['q']??'')?>" placeholder="Search user"><select class="form-control form-control-sm mr-2" name="status"><option value="">Any status</option><option value="1" <?=($_GET['status']??'')==='1'?'selected':''?>>Active</option><option value="0" <?=($_GET['status']??'')==='0'?'selected':''?>>Suspended</option></select><button class="btn btn-sm btn-primary">Search</button></form></div></div>
      <div class="card-body"><?php show_flash(); ?><div class="alert alert-info"><b>Per-user enable:</b> Global settings still control what exists on site. These switches let admin enable/disable each user’s account modules, payment proof upload, paid listing requests and extra slots. Use <b>Activity</b> to view this user’s listings, companies, payments, proofs, orders, offers, quotes, support, verification and full timeline.</div><div class="table-responsive"><table class="table table-striped table-hover mj-data-table"><thead><tr><th>ID</th><th>User</th><th>Country</th><th>Limits</th><th>Access</th><th>Verify</th><th>Status</th><th style="min-width:290px">Action</th></tr></thead><tbody><?php foreach($rows as $r):
        $rowAccess = ['admin_note'=>(string)($r['access_note'] ?? '')];
        foreach($featureKeys as $key){ $rowAccess[$key] = array_key_exists('access_'.$key, $r) && $r['access_'.$key] !== null && $r['access_'.$key] !== '' ? (int)$r['access_'.$key] : 1; }
        $lMax = $r['max_listings'] === null ? $defaultListing : (int)$r['max_listings'];
        $cMax = $r['max_companies'] === null ? $defaultCompany : (int)$r['max_companies'];
        $modalId = 'userAccessModal'.(int)$r['id'];
      ?><tr><td><?=e($r['id'])?></td><td><b><?=e($r['name'])?></b><br><small><?=e($r['email'])?> <?=e($r['mobile']?'• '.$r['mobile']:'')?></small></td><td><?=e(($r['flag_emoji']??'').' '.($r['country']??''))?></td><td><small>Listings: <b><?=e($r['listing_count'])?></b> / <?=e($lMax ?: 'Unlimited')?><br>Companies: <b><?=e($r['company_count'])?></b> / <?=e($cMax ?: 'Unlimited')?></small></td><td style="min-width:180px"><?=mj_admin_user_access_badge($rowAccess,'billing_payments','Billing')?><?=mj_admin_user_access_badge($rowAccess,'payment_proof_upload','Proof')?><?=mj_admin_user_access_badge($rowAccess,'renew_listing','Renew')?><?=mj_admin_user_access_badge($rowAccess,'featured_listing','Feature')?><?=mj_admin_user_access_badge($rowAccess,'sponsored_listing','Sponsor')?><?=mj_admin_user_access_badge($rowAccess,'extra_listing_slots','Slots')?></td><td><?= $r['is_email_verified']?'<span class="badge badge-success">Email</span>':'<span class="badge badge-secondary">Email</span>' ?> <?= $r['is_mobile_verified']?'<span class="badge badge-success">Mobile</span>':'<span class="badge badge-secondary">Mobile</span>' ?></td><td><?= $r['is_active']?'<span class="badge badge-success">Active</span>':'<span class="badge badge-danger">Suspended</span>' ?></td><td><div class="btn-group btn-group-sm mb-1"><a class="btn btn-outline-primary" href="user-edit.php?id=<?=e($r['id'])?>"><i class="fas fa-edit"></i></a><a class="btn btn-outline-info" href="user-activity.php?id=<?=e($r['id'])?>"><i class="fas fa-history"></i> Activity</a><button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#<?=e($modalId)?>"><i class="fas fa-sliders-h"></i> Access</button></div><form method="post" class="d-inline"><?=csrf_input()?><input type="hidden" name="id" value="<?=e($r['id'])?>"><div class="btn-group btn-group-sm mb-1"><button name="action" value="activate" class="btn btn-success">Active</button><button name="action" value="suspend" class="btn btn-danger">Suspend</button><button name="action" value="verify_email" class="btn btn-info">Email OK</button><button name="action" value="verify_mobile" class="btn btn-info">Mobile OK</button><?php if($isSuper): ?><button name="action" value="reset_password" class="btn btn-warning" onclick="return confirm('Reset password and show a temporary password?')">Reset</button><button name="action" value="login_as" class="btn btn-dark" onclick="return confirm('Login as this user?')">Login As</button><?php endif; ?></div></form>
          <div class="modal fade" id="<?=e($modalId)?>" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog modal-lg" role="document"><div class="modal-content"><form method="post"><?=csrf_input()?><input type="hidden" name="action" value="save_user_access"><input type="hidden" name="id" value="<?=e($r['id'])?>"><input type="hidden" name="q_keep" value="<?=e($_GET['q']??'')?>"><div class="modal-header"><h5 class="modal-title">Enable user options: <?=e($r['name'])?></h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><div class="alert alert-warning"><b>Important:</b> Payment proof upload only creates a pending review. Renew, sponsored, featured or extra slots activate only after admin approval.</div><div class="row"><?php foreach($accessGroups as $group=>$items): ?><div class="col-md-6 mb-3"><div class="card h-100"><div class="card-header py-2"><b><?=e($group)?></b></div><div class="card-body py-2"><?php foreach($items as $key=>$cfg): ?><div class="custom-control custom-switch mb-2"><input type="checkbox" class="custom-control-input" id="acc_<?=e($r['id'].'_'.$key)?>" name="access[<?=e($key)?>]" value="1" <?=!empty($rowAccess[$key])?'checked':''?>><label class="custom-control-label" for="acc_<?=e($r['id'].'_'.$key)?>"><?=e($cfg['label'])?></label></div><?php endforeach; ?></div></div></div><?php endforeach; ?></div><hr><h6 class="font-weight-bold">Listing / Company Limits</h6><div class="form-row"><div class="form-group col-md-4"><label>Max listings</label><input class="form-control" type="number" min="0" name="max_listings" placeholder="<?=e($defaultListing)?>" value="<?=e($r['max_listings'] ?? '')?>"><small class="text-muted">Blank = default, 0 = unlimited</small></div><div class="form-group col-md-4"><label>Max companies</label><input class="form-control" type="number" min="0" name="max_companies" placeholder="<?=e($defaultCompany)?>" value="<?=e($r['max_companies'] ?? '')?>"><small class="text-muted">Blank = default, 0 = unlimited</small></div><div class="form-group col-md-4"><label>Limit note</label><input class="form-control" name="limit_note" value="<?=e($r['limit_note'] ?? '')?>"></div></div><div class="form-group"><label>Admin access note</label><textarea class="form-control" rows="2" name="access_note" placeholder="Internal note only"><?=e($rowAccess['admin_note'])?></textarea></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button><button class="btn btn-success"><i class="fas fa-save mr-1"></i>Save Access</button></div></form></div></div></div>
        </td></tr><?php endforeach; ?></tbody></table></div></div>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
