<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Edit User';
verify_csrf();
mj_user_limits_ensure_schema();
mj_user_access_ensure_schema();
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$u = one('SELECT * FROM mj_users WHERE id=? LIMIT 1', [$id]);
if (!$u || !admin_can_manage_user($admin, $u)) { flash('error','User not found or access denied.'); redirect('users.php'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? 'save_profile');
    if ($action === 'save_access') {
        mj_user_access_save($id, (array)($_POST['access'] ?? []), (int)$admin['id'], trim((string)($_POST['access_note'] ?? '')));
        $maxListings = trim((string)($_POST['max_listings'] ?? ''));
        $maxCompanies = trim((string)($_POST['max_companies'] ?? ''));
        $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, trim((string)($_POST['limit_note'] ?? '')), (int)$admin['id']
        ]);
        admin_log('edit_user_access', 'mj_user_feature_access', $id);
        flash('success', 'User access, payment controls and limits updated.');
        redirect('user-edit.php?id='.$id.'#access-controls');
    }

    $name = trim((string)($_POST['name'] ?? ''));
    $email = trim((string)($_POST['email'] ?? ''));
    if (!$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) { flash('error','Name and valid email are required.'); redirect('user-edit.php?id='.$id); }
    q('UPDATE mj_users SET name=?, email=?, mobile=?, country_id=?, state_id=?, city_id=?, timezone=?, preferred_currency=?, trust_score=?, is_active=?, is_email_verified=?, is_mobile_verified=? WHERE id=?', [
        $name, $email, trim((string)($_POST['mobile'] ?? '')), $_POST['country_id'] ?: null, $_POST['state_id'] ?: null, $_POST['city_id'] ?: null, trim((string)($_POST['timezone'] ?? 'UTC')), trim((string)($_POST['preferred_currency'] ?? 'USD')), (int)($_POST['trust_score'] ?? 0), (int)($_POST['is_active'] ?? 0), (int)($_POST['is_email_verified'] ?? 0), (int)($_POST['is_mobile_verified'] ?? 0), $id
    ]);
    admin_log('edit_user','mj_users',$id);
    flash('success','User updated.');
    redirect('user-edit.php?id='.$id);
}

