<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
verify_csrf();
mj_user_limits_ensure_schema();
if (function_exists('mj_v300_ensure_schema')) { mj_v300_ensure_schema(); }
$adminTitle = 'User Listing / Company / Deal Limits';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'save_defaults') {
        $dl = max(0, (int)($_POST['default_max_listings_per_user'] ?? 5));
        $dc = max(0, (int)($_POST['default_max_companies_per_user'] ?? 1));
        $dd = max(0, (int)($_POST['default_max_deals_per_user'] ?? 3));
        q('INSERT INTO mj_settings(setting_key,setting_value) VALUES("default_max_listings_per_user",?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)', [$dl]);
        q('INSERT INTO mj_settings(setting_key,setting_value) VALUES("default_max_companies_per_user",?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)', [$dc]);
        q('INSERT INTO mj_settings(setting_key,setting_value) VALUES("default_max_deals_per_user",?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)', [$dd]);
        flash('success','Default user limits saved.');
    } elseif ($action === 'save_user_limit') {
        $userId = (int)($_POST['user_id'] ?? 0);
        $maxListings = trim((string)($_POST['max_listings'] ?? ''));
        $maxCompanies = trim((string)($_POST['max_companies'] ?? ''));
        $maxDeals = trim((string)($_POST['max_deals'] ?? ''));
        $note = trim((string)($_POST['note'] ?? ''));
        $user = $userId ? one('SELECT id,email,name FROM mj_users WHERE id=? LIMIT 1', [$userId]) : null;
        if (!$user) {
            flash('error','User not found.');
        } else {
            $ml = $maxListings === '' ? null : max(0, (int)$maxListings);
            $mc = $maxCompanies === '' ? null : max(0, (int)$maxCompanies);
            $md = $maxDeals === '' ? null : max(0, (int)$maxDeals);
            q('INSERT INTO mj_user_limits(user_id,max_listings,max_companies,max_deals,note,updated_by,updated_at) VALUES(?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE max_listings=VALUES(max_listings), max_companies=VALUES(max_companies), max_deals=VALUES(max_deals), note=VALUES(note), updated_by=VALUES(updated_by), updated_at=NOW()', [
                $userId, $ml, $mc, $md, $note, (int)$admin['id']
            ]);
            flash('success','User limits updated for '.$user['email']);
        }
    }
    redirect('user-limits.php'.(!empty($_POST['q']) ? '?q='.rawurlencode((string)$_POST['q']) : ''));
}

