<?php
declare(strict_types=1);
session_name('SBMSESSID');
session_start();
ini_set('display_errors','1');
error_reporting(E_ALL);

/* ===== DB ===== */
$DB_HOST = '127.0.0.1';
$DB_PORT = '3307';
$DB_NAME = 'sbm_db';
$DB_USER = 'root';
$DB_PASS = '';
$DB_CHAR = 'utf8mb4';

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function post(string $k, $default = '') { return $_POST[$k] ?? $default; }

try {
  $pdo = new PDO("mysql:host=$DB_HOST;port=$DB_PORT;dbname=$DB_NAME;charset=$DB_CHAR", $DB_USER, $DB_PASS, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
  try { $pdo->exec("SET time_zone = '+05:30'"); } catch(Throwable $e) {}
} catch (Throwable $e) {
  die("DB connection failed: " . $e->getMessage());
}

/* ===== LOGOUT (when logged in) ===== */
if (!empty($_SESSION['super_admin_logged']) && ($_GET['logout'] ?? '') === '1') {
  $_SESSION = [];
  if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time()-42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
  }
  session_destroy();
  header("Location: admin_create.php"); // back to login
  exit;
}

/* ===== LOGIN GUARD ===== */
if (empty($_SESSION['super_admin_logged'])) {
  $ERR = '';
  if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_submit'])) {
    $u = trim($_POST['login_user'] ?? '');
    $p = $_POST['login_pass'] ?? '';
    $st = $pdo->prepare("SELECT username,password_hash FROM admin_users WHERE role='super_admin' AND username=? AND is_active=1 LIMIT 1");
    $st->execute([$u]);
    $row = $st->fetch();
    if ($row && password_verify($p, $row['password_hash'])) {
      $_SESSION['super_admin_logged'] = true;
      header("Location: admin_create.php");
      exit;
    } else $ERR = "Invalid super admin credentials.";
  }
  ?>
  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Super Admin Login - WS</title>
    
  <link rel="icon" type="image/png" href="favicon-ws.png">
    <style><?php include __DIR__ . '/theme.css'; ?></style>
  </head>
  <body class="auth">
      <body class="auth">

  <!-- Top Home button -->
  <!-- Home button above login card -->
<div class="home-wrap">
 <a class="home-btn" href="../home.php">Home</a>
</div>

<style>
.auth{
  min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px;
  flex-direction: column;            /*  stack vertically */
  gap: 10px;                         /* optional spacing */
}
/* Position home button above login card */
.home-wrap {
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}

/* Same green style as other pages */
.home-btn {
  background: linear-gradient(135deg, #2fa84f, #1f7a39);
  color: #fff;
  text-decoration: none;
  border: none;
  padding: 8px 14px;
  border-radius: 10px;
  font-weight: 700;
  box-shadow: 0 2px 4px rgba(31, 122, 57, 0.2);
  transition: filter 0.2s ease-in-out;
}
.home-btn:hover {
  filter: brightness(1.08);
}
</style>

    <div class="auth-card">
      <h1>Super Admin Login</h1>
      <?php if (!empty($ERR)): ?><div class="alert"><?=h($ERR)?></div><?php endif; ?>
      <form method="post">
        <input type="text" name="login_user" placeholder="Username"required>
        <!--<label>Password<input type="password" name="login_pass" required></label>-->
        
<div class="password-wrapper">
  <input type="password" id="login_pass" name="login_pass" placeholder="Password" required>
  <button type="button" class="toggle-password" aria-label="Show password" aria-pressed="false">
    <svg class="eye-open" viewBox="0 0 24 24" width="22" height="22">
      <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      <circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    <svg class="eye-closed" viewBox="0 0 24 24" width="22" height="22" style="display:none">
      <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      <circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      <line x1="2" y1="2" x2="22" y2="22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
  </button>
</div>
<style>
    .password-wrapper {
  position: relative;
  width: 100%;
}

.password-wrapper input {
  width: 100%;
  padding: 10px 40px 10px 12px; /* right padding for icon space */
  border: 1px solid #ccc;
  border-radius: 8px;
  font-size: 1rem;
  box-sizing: border-box;
}

.password-wrapper .toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  color: #555; /* neutral gray */
}

