<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_login();

if (!in_array($_SESSION['user_role'] ?? '', ['owner','admin'], true)) {
  http_response_code(403);
  die("Forbidden");
}

$pdo = db();
ensure_audit_tables($pdo);
$cid = (int)$_SESSION['company_id'];

$err = '';
if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $pass = (string)($_POST['password'] ?? '');
  $role = $_POST['role'] ?? 'user';

  if(!$name || !$email || !$pass || !in_array($role,['admin','user'],true)){
    $err = "تحقق من البيانات";
  } else {
    try{
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare("INSERT INTO users (company_id,name,email,password_hash,role) VALUES (?,?,?,?,?)");
      $stmt->execute([$cid,$name,$email,$hash,$role]);
      $newUserId = (int)$pdo->lastInsertId();
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>(int)($_SESSION['user_id'] ?? 0),'module'=>'users','action'=>'CREATE','entity_type'=>'user','entity_id'=>(string)$newUserId,'description'=>'إضافة مستخدم جديد: ' . $name]);
      flash_set('تم إضافة المستخدم بنجاح');
      header("Location: " . url('/users/index.php'));
      exit;
    } catch(Throwable $e){
      $err = "خطأ: " . $e->getMessage();
    }
  }
}

render_layout("إضافة مستخدم", "الرئيسية <span class='mx-1'>/</span> إدارة المستخدمين <span class='mx-1'>/</span> إضافة مستخدم", function() use ($err) {
?>
<div class="row g-3 mt-3">
  <div class="col-12 col-xl-8">
    <div class="card cardx p-3">
      <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
      <form method="post" class="row g-3">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <div class="col-12 col-md-6">
          <label class="form-label">الاسم</label>
          <input class="form-control" name="name" required>
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">البريد</label>
          <input class="form-control" name="email" type="email" required>
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">كلمة المرور</label>
          <input class="form-control" name="password" type="password" required>
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">الدور</label>
          <select class="form-select selectpicker" data-live-search="true" name="role">
            <option value="user">User</option>
            <option value="admin">Admin</option>
          </select>
          <div class="text-secondary small mt-1">Owner يتحدد تلقائيًا عند إنشاء الشركة.</div>
        </div>
        <div class="col-12 d-flex gap-2">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ</button>
          <a class="btn btn-outline-secondary" href="<?= url('/users/index.php') ?>">إلغاء</a>
        </div>
      </form>
    </div>
  </div>
</div>
<?php }); ?>