$qstr = trim((string)($_GET['q'] ?? ''));
$where = [];
$params = [];
if ($qstr !== '') {
    $where[] = '(u.name LIKE ? OR u.email LIKE ? OR u.mobile LIKE ?)';
    $like = '%'.$qstr.'%';
    array_push($params,$like,$like,$like);
}
$rows = all_rows('SELECT u.id,u.name,u.email,u.mobile,u.is_active,ul.max_listings,ul.max_companies,ul.max_deals,ul.note,
    (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,
    (SELECT COUNT(*) FROM mj_deals d WHERE d.user_id=u.id AND d.status NOT IN ("deleted","rejected")) deal_count
    FROM mj_users u
    LEFT JOIN mj_user_limits ul ON ul.user_id=u.id
    '.($where?'WHERE '.implode(' AND ',$where):'').'
    ORDER BY u.id DESC LIMIT 500', $params);

$defaultListing = (int)setting('default_max_listings_per_user','5');
$defaultCompany = (int)setting('default_max_companies_per_user','1');
$defaultDeal = (int)setting('default_max_deals_per_user','3');
include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-user-lock mr-2"></i>User Listing / Company / Deal Limits</h3>
  </div>
  <div class="card-body">
    <?php show_flash(); ?>

    <div class="alert alert-info">
      <b>Limit rules:</b> 0 means unlimited. Blank per-user value means use default limit.
    </div>

    <form method="post" class="card card-body bg-light mb-4">
      <?=csrf_input()?>
      <input type="hidden" name="action" value="save_defaults">
      <h5 class="font-weight-bold">Default limits</h5>
      <div class="row">
        <div class="col-md-4">
          <label>Default max listings per user</label>
          <input class="form-control" type="number" min="0" name="default_max_listings_per_user" value="<?=e($defaultListing)?>">
        </div>
        <div class="col-md-4">
          <label>Default max companies per user</label>
          <input class="form-control" type="number" min="0" name="default_max_companies_per_user" value="<?=e($defaultCompany)?>">
        </div>
        <div class="col-md-4">
          <label>Default max deals per user</label>
          <input class="form-control" type="number" min="0" name="default_max_deals_per_user" value="<?=e($defaultDeal)?>">
        </div>
        <div class="col-md-4 d-flex align-items-end mt-2">
          <button class="btn btn-primary"><i class="fas fa-save mr-1"></i>Save Defaults</button>
        </div>
      </div>
    </form>

    <form class="form-inline mb-3">
      <input class="form-control mr-2" name="q" value="<?=e($qstr)?>" placeholder="Search user name, email, mobile">
      <button class="btn btn-primary"><i class="fas fa-search mr-1"></i>Search</button>
      <a class="btn btn-outline-secondary ml-2" href="user-limits.php">Clear</a>
    </form>

    <div class="table-responsive">
      <table class="table table-hover">
        <thead><tr><th>User</th><th>Usage</th><th>Current Limit</th><th>Set Custom Limit</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r):
            $lMax = $r['max_listings'] === null ? $defaultListing : (int)$r['max_listings'];
            $cMax = $r['max_companies'] === null ? $defaultCompany : (int)$r['max_companies'];
            $dMax = $r['max_deals'] === null ? $defaultDeal : (int)$r['max_deals'];
          ?>
            <tr>
              <td>
                <b><?=e($r['name'])?></b><br>
                <small><?=e($r['email'])?> <?=e($r['mobile'])?></small>
              </td>
              <td>
                Listings: <b><?=e($r['listing_count'])?></b> / <?=e($lMax ?: 'Unlimited')?><br>
                Companies: <b><?=e($r['company_count'])?></b> / <?=e($cMax ?: 'Unlimited')?><br>
                Deals: <b><?=e($r['deal_count'])?></b> / <?=e($dMax ?: 'Unlimited')?>
              </td>
              <td>
                <span class="badge badge-<?=((int)$r['listing_count'] >= $lMax && $lMax>0)?'warning':'success'?>">Listings <?=e($lMax ?: 'Unlimited')?></span>
                <span class="badge badge-<?=((int)$r['company_count'] >= $cMax && $cMax>0)?'warning':'success'?>">Companies <?=e($cMax ?: 'Unlimited')?></span>
                <span class="badge badge-<?=((int)$r['deal_count'] >= $dMax && $dMax>0)?'warning':'success'?>">Deals <?=e($dMax ?: 'Unlimited')?></span>
                <?php if($r['note']): ?><br><small class="text-muted"><?=e($r['note'])?></small><?php endif; ?>
              </td>
              <td style="min-width:360px">
                <form method="post" class="d-flex flex-wrap gap-1">
                  <?=csrf_input()?>
                  <input type="hidden" name="action" value="save_user_limit">
                  <input type="hidden" name="user_id" value="<?=e($r['id'])?>">
                  <input type="hidden" name="q" value="<?=e($qstr)?>">
                  <input class="form-control form-control-sm" style="width:90px" type="number" min="0" name="max_listings" placeholder="<?=e($defaultListing)?>" value="<?=e($r['max_listings'] ?? '')?>">
                  <input class="form-control form-control-sm" style="width:90px" type="number" min="0" name="max_companies" placeholder="<?=e($defaultCompany)?>" value="<?=e($r['max_companies'] ?? '')?>">
                  <input class="form-control form-control-sm" style="width:90px" type="number" min="0" name="max_deals" placeholder="<?=e($defaultDeal)?>" value="<?=e($r['max_deals'] ?? '')?>">
                  <input class="form-control form-control-sm" style="width:150px" name="note" placeholder="Note" value="<?=e($r['note'] ?? '')?>">
                  <button class="btn btn-sm btn-success">Save</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if(!$rows): ?><tr><td colspan="4" class="text-center text-muted py-4">No users found.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