.password-wrapper .toggle-password:hover {
  color: #000; /* darken slightly on hover */
}

.password-wrapper svg {
  pointer-events: none;
}


</style>
<script>
(function(){
  const wrap = document.querySelector('.password-wrapper');
  if(!wrap) return;
  const input = wrap.querySelector('input');
  const btn   = wrap.querySelector('.toggle-password');
  const open  = wrap.querySelector('.eye-open');
  const off   = wrap.querySelector('.eye-closed');

  btn.addEventListener('click', ()=>{
    const isPwd = input.type === 'password';
    input.type = isPwd ? 'text' : 'password';
    open.style.display = isPwd ? 'none' : 'inline';
    off.style.display  = isPwd ? 'inline' : 'none';
    btn.setAttribute('aria-label', isPwd ? 'Hide password' : 'Show password');
    btn.setAttribute('aria-pressed', String(isPwd));
  });
})();
</script>


        <button type="submit" name="login_submit">Login</button>
      </form>
      <div class="help">Only Super Admin can access Admin Creation</div>
    </div>
  </body>
  </html>
  <?php
  exit;
}

/* ===== ADMIN CREATE PAGE ===== */
$ERR = $OK = '';
$districts = $pdo->query("SELECT id,name FROM districts ORDER BY name")->fetchAll();

