<?php
require_once __DIR__ . '/includes/initialize.php';

/* Require login (stay inside console) */
if (!is_logged_in()) {
  redirect('/adminconsole/login.php?next=' . urlencode($_SERVER['REQUEST_URI']));
}
$me = $_SESSION['admin_user'] ?? null;
$myrole = strtolower($me['role'] ?? '');
$can_manage = in_array($myrole, ['superadmin','admin','owner','root','manager','staff']); // adjust as you like
if (!$can_manage) {
  http_response_code(403);
  die('<!doctype html><meta charset="utf-8"><title>Forbidden</title><div style="font:14px system-ui;padding:24px;color:#e11d48;background:#0b1220">Access denied</div>');
}

$err = ''; $ok = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tok    = $_POST['csrf'] ?? '';
    $name   = trim($_POST['name'] ?? '');
    $email  = trim($_POST['email'] ?? '');
    $mobile = preg_replace('/\D+/', '', (string)($_POST['mobile'] ?? ''));
    $pass   = (string)($_POST['password'] ?? '');
    $cpass  = (string)($_POST['confirm_password'] ?? '');
    $role   = trim($_POST['role'] ?? 'staff');
    $status = (int)($_POST['status'] ?? 1);

    if (!verify_csrf($tok)) {
        $err = 'Invalid request. Please refresh and try again.';
    } elseif ($name === '' || $pass === '' || $cpass === '') {
        $err = 'Please fill all required fields.';
    } elseif ($pass !== $cpass) {
        $err = 'Passwords do not match.';
    } elseif ($email === '' && $mobile === '') {
        $err = 'Enter at least Email or Mobile.';
    } elseif ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $err = 'Enter a valid email address.';
    } elseif ($mobile !== '' && strlen($mobile) < 10) {
        $err = 'Enter a valid mobile number (min 10 digits).';
    } else {
        // Duplicate check (email or mobile)
        $dup_sql = "SELECT id FROM jos_admin_users
                    WHERE ( ? <> '' AND LOWER(email)=LOWER(?) )
                       OR ( ? <> '' AND mobile_no = ? )
                    LIMIT 1";
        if ($st = $con->prepare($dup_sql)) {
            $st->bind_param('ssss', $email, $email, $mobile, $mobile);
            $st->execute();
            $dup = $st->get_result()->fetch_assoc();
            $st->close();

            if ($dup) {
                $err = 'User already exists with this email or mobile.';
            } else {
                $hash = password_hash($pass, PASSWORD_DEFAULT);
                if ($ins = $con->prepare("INSERT INTO jos_admin_users (name,email,mobile_no,password_hash,role,status) VALUES (?,?,?,?,?,?)")) {
                    $ins->bind_param('sssssi', $name, $email, $mobile, $hash, $role, $status);
                    if ($ins->execute()) {
                        $ins->close();
                        $ok = 'User created successfully.';
                        // clear POST fields
                        $_POST = [];
                    } else {
                        $err = 'Could not create user. Please try again.';
                        $ins->close();
                    }
                } else {
                    $err = 'Server error creating user.';
                }
            }
        } else {
            $err = 'Server error. Please try again.';
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Admin User</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" type="image/jpeg" href="/adminconsole/uploads/logo.jpeg">
<style>
  :root{--bg:#0f172a;--panel:#111827;--line:#1f2937;--text:#e2e8f0;--muted:#9ca3af;--brand:#3b82f6;}
  *{box-sizing:border-box}
  body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;margin:0;display:flex;align-items:center;justify-content:center;padding:16px}
  .card{background:var(--panel);border:1px solid var(--line);border-radius:18px;width:100%;max-width:560px;box-shadow:0 10px 40px rgba(0,0,0,.45);padding:22px 22px 18px}
  .brand{display:flex;align-items:center;justify-content:center;margin-bottom:12px}
  .brand img{max-width:220px;height:auto;display:block}
  h1.title{margin:6px 0 14px;text-align:center;font-size:24px}
  label{display:block;font-size:14px;margin:12px 0 6px}
  .control{width:100%;display:block;padding:12px 14px;border-radius:12px;border:1px solid #374151;background:#0b1220;color:var(--text);outline:none}
  .control:focus{border-color:#4b5563;box-shadow:0 0 0 3px rgba(59,130,246,.25)}
  .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
  .btn{width:100%;display:inline-block;text-align:center;padding:12px 14px;border-radius:12px;border:0;background:var(--brand);color:#fff;font-weight:700;margin-top:16px;cursor:pointer}
  .err{background:#7f1d1d;color:#fecaca;padding:10px 12px;border-radius:10px;margin:8px 0 12px;text-align:center}
  .ok{background:#065f46;color:#d1fae5;padding:10px 12px;border-radius:10px;margin:8px 0 12px;text-align:center}
  .hint{font-size:12px;color:#9ca3af;text-align:center;margin-top:10px}
  a.link{color:#93c5fd;text-decoration:none}
</style>
</head>
<body>
  <div class="card">
    <div class="brand">
      <img src="/adminconsole/uploads/logo.jpeg?v=<?php echo time()%1000; ?>"
           onerror="this.onerror=null;this.src='/adminconsole/uploads/logo.png?v=<?php echo time()%1000; ?>';"
           alt="Pacific iConnect Logo">
    </div>

    <h1 class="title">Add Admin User</h1>

    <?php if($ok): ?><div class="ok"><?=htmlspecialchars($ok)?></div><?php endif; ?>
    <?php if($err): ?><div class="err"><?=htmlspecialchars($err)?></div><?php endif; ?>

    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">

      <label for="name">Full Name*</label>
      <input id="name" name="name" class="control" required value="<?=htmlspecialchars($_POST['name']??'')?>">

      <div class="row">
        <div>
          <label for="email">Email</label>
          <input id="email" name="email" type="email" class="control" value="<?=htmlspecialchars($_POST['email']??'')?>">
        </div>
        <div>
          <label for="mobile">Mobile</label>
          <input id="mobile" name="mobile" class="control" inputmode="numeric" pattern="[0-9]*" value="<?=htmlspecialchars($_POST['mobile']??'')?>">
        </div>
      </div>

      <div class="row">
        <div>
          <label for="password">Password*</label>
          <input id="password" name="password" type="password" class="control" required>
        </div>
        <div>
          <label for="confirm_password">Confirm Password*</label>
          <input id="confirm_password" name="confirm_password" type="password" class="control" required>
        </div>
      </div>

      <div class="row">
        <div>
          <label for="role">Role</label>
          <select id="role" name="role" class="control">
            <option value="staff" <?= (($_POST['role']??'staff')==='staff'?'selected':'') ?>>Staff</option>
            <option value="manager" <?= (($_POST['role']??'')==='manager'?'selected':'') ?>>Manager</option>
            <option value="admin" <?= (($_POST['role']??'')==='admin'?'selected':'') ?>>Admin</option>
            <option value="superadmin" <?= (($_POST['role']??'')==='superadmin'?'selected':'') ?>>Superadmin</option>
          </select>
        </div>
        <div>
          <label for="status">Status</label>
          <select id="status" name="status" class="control">
            <?php $st=(int)($_POST['status']??1); ?>
            <option value="1" <?= $st===1?'selected':'' ?>>Active</option>
            <option value="0" <?= $st===0?'selected':'' ?>>Inactive</option>
          </select>
        </div>
      </div>

      <button class="btn" type="submit">Create User</button>
    </form>

    <div class="hint" style="margin-top:14px">
      Back to dashboard? <a class="link" href="/adminconsole/index.php">Open</a>
    </div>
  </div>
</body>
</html>
