<?php
/* =============================================================================
 * File   : /brocrm/login.php
 * Goal   : Mobile-responsive sign-in (Broker / Employee) with device-based routing
 * DB     : MySQLi via config.php (NO PDO), COLLATE=utf8mb4_general_ci
 * Auth   : Builds unified $_SESSION['auth'] + legacy AMS keys for mobile pages
 * Routes : Uses includes/post_login_router.php to redirect based on device+role
 * NOTE   : Per requirement:
 *          - If BROKER login -> role_id MUST be 6
 *          - If EMPLOYEE login -> role_id MUST be 4
 * ============================================================================= */

@ini_set('session.cookie_secure', '1');
@ini_set('session.cookie_httponly', '1');
@ini_set('session.use_only_cookies', '1');
@ini_set('session.cookie_samesite', 'Lax');
@ini_set('session.gc_maxlifetime', 60*60*24*7);

session_set_cookie_params([
    'lifetime' => 60*60*24*7,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax'
]);

if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
date_default_timezone_set('Asia/Kolkata');

/* --------------------- Security headers (helpful on login) ------------------- */
@header('X-Content-Type-Options: nosniff');
@header('Referrer-Policy: strict-origin-when-cross-origin');
@header('X-Frame-Options: DENY');
@header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
@header('Pragma: no-cache');

/* --------- Centralized DB config (defines $conn_sa, $conn_ic, helpers) ------- */
$cfgs = [
  __DIR__ . '/config.php',
  __DIR__ . '/../config.php',
  __DIR__ . '/../../config.php'
];
$cfgFound = false;
foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; $cfgFound = true; break; } }
if (!$cfgFound) { http_response_code(500); echo 'config.php not found'; exit; }

/* Ensure charset/collation (utf8mb4_general_ci) on both links if present */
if (function_exists('_set_charset_and_collation')) {
    if (isset($conn_sa) && $conn_sa instanceof mysqli) { _set_charset_and_collation($conn_sa); }
    if (isset($conn_ic) && $conn_ic instanceof mysqli) { _set_charset_and_collation($conn_ic); }
} else {
    if (isset($conn_sa) && $conn_sa instanceof mysqli) {
        @mysqli_set_charset($conn_sa, 'utf8mb4');
        @mysqli_query($conn_sa, "SET collation_connection='utf8mb4_general_ci'");
    }
    if (isset($conn_ic) && $conn_ic instanceof mysqli) {
        @mysqli_set_charset($conn_ic, 'utf8mb4');
        @mysqli_query($conn_ic, "SET collation_connection='utf8mb4_general_ci'");
    }
}

/* ------------------------------ Helpers ------------------------------------- */
if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}
function is_bcrypt($hash){ return is_string($hash) && strpos($hash, '$2y$') === 0; }
function verify_any($plain, $stored){
    if ($stored === null) return false;
    if (is_bcrypt($stored)) return password_verify($plain, $stored);
    return hash_equals((string)$stored, (string)$plain);
}

/* --------------- If already logged-in, route immediately --------------------- */
if (!empty($_SESSION['auth']) && is_array($_SESSION['auth'])) {
    $router = __DIR__ . '/includes/post_login_router.php';
    if (file_exists($router)) { require_once $router; post_login_redirect(); }
    else { header('Location: /brocrm/'); }
    exit;
}

/* ---------------------------- POST handling ---------------------------------- */
$error_broker   = '';
$error_employee = '';
$active_tab     = (isset($_GET['tab']) && $_GET['tab']==='employee') ? 'employee' : 'broker';