$selDist = (int)post('district_id', 0);
$ulbArgs = [];
$ulbWhere = '';
if ($selDist > 0) { $ulbWhere = "WHERE district_id=:d"; $ulbArgs['d']=$selDist; }
$st = $pdo->prepare("SELECT id,name FROM ulbs {$ulbWhere} ORDER BY name");
$st->execute($ulbArgs);
$ulbs = $st->fetchAll();

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['create_submit'])) {
  try {
    $username    = trim(post('username'));
    $password    = (string)post('password');
    $role        = trim((string)post('role','0')); // default 0
    $district_id = (int)post('district_id',0);
    $ulb_id      = (int)post('ulb_id',0);

    if ($username==='' || !preg_match('/^[a-zA-Z0-9._-]{3,100}$/',$username)) throw new RuntimeException('Enter valid username.');
    if (strlen($password) < 3) throw new RuntimeException('Password too short.');
    if ($role === '0') throw new RuntimeException('Please select a role.');
    $allowedRoles = ['district_admin','ulb_admin'];
    if (!in_array($role,$allowedRoles,true)) throw new RuntimeException('Invalid role.');

    if ($role==='district_admin' && $district_id<=0) throw new RuntimeException('Select district.');
    if ($role==='ulb_admin' && $ulb_id<=0) throw new RuntimeException('Select ULB.');

    $st=$pdo->prepare("SELECT 1 FROM admin_users WHERE username=? LIMIT 1");
    $st->execute([$username]);
    if ($st->fetchColumn()) throw new RuntimeException('Username already exists.');

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $st=$pdo->prepare("INSERT INTO admin_users (username,password_hash,role,is_active,created_at,district_id,ulb_id)
      VALUES(:u,:p,:r,1,NOW(),:did,:uid)");
    $st->execute(['u'=>$username,'p'=>$hash,'r'=>$role,'did'=>$district_id?:null,'uid'=>$ulb_id?:null]);

    $OK='Admin user created successfully.';
    $_POST=[];
    $ulbs=$pdo->query("SELECT id,name FROM ulbs ORDER BY name")->fetchAll();
  } catch(Throwable $e){ $ERR=$e->getMessage(); }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Add Admin User - WS</title>
  <link rel="icon" type="image/png" href="favicon-ws.png">
  <style><?php include __DIR__ . '/theme.css'; ?></style>
</head>
<body class="auth">
<div class="auth-card">

  <!--Top actions: Home (left) + Logout (right) -->
  <div style="
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:6px;
  ">

    <!-- Home button -->
      <a href="../home.php" style="
      background:linear-gradient(135deg,#2fa84f,#1f7a39);
      color:#fff;
      text-decoration:none;
      border:none;
      padding:8px 14px;
      border-radius:10px;
      font-weight:700;
      box-shadow:0 2px 4px rgba(31,122,57,0.2);
      transition:all .2s ease-in-out;
    "
    onmouseover="this.style.filter='brightness(1.1)'"
    onmouseout="this.style.filter='brightness(1)'">
      Home
    </a>

    <!--´ Logout button -->
    <a href="?logout=1" style="
      background:linear-gradient(135deg,#ff4b4b,#b30000);
      color:#fff;
      text-decoration:none;
      border:none;
      padding:8px 14px;
      border-radius:10px;
      font-weight:700;
      box-shadow:0 2px 4px rgba(179,0,0,0.2);
      transition:all .2s ease-in-out;
    "
    onmouseover="this.style.filter='brightness(1.1)'"
    onmouseout="this.style.filter='brightness(1)'">
      Logout
    </a>

  </div>


    <h1>Add Admin User</h1>
    <?php if ($OK): ?><div class="alert" style="background:#ecfff2;border-color:rgba(47,168,79,0.2);color:#1f7a39;"><?=h($OK)?></div><?php endif; ?>
    <?php if ($ERR): ?><div class="alert"><?=h($ERR)?></div><?php endif; ?>

    <form method="post">
      <label>Username
        <input type="text" name="username" value="<?=h((string)post('username'))?>" required>
      </label>

      <label>Password
        <input type="text" name="password" required>
      </label>

      <label>Role
        <select name="role" id="role" required>
          <option value="0" <?= post('role','0')==='0'?'selected':''; ?>>--Select--</option>
          <option value="district_admin" <?= post('role')==='district_admin'?'selected':''; ?>>District Admin</option>
          <option value="ulb_admin"      <?= post('role')==='ulb_admin'?'selected':''; ?>>ULB Admin</option>
          
        </select>
      </label>

      <label>District
        <select name="district_id" id="district">
          <option value="0">--Select--</option>
          <?php foreach ($districts as $d): ?>
            <option value="<?= (int)$d['id'] ?>" <?= (int)post('district_id')===(int)$d['id']?'selected':''; ?>>
              <?= h($d['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>

      <label>ULB
        <select name="ulb_id" id="ulb">
          <option value="0">--Select--</option>
          <?php foreach ($ulbs as $u): ?>
            <option value="<?= (int)$u['id'] ?>" <?= (int)post('ulb_id')===(int)$u['id']?'selected':''; ?>>
              <?= h($u['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>

      <button type="submit" name="create_submit">Create</button>
    </form>
    <div class="help">Use this page to create new Admins (Super Admin only)</div>
  </div>

  <script>
    const roleSel=document.getElementById('role');
    const distSel=document.getElementById('district');
    const ulbSel=document.getElementById('ulb');

    function applyRoleUI(){
      const r=roleSel.value;

      if (r==='0'){ // default state
        distSel.disabled = true; distSel.required = false; distSel.selectedIndex = 0;
        ulbSel.disabled  = true; ulbSel.required  = false; ulbSel.selectedIndex  = 0;
        return;
      }
      if(r==='district_admin'){
        ulbSel.disabled=true; ulbSel.required=false; ulbSel.selectedIndex=0;
        distSel.disabled=false; distSel.required=true;
      }else if(r==='ulb_admin'){
        ulbSel.disabled=false; ulbSel.required=true;
        distSel.disabled=false; distSel.required=false; // optional
      }
    }

    document.addEventListener('DOMContentLoaded', applyRoleUI);
    roleSel.addEventListener('change', applyRoleUI);
    distSel.addEventListener('change', ()=>{ if(roleSel.value==='ulb_admin'){ ulbSel.selectedIndex=0; }});
  </script>
</body>
</html>


