<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/User.php';
require_once __DIR__.'/../../app/Models/ActivityLog.php';

$user = requireAuth(['admin']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $act = $_POST['action'] ?? '';

    if ($act === 'create') {
        $name = trim($_POST['name'] ?? ''); $email = trim($_POST['email'] ?? '');
        $pass = $_POST['password'] ?? '';   $role  = $_POST['role'] ?? 'driver';
        $phone= trim($_POST['phone'] ?? '');
        if (!$name || !$email || !$pass) {
            flash('dash', t('fill_all_fields'), 'danger');
        } elseif (User::findByEmail($email)) {
            flash('dash', t('email_exists'), 'danger');
        } else {
            $id = User::adminCreate([
                'name'=>$name, 'email'=>$email, 'password'=>$pass,
                'role'=>$role, 'phone'=>$phone,
            ]);
            ActivityLog::record($user['id'],'create_user','user',$id,$email);
            flash('dash', t('user_created'));
        }
        redirect(BASE_URL.'/admin/users.php');
    }

    $id = (int)($_POST['id'] ?? 0);

    if ($act === 'role' && $id) {
        User::updateRole($id, $_POST['role'] ?? 'driver');
        ActivityLog::record($user['id'],'change_role','user',$id,$_POST['role'] ?? '');
        flash('dash', t('role_changed'));
        redirect(BASE_URL.'/admin/users.php');
    }

    if ($act === 'reset' && $id) {
        $np = $_POST['new_password'] ?? '';
        if (strlen($np) >= 4) {
            User::resetPassword($id, $np);
            ActivityLog::record($user['id'],'reset_password','user',$id);
            flash('dash', t('password_reset'));
        }
        redirect(BASE_URL.'/admin/users.php');
    }

    if ($act === 'delete' && $id) {
        if ($id === (int)$user['id']) {
            flash('dash', t('cannot_delete_self'), 'danger');
        } else {
            $target = User::find($id);
            if ($target && $target['role'] === 'admin' && User::countAdmins() <= 1) {
                flash('dash', t('last_admin'), 'danger');
            } else {
                User::deleteById($id);
                ActivityLog::record($user['id'],'delete_user','user',$id, $target['email'] ?? '');
                flash('dash', t('user_deleted'));
            }
        }
        redirect(BASE_URL.'/admin/users.php');
    }
}

$search = trim($_GET['q'] ?? '');
$role   = $_GET['role'] ?? '';
$users  = User::all($search, $role);
$roleLabels = ['owner'=>t('owner_role'),'driver'=>t('driver_role'),'officer'=>t('officer_role'),'admin'=>t('admin_role')];

$pageTitle  = t('manage_users');
$activePage = BASE_URL.'/admin/users.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<div class="page-header" style="display:flex;justify-content:space-between;align-items:center">
  <div><h2>👥 <?= t('manage_users') ?> <span style="font-size:14px;color:var(--text-muted)">(<?= count($users) ?>)</span></h2></div>
  <div style="display:flex;gap:8px">
    <button class="btn btn-secondary" onclick="openCreate('officer')">👮 <?= t('add_officer') ?></button>
    <button class="btn btn-primary" onclick="openCreate('')">➕ <?= t('add_user') ?></button>
  </div>
</div>

<!-- بحث وتصفية -->
<div class="card" style="margin-bottom:16px">
  <div class="card-body">
    <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end">
      <div class="form-group" style="flex:1;min-width:200px;margin:0">
        <label class="form-label"><?= t('search') ?></label>
        <input type="text" name="q" class="form-control" value="<?= e($search) ?>" placeholder="<?= t('search') ?>...">
      </div>
      <div class="form-group" style="min-width:160px;margin:0">
        <label class="form-label"><?= t('role') ?></label>
        <select name="role" class="form-control">
          <option value=""><?= t('all') ?></option>
          <?php foreach($roleLabels as $rk=>$rl): ?>
          <option value="<?= $rk ?>" <?= $role===$rk?'selected':'' ?>><?= e($rl) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button class="btn btn-primary">🔍 <?= t('filter') ?></button>
    </form>
  </div>
</div>

