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

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

$err = '';
$openModal = false;
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,phone,avatar_path,password_hash,role) VALUES (?,?,?,?,?,?,?)");
      $stmt->execute([$cid,$name,$email,null,null,$hash,$role]);
      flash_set('تم إضافة المستخدم بنجاح');
      header("Location: " . url('/users/index.php'));
      exit;
    } catch(Throwable $e){
      $err = 'خطأ: ' . $e->getMessage();
    }
  }
  $openModal = true;
}

$stmt = $pdo->prepare("SELECT id,name,email,phone,role,is_active,created_at FROM users WHERE company_id=? ORDER BY id DESC");
$stmt->execute([$cid]);
$rows = $stmt->fetchAll();

render_layout("المستخدمين", "الرئيسية <span class='mx-1'>/</span> إدارة المستخدمين <span class='mx-1'>/</span> المستخدمين", function() use ($rows,$err,$openModal) {
?>
<div class="card cardx mt-3">
  <div class="p-3 d-flex align-items-center justify-content-between flex-wrap gap-2">
    <div>
      <div class="fw-bold">المستخدمين</div>
      <div class="text-secondary small">إدارة المستخدمين تتم الآن من خلال Modal داخل نفس الصفحة.</div>
    </div>
    <button class="btn btn-dark btn-sm" data-bs-toggle="modal" data-bs-target="#userCreateModal"><i class="bi bi-plus-lg"></i> إضافة مستخدم</button>
  </div>

  <?php if($err): ?>
    <div class="px-3 pb-0"><div class="alert alert-danger mb-0"><?= h($err) ?></div></div>
  <?php endif; ?>

  <div class="table-responsive px-3 pb-3 pt-3">
    <table class="table align-middle mb-0">
      <thead>
        <tr class="text-secondary small">
          <th>#</th>
          <th>الاسم</th>
          <th>البريد</th>
          <th>الموبايل</th>
          <th>الدور</th>
          <th>الحالة</th>
        </tr>
      </thead>
      <tbody>
        <?php if(!$rows): ?>
          <tr><td colspan="6" class="text-center text-secondary py-4">لا توجد بيانات</td></tr>
        <?php else: foreach($rows as $u): ?>
          <tr>
            <td class="text-secondary"><?= (int)$u['id'] ?></td>
            <td class="fw-semibold"><?= h($u['name']) ?></td>
            <td class="text-secondary"><?= h($u['email']) ?></td>
            <td class="text-secondary"><?= h($u['phone'] ?? '-') ?></td>
            <td><span class="badge bg-dark-subtle text-dark border border-dark-subtle"><?= h($u['role']) ?></span></td>
            <td>
              <?php if((int)$u['is_active']===1): ?>
                <span class="badge bg-success-subtle text-success border border-success-subtle">نشط</span>
              <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle">معطل</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade modal-erp" id="userCreateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <div class="modal-header">
          <h5 class="modal-title">إضافة مستخدم</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-12 col-md-6">
              <label class="form-label">الاسم</label>
              <input class="form-control" name="name" required value="<?= h($_POST['name'] ?? '') ?>">
            </div>
            <div class="col-12 col-md-6">
              <label class="form-label">البريد</label>
              <input class="form-control" name="email" type="email" required value="<?= h($_POST['email'] ?? '') ?>">
            </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" data-width="100%" name="role">
                <option value="user" <?= (($_POST['role'] ?? 'user') === 'user') ? 'selected' : '' ?>>User</option>
                <option value="admin" <?= (($_POST['role'] ?? '') === 'admin') ? 'selected' : '' ?>>Admin</option>
              </select>
              <div class="text-secondary small mt-1">Owner يتحدد تلقائيًا عند إنشاء الشركة.</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($openModal): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('userCreateModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
