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

/* ---------- DB CREDS (same as project) ---------- */
$cfg = require __DIR__ . '/../includes/config.php';
$db = $cfg['db'] ?? [];

$DB_HOST = (string)($db['host'] ?? '127.0.0.1');
$DB_PORT = (string)($db['port'] ?? '');
$DB_NAME = (string)($db['name'] ?? '');
$DB_USER = (string)($db['user'] ?? '');
$DB_PASS = (string)($db['pass'] ?? '');
$DB_CHAR = (string)($db['charset'] ?? 'utf8mb4');

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

try {
  $dsn = "mysql:host=$DB_HOST;" . ($DB_PORT !== '' ? "port=$DB_PORT;" : '') . "dbname=$DB_NAME;charset=$DB_CHAR";
  $pdo = new PDO($dsn, $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 (if already logged in) ---------- */
if (!empty($_SESSION['super_admin_logged']) && isset($_GET['logout']) && $_GET['logout']=='1') {
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time()-42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
  }
  session_destroy();
  header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); // back to login
  exit;
}

/* ---------- LOGIN GATE: show login first ---------- */
if (empty($_SESSION['super_admin_logged'])) {
  $ERR = '';
  if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['login_submit'])) {
    $u = trim($_POST['login_user'] ?? '');
    $p = (string)($_POST['login_pass'] ?? '');
    $st = $pdo->prepare("SELECT username, password_hash FROM admin_users WHERE role='super_admin' AND is_active=1 AND username=? LIMIT 1");
    $st->execute([$u]);
    $row = $st->fetch();
    if ($row && password_verify($p, $row['password_hash'])) {
      $_SESSION['super_admin_logged'] = true;
      header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); // reload page content
      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</title>
    <link rel="icon" type="image/png" href="favicon-ws.png">
    <link rel="stylesheet" href="assets/bootstrap.min.css">
    <link rel="stylesheet" href="assets/gov-ui.css?v=1">
    <style>
      :root{
        --bg:#ffffff; --card:#fff6ec; --muted:#6b766b; --text:#0b0b0b;
        --accent:#2fa84f; --radius:18px;
      }
      body{background:var(--bg); color:var(--text); font-family:Inter,system-ui,Segoe UI,Arial,sans-serif;}
     .auth{
  min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px;
  flex-direction: column;            /* 🔑 stack vertically */
  gap: 10px;                         /* optional spacing */
}

      .auth-card{width:100%; max-width:420px; background:var(--card); border:1px solid rgba(0,0,0,.06);
        border-radius:16px; padding:24px 22px; box-shadow:0 10px 30px rgba(18,20,18,.06);}
      .auth-card h1{margin:0 0 14px; font-size:26px; font-weight:800;}
      .auth-card .alert{background:#fff4f4; border:1px solid rgba(255,107,107,.12); color:#7a1111; border-radius:12px; padding:10px 12px; margin-bottom:12px;}
      .auth-card label{display:grid; gap:6px; font-size:13px; color:var(--muted); margin-bottom:10px;}
      .auth-card input{padding:12px 14px; border-radius:12px; border:1px solid rgba(0,0,0,.15); background:#fff; color:#111; font-weight:500;
        box-shadow:inset 0 1px 2px rgba(0,0,0,.04);}
      .auth-card input:focus{border-color:#2fa84f; box-shadow:0 0 0 3px rgba(47,168,79,.2); outline:none;}
      .auth-card button{margin-top:4px; background:linear-gradient(135deg,var(--accent),#1f7a39); border:none; color:#fff;
        padding:12px 16px; border-radius:12px; cursor:pointer; font-weight:700; width:100%;}
      .auth-card .help{margin-top:10px; color:var(--muted); font-size:12px; text-align:center;}
    </style>
  </head>
   <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>
/* 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>


  <form class="auth-card" method="post">
    <h1>Super Admin Login</h1>
    <?php if($ERR): ?><div class="alert"><?=h($ERR)?></div><?php endif; ?>
    <input type="text" name="login_user" placeholder="Username" required>

    <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>

/* --- Force proper box model & spacing --- */
.auth-card input[type="text"],
.auth-card input[type="password"]{
  display:block !important;
  width:100% !important;
  box-sizing:border-box !important;
  margin:0 0 14px 0 !important;
  padding:12px 44px 12px 14px !important; /* room for eye on right */
  border:1px solid #d7dbe0 !important;
  border-radius:12px !important;
  font-size:16px !important;
  line-height:1.2 !important;
  background:#fff !important;
}

/* --- Keep the icon INSIDE the field on the right --- */
.password-wrapper{
  position:relative !important;
  width:100% !important;
}

.password-wrapper .toggle-password{
  position:absolute !important;
  right:12px !important;
  top:50% !important;
  transform:translateY(-50%) !important;
  background:transparent !important;
  border:none !important;
  padding:0 !important;
  margin:0 !important;
  width:24px !important;
  height:24px !important;
  display:flex !important;
  align-items:center !important;
  justify-content:center !important;
  color:#777 !important;      /* no green */
  cursor:pointer !important;
}

.password-wrapper .toggle-password:hover{ color:#333 !important; }
.password-wrapper svg{ pointer-events:none !important; }
</style>

<script>
(function(){
  const wrap = document.querySelector('.password-wrapper');
  if(!wrap) return;
  const input = wrap.querySelector('input[type="password"], input[type="text"]');
  const btn   = wrap.querySelector('.toggle-password');
  const open  = wrap.querySelector('.eye-open');
  const shut  = wrap.querySelector('.eye-closed');

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

      <button type="submit" name="login_submit">Login</button>
      <div class="help">Only Super Admin can open Executive Registration page.</div>
    </form>
    
  </body>
  </html>
  <?php
  exit;
}

/* ---------- PAGE CONTENT (visible after login) ---------- */
/* remove old redirect to index.php; not needed now */
// if (!empty($_SESSION['user_id'])) { header('Location: index.php'); exit; }

$DATA = include __DIR__ . '/up_admin_tree.php';
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Executive Registration - WS</title>
  <link rel="icon" type="image/png" href="favicon-ws.png">
  <link rel="stylesheet" href="assets/bootstrap.min.css">
  <link rel="stylesheet" href="assets/gov-ui.css?v=1">
  <style>
    .valid-tip{color:#0f9d58;font-weight:600;display:none}
    .invalid-tip{color:#d93025;font-weight:600;display:none}
    .password-wrapper{position:relative}
    .password-wrapper .toggle-password{position:absolute;right:12px;top:50%;transform:translateY(-50%);display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;cursor:pointer;border:0;background:transparent;padding:0;color:#6c757d}
    .password-wrapper .toggle-password svg{width:22px;height:22px;stroke:currentColor;fill:none;stroke-width:2}
    /* top-right red logout */
    .logout-wrap{display:flex;justify-content:flex-end;max-width:860px;margin:0 auto 10px}
    .logout-btn{
      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,.2);
    }
    .logout-btn:hover{filter:brightness(1.08)}
    /* top bar */
.top-actions{
  display:flex; justify-content:space-between; align-items:center;
  max-width:860px; margin:0 auto 10px;
}

/* green Home button */
.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,.2);
}
.home-btn:hover{ filter:brightness(1.08); }

/* existing red Logout button (kept same) */
.logout-btn{
  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,.2);
}
.logout-btn:hover{ filter:brightness(1.08); }

  </style>
</head>
<body class="p-3 p-md-5">
 <!-- Top actions: Home (left) + Logout (right) -->
<div class="top-actions">
  <a class="home-btn" href="home.php">Home</a>
  <a class="logout-btn" href="?logout=1">Logout</a>
</div>


  <div class="container" style="max-width:860px">
    <div class="text-center mb-4">
      <h2 class="fw-bold">Executive Registration</h2>
      <p class="text-muted m-0">One-time registration. Use this to create your Executive account.</p>
    </div>

    <div class="card shadow-sm">
      <div class="card-body p-4">
        <form id="regForm" autocomplete="off">
          <input type="hidden" name="flow" value="register_executive">

          <div class="row g-3">
            <div class="col-md-6">
              <input type="text" pattern="\d{10}" maxlength="10" class="form-control" name="phone" id="phone" placeholder="10-digit mobile (without +91)" required>
              <div class="valid-tip" id="phone-ok">Phone number available ✓</div>
              <div class="invalid-tip" id="phone-bad">Phone already registered ✗</div>
            </div>
            <div class="col-md-6">
              <input type="text" class="form-control" name="full_name" placeholder="Full Name" required>
            </div>
            <div class="col-md-6">
              <input type="email" class="form-control" name="email" id="email" placeholder="Email (ex: example@domain.com)" required>
              <div class="valid-tip" id="email-ok">Email available ✓</div>
              <div class="invalid-tip" id="email-bad">Email already registered ✗</div>
            </div>
            <div class="col-md-6">
              <div class="password-wrapper">
                <input type="password" class="form-control" name="password" minlength="6" placeholder="Password" required>
                <button type="button" class="toggle-password" aria-label="Show password">
                  <svg class="eye-open" viewBox="0 0 24 24">
                    <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z" stroke-linecap="round" stroke-linejoin="round"/>
                    <circle cx="12" cy="12" r="3" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <svg class="eye-closed" viewBox="0 0 24 24" style="display:none">
                    <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z" stroke-linecap="round" stroke-linejoin="round"/>
                    <circle cx="12" cy="12" r="3" stroke-linecap="round" stroke-linejoin="round"/>
                    <line x1="2" y1="2" x2="22" y2="22" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </button>
              </div>
            </div>
            <div class="col-12">
              <input type="text" class="form-control" name="address" placeholder="Full Address" required>
            </div>
            <div class="col-md-6">
              <input type="text" class="form-control" name="home_district" placeholder="District" required>
            </div>
          </div>

          <hr class="my-4">

          <div class="form-section-title mb-2">Assignment (State / Nodal / District / ULB)</div>
          <hr class="mt-1 mb-3">
          <div class="row g-3">
            <div class="col-md-3">
              <select class="form-select" id="duty_state" name="duty_state" required>
                <option value="">-- Select State --</option>
              </select>
            </div>
            <div class="col-md-3">
              <select class="form-select" id="duty_nodal" name="duty_nodal" required disabled>
                <option value="">-- Select Nodal --</option>
              </select>
            </div>
            <div class="col-md-3">
              <select class="form-select" id="duty_district" name="duty_district" required disabled>
                <option value="">-- Select District --</option>
              </select>
            </div>
            <div class="col-md-3">
              <select class="form-select" id="duty_ulb" name="duty_ulb" required disabled>
                <option value="">-- Select ULB --</option>
              </select>
            </div>
          </div>

          <div class="d-grid mt-4">
            <button class="btn btn-success btn-lg" type="submit">Register</button>
          </div>

          <div id="msg" class="alert d-none mt-3" role="alert"></div>
          <style>
            #msg.alert{font-size:1.15rem; padding:14px 16px;}
          </style>

          <hr class="my-4">
          <div class="text-center mt-3">
            <a href="executive_login.php">Already registered? Login</a>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script>
  (function(){
    function $(s,ctx=document){return ctx.querySelector(s)}
    function $$(s,ctx=document){return Array.from(ctx.querySelectorAll(s))}
    $$('.password-wrapper').forEach(wrap=>{
      const input=$('input[type="password"], input[type="text"]',wrap);
      const btn=$('.toggle-password',wrap);
      const open=$('.eye-open',wrap);
      const off=$('.eye-closed',wrap);
      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');
      });
    });
  })();

  const DATA = <?php echo json_encode($DATA, JSON_UNESCAPED_UNICODE); ?>;
  function $$(sel, ctx=document){ return Array.from(ctx.querySelectorAll(sel)); }
  function $(sel, ctx=document){ return ctx.querySelector(sel); }

  const phone=$('#phone'), email=$('#email');
  const phoneOk=$('#phone-ok'), phoneBad=$('#phone-bad');
  const emailOk=$('#email-ok'), emailBad=$('#email-bad');

  let phoneTimer=null, emailTimer=null;
  phone.addEventListener('input', e=>{
    phoneOk.style.display='none'; phoneBad.style.display='none';
    clearTimeout(phoneTimer);
    const val=(e.target.value||'').trim();
    if (!/^\d{10}$/.test(val)) return;
    phoneTimer=setTimeout(async ()=>{
      const r=await fetch('check_available.php?type=phone&value='+encodeURIComponent(val));
      const j=await r.json();
      (j.available?phoneOk:phoneBad).style.display='block';
    },300);
  });
  email.addEventListener('input', e=>{
    emailOk.style.display='none'; emailBad.style.display='none';
    clearTimeout(emailTimer);
    const val=(e.target.value||'').trim();
    if (!/^\S+@\S+\.\S+$/.test(val)) return;
    emailTimer=setTimeout(async ()=>{
      const r=await fetch('check_available.php?type=email&value='+encodeURIComponent(val));
      const j=await r.json();
      (j.available?emailOk:emailBad).style.display='block';
    },300);
  });

  const stateSel=$('#duty_state'), nodalSel=$('#duty_nodal'), districtSel=$('#duty_district'), ulbSel=$('#duty_ulb');
  function clearSelect(sel, placeholder){ sel.innerHTML=`<option value="">${placeholder}</option>`; sel.setAttribute('disabled','disabled'); }
  function enableSelect(sel){ sel.removeAttribute('disabled'); }

  (function initStates(){
    for (const stateKey of Object.keys(DATA)) {
      const s = DATA[stateKey];
      stateSel.insertAdjacentHTML('beforeend', `<option value="${stateKey}">${s.name} (${s.code})</option>`);
    }
    enableSelect(stateSel);
  })();

  function populateNodals(stateKey){
    clearSelect(nodalSel,'-- Select Nodal --'); clearSelect(districtSel,'-- Select District --'); clearSelect(ulbSel,'-- Select ULB --');
    if (!stateKey || !DATA[stateKey]) return;
    const nodals = DATA[stateKey].nodals || {};
    for (const nodalKey of Object.keys(nodals)) {
      const n = nodals[nodalKey];
      nodalSel.insertAdjacentHTML('beforeend', `<option value="${nodalKey}">${nodalKey} (${n.code})</option>`);
    }
    enableSelect(nodalSel);
  }
  function populateDistricts(stateKey, nodalKey){
    clearSelect(districtSel,'-- Select District --'); clearSelect(ulbSel,'-- Select ULB --');
    const n = DATA[stateKey]?.nodals?.[nodalKey];
    if (!n) return;
    const districts = n.districts || {};
    for (const distKey of Object.keys(districts)) {
      const d = districts[distKey];
      districtSel.insertAdjacentHTML('beforeend', `<option value="${distKey}">${distKey} (${d.code})</option>`);
    }
    enableSelect(districtSel);
  }
  function populateULBs(stateKey, nodalKey, distKey){
    clearSelect(ulbSel,'-- Select ULB --');
    const d = DATA[stateKey]?.nodals?.[nodalKey]?.districts?.[distKey];
    if (!d) return;
    const ulbs = d.ulbs || [];
    for (const u of ulbs) {
      ulbSel.insertAdjacentHTML('beforeend', `<option value="${u.name}">${u.name} (${u.code})</option>`);
    }
    enableSelect(ulbSel);
  }
  stateSel.addEventListener('change', e=>populateNodals(e.target.value));
  nodalSel.addEventListener('change', e=>populateDistricts(stateSel.value, e.target.value));
  districtSel.addEventListener('change', e=>populateULBs(stateSel.value, nodalSel.value, e.target.value));

  document.getElementById('regForm').addEventListener('submit', async (e)=>{
    e.preventDefault();
    const fd = new FormData(e.target);
    const r = await fetch('submit.php', { method:'POST', body: fd });
    const j = await r.json();
    if (j.success && j.redirect) { window.location.href = j.redirect; return; }
    alert(j.message || 'Something went wrong');
  });
  </script>
</body>
</html>