<!-- جدول المستخدمين -->
<div class="card">
  <div style="overflow-x:auto">
    <table class="table" style="width:100%;border-collapse:collapse">
      <thead>
        <tr style="border-bottom:1px solid var(--border)">
          <th style="padding:12px"><?= t('full_name') ?></th>
          <th style="padding:12px"><?= t('email') ?></th>
          <th style="padding:12px"><?= t('phone') ?></th>
          <th style="padding:12px"><?= t('role') ?></th>
          <th style="padding:12px"><?= t('registered_at') ?></th>
          <th style="padding:12px"><?= t('actions') ?></th>
        </tr>
      </thead>
      <tbody>
      <?php if(empty($users)): ?>
        <tr><td colspan="6" style="padding:24px;text-align:center;color:var(--text-muted)"><?= t('no_data') ?></td></tr>
      <?php else: foreach($users as $u): ?>
        <tr style="border-bottom:1px solid var(--border)">
          <td style="padding:12px;font-weight:600"><?= e($u['name']) ?></td>
          <td style="padding:12px"><?= e($u['email']) ?></td>
          <td style="padding:12px"><?= e($u['phone'] ?: '—') ?></td>
          <td style="padding:12px">
            <form method="POST" style="display:flex;gap:4px;align-items:center">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="role">
              <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
              <select name="role" class="form-control" style="padding:4px 8px;font-size:13px" onchange="this.form.submit()">
                <?php foreach($roleLabels as $rk=>$rl): ?>
                <option value="<?= $rk ?>" <?= $u['role']===$rk?'selected':'' ?>><?= e($rl) ?></option>
                <?php endforeach; ?>
              </select>
            </form>
          </td>
          <td style="padding:12px;font-size:13px;color:var(--text-muted)"><?= e(substr($u['created_at'],0,10)) ?></td>
          <td style="padding:12px;white-space:nowrap">
            <button class="btn btn-sm btn-secondary" onclick="document.getElementById('rp<?= (int)$u['id'] ?>').style.display='flex'">🔑</button>
            <?php if((int)$u['id'] !== (int)$user['id']): ?>
            <form method="POST" style="display:inline" onsubmit="return confirm('<?= e(t('delete_user')) ?>?')">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
              <button class="btn btn-sm btn-danger">🗑️</button>
            </form>
            <?php endif; ?>
            <form method="POST" id="rp<?= (int)$u['id'] ?>" style="display:none;gap:4px;margin-top:6px">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="reset">
              <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
              <input type="text" name="new_password" class="form-control" style="padding:4px 8px;font-size:13px" placeholder="<?= t('new_password') ?>" required>
              <button class="btn btn-sm btn-primary">✓</button>
            </form>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- نموذج مستخدم جديد -->
<div class="card" id="newUser" style="margin-top:20px;display:none">
  <div class="card-header"><span class="card-title"><?= t('new_user') ?></span></div>
  <div class="card-body">
    <form method="POST">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="create">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
        <div class="form-group"><label class="form-label"><?= t('full_name') ?></label><input type="text" name="name" class="form-control" required></div>
        <div class="form-group"><label class="form-label"><?= t('email') ?></label><input type="email" name="email" class="form-control" required></div>
        <div class="form-group"><label class="form-label"><?= t('phone') ?></label><input type="text" name="phone" class="form-control"></div>
        <div class="form-group"><label class="form-label"><?= t('password') ?></label><input type="text" name="password" class="form-control" required></div>
        <div class="form-group">
          <label class="form-label"><?= t('role') ?></label>
          <select name="role" id="createRole" class="form-control">
            <?php foreach($roleLabels as $rk=>$rl): ?>
            <option value="<?= $rk ?>" <?= $rk==='driver'?'selected':'' ?>><?= e($rl) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div style="display:flex;gap:10px;margin-top:8px">
        <button type="submit" class="btn btn-primary">💾 <?= t('save') ?></button>
        <a href="<?= BASE_URL ?>/admin/users.php" class="btn btn-secondary"><?= t('cancel') ?></a>
      </div>
    </form>
  </div>
</div>

<script>
function openCreate(role){
  var box = document.getElementById('newUser');
  box.style.display = 'block';
  if(role){ var sel = document.getElementById('createRole'); if(sel) sel.value = role; }
  box.scrollIntoView({behavior:'smooth'});
}
</script>

<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