$countries = all_rows('SELECT id,name,flag_emoji FROM mj_countries WHERE is_active=1 ORDER BY name');
$states = $u['country_id'] ? all_rows('SELECT id,name FROM mj_states WHERE country_id=? AND is_active=1 ORDER BY name LIMIT 500', [(int)$u['country_id']]) : [];
$cities = $u['state_id'] ? all_rows('SELECT id,name FROM mj_cities WHERE state_id=? AND is_active=1 ORDER BY name LIMIT 500', [(int)$u['state_id']]) : [];
$access = mj_user_access_get($id);
$accessGroups = mj_user_access_grouped_defs();
$limit = one('SELECT * FROM mj_user_limits WHERE user_id=? LIMIT 1', [$id]) ?: [];
$defaultListing = (int)setting('default_max_listings_per_user', '5');
$defaultCompany = (int)setting('default_max_companies_per_user', '1');
$userActivityCounts = [
    'listings' => table_exists('mj_listings') ? safe_count('SELECT COUNT(*) c FROM mj_listings WHERE user_id=?', [$id]) : 0,
    'companies' => table_exists('mj_companies') ? safe_count('SELECT COUNT(*) c FROM mj_companies WHERE user_id=?', [$id]) : 0,
    'orders' => table_exists('mj_orders') ? safe_count('SELECT COUNT(*) c FROM mj_orders WHERE buyer_id=? OR seller_id=?', [$id,$id]) : 0,
    'payments' => (table_exists('mj_upgrade_payment_proofs') ? safe_count('SELECT COUNT(*) c FROM mj_upgrade_payment_proofs WHERE user_id=?', [$id]) : 0) + (table_exists('mj_payment_requests') ? safe_count('SELECT COUNT(*) c FROM mj_payment_requests WHERE user_id=?', [$id]) : 0) + (table_exists('mj_invoices') ? safe_count('SELECT COUNT(*) c FROM mj_invoices WHERE user_id=?', [$id]) : 0),
    'support' => table_exists('mj_support_tickets') ? safe_count('SELECT COUNT(*) c FROM mj_support_tickets WHERE user_id=?', [$id]) : 0,
    'activity' => table_exists('mj_user_activity_logs') ? safe_count('SELECT COUNT(*) c FROM mj_user_activity_logs WHERE user_id=?', [$id]) : 0,
];
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-lg-8">
    <div class="card card-primary card-outline">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-user-edit mr-2"></i>Edit User #<?=e($id)?></h3></div>
      <form method="post">
        <div class="card-body">
          <?php show_flash(); ?>
          <?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><input type="hidden" name="action" value="save_profile">
          <div class="form-row"><div class="form-group col-md-6"><label>Name</label><input class="form-control" name="name" value="<?=e($u['name'])?>" required></div><div class="form-group col-md-6"><label>Email</label><input class="form-control" name="email" type="email" value="<?=e($u['email'])?>" required></div></div>
          <div class="form-row"><div class="form-group col-md-4"><label>Mobile</label><input class="form-control" name="mobile" value="<?=e($u['mobile'])?>"></div><div class="form-group col-md-4"><label>Timezone</label><input class="form-control" name="timezone" value="<?=e($u['timezone'])?>"></div><div class="form-group col-md-4"><label>Currency</label><input class="form-control" name="preferred_currency" value="<?=e($u['preferred_currency'])?>"></div></div>
          <div class="form-row"><div class="form-group col-md-4"><label>Country</label><select class="form-control" name="country_id" onchange="loadStates(this.value,'state_id')"><option value="">None</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=((int)$u['country_id']===(int)$c['id'])?'selected':''?>><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?></select></div><div class="form-group col-md-4"><label>State</label><select class="form-control" name="state_id" id="state_id" onchange="loadCities(this.value,'city_id')"><option value="">None</option><?php foreach($states as $s): ?><option value="<?=e($s['id'])?>" <?=((int)$u['state_id']===(int)$s['id'])?'selected':''?>><?=e($s['name'])?></option><?php endforeach; ?></select></div><div class="form-group col-md-4"><label>City</label><select class="form-control" name="city_id" id="city_id"><option value="">None</option><?php foreach($cities as $c): ?><option value="<?=e($c['id'])?>" <?=((int)$u['city_id']===(int)$c['id'])?'selected':''?>><?=e($c['name'])?></option><?php endforeach; ?></select></div></div>
          <div class="form-row"><div class="form-group col-md-3"><label>Trust Score</label><input class="form-control" name="trust_score" type="number" value="<?=e($u['trust_score'])?>"></div><div class="form-group col-md-3"><label>Status</label><select class="form-control" name="is_active"><option value="1" <?=$u['is_active']?'selected':''?>>Active</option><option value="0" <?=!$u['is_active']?'selected':''?>>Suspended</option></select></div><div class="form-group col-md-3"><label>Email Verified</label><select class="form-control" name="is_email_verified"><option value="1" <?=$u['is_email_verified']?'selected':''?>>Yes</option><option value="0" <?=!$u['is_email_verified']?'selected':''?>>No</option></select></div><div class="form-group col-md-3"><label>Mobile Verified</label><select class="form-control" name="is_mobile_verified"><option value="1" <?=$u['is_mobile_verified']?'selected':''?>>Yes</option><option value="0" <?=!$u['is_mobile_verified']?'selected':''?>>No</option></select></div></div>
        </div>
        <div class="card-footer"><button class="btn btn-primary">Save User</button><a href="users.php" class="btn btn-secondary">Back</a></div>
      </form>
    </div>

    <div class="card card-success card-outline" id="access-controls">
      <div class="card-header"><h3 class="card-title"><i class="fas fa-sliders-h mr-2"></i>User Access, Payment Controls & Limits</h3></div>
      <form method="post">
        <div class="card-body">
          <?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><input type="hidden" name="action" value="save_access">
          <div class="alert alert-warning"><b>Admin control:</b> Disable any option here to hide/block it for this specific user. Payment proof still requires admin review before activation.</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="edit_acc_<?=e($key)?>" name="access[<?=e($key)?>]" value="1" <?=!empty($access[$key])?'checked':''?>><label class="custom-control-label" for="edit_acc_<?=e($key)?>"><?=e($cfg['label'])?></label></div><?php endforeach; ?></div></div></div><?php endforeach; ?></div>
          <hr><h5 class="font-weight-bold">Custom Limits</h5><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($limit['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($limit['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($limit['note'] ?? '')?>"></div></div>
          <div class="form-group"><label>Admin access note</label><textarea class="form-control" rows="2" name="access_note"><?=e($access['admin_note'] ?? '')?></textarea></div>
        </div>
        <div class="card-footer"><button class="btn btn-success"><i class="fas fa-save mr-1"></i>Save Access Controls</button></div>
      </form>
    </div>
  </div>
  <div class="col-lg-4"><div class="card"><div class="card-header"><h3 class="card-title">User Summary</h3></div><div class="card-body"><p><b>Created:</b> <?=e($u['created_at'])?></p><p><b>Last Login:</b> <?=e($u['last_login_at'])?></p><div class="row text-center mb-3"><div class="col-6 mb-2"><span class="badge badge-info p-2">Listings <?=e($userActivityCounts['listings'])?></span></div><div class="col-6 mb-2"><span class="badge badge-primary p-2">Companies <?=e($userActivityCounts['companies'])?></span></div><div class="col-6 mb-2"><span class="badge badge-success p-2">Orders <?=e($userActivityCounts['orders'])?></span></div><div class="col-6 mb-2"><span class="badge badge-warning p-2">Payments <?=e($userActivityCounts['payments'])?></span></div><div class="col-6 mb-2"><span class="badge badge-danger p-2">Support <?=e($userActivityCounts['support'])?></span></div><div class="col-6 mb-2"><span class="badge badge-secondary p-2">Logs <?=e($userActivityCounts['activity'])?></span></div></div><hr><a class="btn btn-info btn-block" href="user-activity.php?id=<?=e($id)?>"><i class="fas fa-history mr-1"></i>View Full User Activity</a><a class="btn btn-success btn-block" href="#access-controls"><i class="fas fa-sliders-h mr-1"></i>Jump to Access Controls</a></div></div></div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