/* Preserve input values after error for better UX */
$keep_b_email = '';
$keep_e_empid = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $which = $_POST['which'] ?? '';

    /* ---------------------------- Broker Login ---------------------------- */
    if ($which === 'broker') {
        $active_tab  = 'broker';
        $email       = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
        $pass        = trim($_POST['Password'] ?? '');
        $keep_b_email = $email ?: '';

        if (!$email) {
            $error_broker = 'Please enter a valid email.';
        } elseif ($pass === '') {
            $error_broker = 'Please enter your password.';
        } elseif (!isset($conn_sa) || !($conn_sa instanceof mysqli)) {
            $error_broker = 'DB connection unavailable.';
        } else {
            $sql = "SELECT id, first_name, last_name, email, phone, empid, password, Password, status 
                    FROM users WHERE email=? LIMIT 1";
            if ($st = mysqli_prepare($conn_sa, $sql)) {
                mysqli_stmt_bind_param($st, 's', $email);
                mysqli_stmt_execute($st);
                $rs = mysqli_stmt_get_result($st);
                if ($rs && $rs->num_rows === 1) {
                    $u = $rs->fetch_assoc();
                    $status     = strtolower(trim((string)($u['status'] ?? 'active')));
                    $storedPass = $u['password'] ?? ($u['Password'] ?? '');

                    if ($status !== '' && $status !== 'active' && $status !== '1') {
                        $error_broker = 'Your account is not active.';
                    } elseif (!verify_any($pass, $storedPass)) {
                        $error_broker = 'Invalid email or password.';
                    } else {
                        /* --------- REQUIRED: force role_id=6 for brokers --------- */
                        $forcedRoleId   = 6;
                        $forcedRoleName = 'broker';

                        $_SESSION['auth'] = [
                            'source'     => 'broker',
                            'id'         => (int)($u['id'] ?? 0),
                            'email'      => (string)($u['email'] ?? ''),
                            'first_name' => (string)($u['first_name'] ?? ''),
                            'last_name'  => (string)($u['last_name'] ?? ''),
                            'phone'      => (string)($u['phone'] ?? ''),
                            'empid'      => (string)($u['empid'] ?? ''),
                            'role_id'    => $forcedRoleId,
                            'role_name'  => $forcedRoleName
                        ];

                        /* Legacy keys used by AMS/mobile pages */
                        if (!empty($u['empid'])) {
                            $_SESSION['user_id1']    = (string)$u['empid'];
                            $_SESSION['idverified1'] = 1;
                            $_SESSION['namevfied1']  = trim(($u['first_name'] ?? '').' '.($u['last_name'] ?? ''));
                        }

                        /* Also set flat session flags some pages expect */
                        $_SESSION['role_id']   = $forcedRoleId;      // *** IMPORTANT ***
                        $_SESSION['role_name'] = $forcedRoleName;
                        $_SESSION['user_email']= (string)($u['email'] ?? '');

                        $sname = session_name();
                        if (isset($_COOKIE[$sname])) {
                            setcookie($sname, $_COOKIE[$sname], time() + (60*60*24*7), '/', '', true, true);
                        }
                        $router = __DIR__ . '/includes/post_login_router.php';
                        if (file_exists($router)) { require_once $router; post_login_redirect(); }
                        else { header('Location: /'); }
                        exit;
                    }
                } else {
                    $error_broker = 'Invalid email or password.';
                }
                if ($rs) mysqli_free_result($rs);
                mysqli_stmt_close($st);
            } else {
                $error_broker = 'Please try again later.';
            }
        }
    }

    /* --------------------------- Employee Login --------------------------- */
    if ($which === 'employee') {
        $active_tab   = 'employee';
        $empid        = trim($_POST['empid'] ?? '');
        $pass         = trim($_POST['Password'] ?? '');
        $keep_e_empid = $empid;

        if ($empid === '') {
            $error_employee = 'Please enter EmpID.';
        } elseif ($pass === '') {
            $error_employee = 'Please enter your password.';
        } elseif (!isset($conn_ic) || !($conn_ic instanceof mysqli)) {
            $error_employee = 'DB connection unavailable.';
        } else {
            $sql = "SELECT * FROM hr_dump WHERE empid=? LIMIT 1";
            if ($st = mysqli_prepare($conn_ic, $sql)) {
                mysqli_stmt_bind_param($st, 's', $empid);
                mysqli_stmt_execute($st);
                $rs = mysqli_stmt_get_result($st);
                if ($rs && $rs->num_rows === 1) {
                    $u = $rs->fetch_assoc();
                    $stored = $u['Password'] ?? ($u['password'] ?? '');

                    if (!verify_any($pass, $stored)) {
                        $error_employee = 'Invalid EmpID or password.';
                    } else {
                        /* --------- REQUIRED: force role_id=4 for employees --------- */
                        $forcedRoleId   = 4;
                        $forcedRoleName = 'employee';

                        $full = $u['Employee_Full_Name'] ?? ($u['Full_Name'] ?? ($u['emp_name'] ?? ''));
                        $mail = $u['official_email'] ?? ($u['email'] ?? '');

                        $_SESSION['auth'] = [
                            'source'     => 'employee',
                            'id'         => 0,
                            'email'      => (string)$mail,
                            'first_name' => (string)$full,
                            'last_name'  => '',
                            'phone'      => (string)($u['Phone'] ?? ($u['phone'] ?? '')),
                            'empid'      => (string)$empid,
                            'role_id'    => $forcedRoleId,
                            'role_name'  => $forcedRoleName
                        ];

                        /* Legacy keys used by AMS/mobile pages */
                        $_SESSION['user_id1']    = (string)$empid;
                        $_SESSION['idverified1'] = 1;
                        $_SESSION['namevfied1']  = (string)$full;

                        /* Also set flat session flags some pages expect */
                        $_SESSION['role_id']   = $forcedRoleId;      // *** IMPORTANT ***
                        $_SESSION['role_name'] = $forcedRoleName;
                        $_SESSION['user_email']= (string)$mail;

                        $sname = session_name();
                        if (isset($_COOKIE[$sname])) {
                            setcookie($sname, $_COOKIE[$sname], time() + (60*60*24*7), '/', '', true, true);
                        }
                        $router = __DIR__ . '/includes/post_login_router.php';
                        if (file_exists($router)) { require_once $router; post_login_redirect(); }
                        else { header('Location: /'); }
                        exit;
                    }
                } else {
                    $error_employee = 'Invalid EmpID or password.';
                }
                if ($rs) mysqli_free_result($rs);
                mysqli_stmt_close($st);
            } else {
                $error_employee = 'Please try again later.';
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
      content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimal-ui, viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<meta name="theme-color" content="#2aa5ff">
<title>Sign In • Broker / Employee</title>
<style>
/* ============================== Light, modern, responsive ============================== */
:root{
  --pri:#2aa5ff; --pri2:#16c5b8; --bg:#f7fafc; --card:#ffffff; --muted:#6b7380; --line:rgba(0,0,0,.07);
  --radius:18px; --gap:12px; --pad:18px;
  --focus:0 0 0 3px rgba(42,165,255,.20), 0 2px 10px rgba(0,0,0,.06);
}
*{box-sizing:border-box}
html,body{height:100%}
body{
  margin:0;
  font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial,sans-serif;
  background:var(--bg); color:#111; -webkit-text-size-adjust:100%;
}
.wrap{
  min-height:100dvh;
  display:grid;
  place-items:center;
  padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left));
}
.card{
  width:100%;
  max-width:560px;
  background:var(--card);
  border:1px solid var(--line);
  border-radius:var(--radius);
  box-shadow:0 16px 44px rgba(0,0,0,.06);
  overflow:hidden;
}
.header{
  padding:16px 20px;
  display:flex; align-items:center; justify-content:space-between; gap:8px;
  border-bottom:1px solid var(--line);
}
.brand{
  display:flex; align-items:center; gap:10px;
  font-weight:800; letter-spacing:0.3px; font-size: clamp(18px, 2.2vw, 20px);
}
.brand .dot{width:12px;height:12px;border-radius:20px;background:linear-gradient(135deg,var(--pri),var(--pri2))}
.content{padding:var(--pad)}
.tabs{
  display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:14px;
}
.tab{
  border:1px solid var(--line); background:#fff; padding:12px; border-radius:14px; text-align:center;
  font-weight:700; cursor:pointer; user-select:none; font-size:15px; line-height:1;
}
.tab:focus-visible{outline:none; box-shadow:var(--focus)}
.tab.active{background:linear-gradient(135deg,var(--pri),var(--pri2)); color:#fff; border-color:transparent}
.row{margin-bottom:12px}
label{display:block; font-size:13px; color:var(--muted); margin-bottom:6px}
.input{
  display:flex; align-items:center; gap:8px;
  border:1px solid var(--line); border-radius:14px; background:#fff; padding:0 12px;
}
.input input{
  flex:1; height:50px; border:0; outline:0; font-size:16px; background:transparent;
}
.input button.icon{
  background:transparent; border:0; padding:8px; border-radius:10px; cursor:pointer;
}
.input button.icon:focus-visible{outline:none; box-shadow:var(--focus)}
button[type="submit"]{
  width:100%; height:50px; border:0; border-radius:14px;
  background:linear-gradient(135deg,var(--pri),var(--pri2)); color:#fff; font-weight:800; cursor:pointer;
  font-size:16px;
}
button[type="submit"]:focus-visible{outline:none; box-shadow:var(--focus)}
.error{
  background:#fff4f2; color:#b00020; border:1px solid #ffc9c3;
  padding:10px 12px; border-radius:14px; margin-bottom:12px; font-size:14px;
}
.hint{font-size:12px; color:var(--muted); margin-top:8px}
.helper{
  display:flex; align-items:center; justify-content:space-between; gap:10px; margin-top:10px;
  font-size:12px; color:var(--muted);
}
.helper a{color:inherit; text-decoration:underline dotted}
.footer-note{
  margin-top:12px; font-size:11px; color:#777; text-align:center;
}

/* ----------- Larger screens: give the card a gentle zoom & breathing room ---- */
@media (min-width: 640px){
  .card{max-width:600px}
  .content{padding:22px}
}

/* ----------- Tall mobiles: slightly increase paddings ------------------------ */
@media (min-height: 740px){
  .content{padding:26px}
}

/* ------------------ Dark mode (auto) ---------------------------------------- */
@media (prefers-color-scheme: dark){
  :root{ --bg:#0b0e12; --card:#0e1319; --muted:#9aa3af; --line:rgba(255,255,255,.08) }
  body{ color:#e6e6e6 }
  .tab{ background:#0f141a; color:#e6e6e6 }
  .input{ background:#0f141a }
  .error{ background:#1f0c0c; border-color:#472727; color:#ffb4b4 }
  .hint, .helper, .footer-note{ color:#a8b3be }
}
</style>
</head>
<body>
<div class="wrap">
  <div class="card" role="dialog" aria-labelledby="signinTitle" aria-modal="true">
    <div class="header">
      <div class="brand"><span class="dot" aria-hidden="true"></span> <span id="signinTitle">Sign in</span></div>
      <div style="font-size:12px;color:var(--muted);">Secure Access</div>
    </div>

    <div class="content">
      <div class="tabs" role="tablist" aria-label="Choose account type">
        <button class="tab<?php echo $active_tab==='broker'?' active':''; ?>"
                id="tab-broker" aria-controls="panel-broker"
                aria-selected="<?php echo $active_tab==='broker'?'true':'false'; ?>">
          Broker Login
        </button>
        <button class="tab<?php echo $active_tab==='employee'?' active':''; ?>"
                id="tab-employee" aria-controls="panel-employee"
                aria-selected="<?php echo $active_tab==='employee'?'true':'false'; ?>">
          Employee Login
        </button>
      </div>

      <!-- Broker -->
      <section id="panel-broker" role="tabpanel" tabindex="0"
               style="display:<?php echo $active_tab==='broker'?'block':'none'; ?>">
        <?php if ($error_broker!==''): ?>
          <div class="error"><?php echo h($error_broker); ?></div>
        <?php endif; ?>
        <form method="post" autocomplete="on" novalidate>
          <input type="hidden" name="which" value="broker">
          <div class="row">
            <label for="b_email">Email Address</label>
            <div class="input">
              <input id="b_email" type="email" name="email"
                     placeholder="you@example.com" inputmode="email" autocomplete="email"
                     value="<?php echo h($keep_b_email); ?>" required>
            </div>
          </div>
          <div class="row">
            <label for="b_pass">Password</label>
            <div class="input">
              <input id="b_pass" type="password" name="Password"
                     placeholder="••••••••" autocomplete="current-password" required>
              <button type="button" class="icon" aria-label="Show password" data-toggle="reveal" data-target="b_pass">
                <!-- eye icon -->
                <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-7 0-10 7-10 7s3 7 10 7 10-7 10-7-3-7-10-7zm0 12a5 5 0 1 1 .001-10.001A5 5 0 0 1 12 17z"/></svg>
              </button>
            </div>
          </div>
          <button type="submit">Login as Broker</button>
          <div class="helper">
            <a href="#" onclick="alert('Contact admin to reset your password.'); return false;">Forgot?</a>
          </div>
        </form>
      </section>

      <!-- Employee -->
      <section id="panel-employee" role="tabpanel" tabindex="0"
               style="display:<?php echo $active_tab==='employee'?'block':'none'; ?>">
        <?php if ($error_employee!==''): ?>
          <div class="error"><?php echo h($error_employee); ?></div>
        <?php endif; ?>
        <form method="post" autocomplete="on" novalidate>
          <input type="hidden" name="which" value="employee">
          <div class="row">
            <label for="e_empid">EmpID</label>
            <div class="input">
              <input id="e_empid" type="text" name="empid"
                     placeholder="e.g. BR00123" inputmode="text" autocomplete="username"
                     value="<?php echo h($keep_e_empid); ?>" required>
            </div>
          </div>
          <div class="row">
            <label for="e_pass">Password</label>
            <div class="input">
              <input id="e_pass" type="password" name="Password"
                     placeholder="••••••••" autocomplete="current-password" required>
              <button type="button" class="icon" aria-label="Show password" data-toggle="reveal" data-target="e_pass">
                <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-7 0-10 7-10 7s3 7 10 7 10-7 10-7-3-7-10-7zm0 12a5 5 0 1 1 .001-10.001A5 5 0 0 1 12 17z"/></svg>
              </button>
            </div>
          </div>
          <button type="submit">Login as Employee</button>
          <div class="helper"><span></span></div>
        </form>
      </section>

      <div class="footer-note">Protected area • Use your official credentials</div>
    </div>
  </div>
</div>

<script>
/* -------------------- Accessible tabs (mobile-friendly) -------------------- */
const tBroker   = document.getElementById('tab-broker');
const tEmployee = document.getElementById('tab-employee');
const pBroker   = document.getElementById('panel-broker');
const pEmployee = document.getElementById('panel-employee');

function activate(tab){
  if (tab === 'broker') {
    tBroker.classList.add('active'); tBroker.setAttribute('aria-selected','true');
    tEmployee.classList.remove('active'); tEmployee.setAttribute('aria-selected','false');
    pBroker.style.display='block'; pEmployee.style.display='none'; pBroker.focus();
    history.replaceState(null,'','?tab=broker');
  } else {
    tEmployee.classList.add('active'); tEmployee.setAttribute('aria-selected','true');
    tBroker.classList.remove('active'); tBroker.setAttribute('aria-selected','false');
    pEmployee.style.display='block'; pBroker.style.display='none'; pEmployee.focus();
    history.replaceState(null,'','?tab=employee');
  }
}
tBroker.addEventListener('click', ()=>activate('broker'));
tEmployee.addEventListener('click', ()=>activate('employee'));

/* Keyboard support for tabs */
[tBroker, tEmployee].forEach((btn, idx, arr)=>{
  btn.addEventListener('keydown', (e)=>{
    if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
      e.preventDefault();
      const next = (idx + (e.key === 'ArrowRight' ? 1 : -1) + arr.length) % arr.length;
      arr[next].focus();
    }
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      btn.click();
    }
  });
});

/* -------------------- Show/hide password toggles --------------------------- */
document.querySelectorAll('button[data-toggle="reveal"]').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const id = btn.getAttribute('data-target');
    const input = document.getElementById(id);
    if (!input) return;
    const isPw = input.getAttribute('type') === 'password';
    input.setAttribute('type', isPw ? 'text' : 'password');
    btn.setAttribute('aria-label', isPw ? 'Hide password' : 'Show password');
  });
});

/* -------------------- Reduce layout shift on mobile keyboards -------------- */
if ('virtualKeyboard' in navigator) {
  try { navigator.virtualKeyboard.overlaysContent = true; } catch(e){}
}
</script>
</body>
</html>
