<?php
session_start();
ob_start();
require_once "config.php";


$message = $_SESSION['message'] ?? "";
unset($_SESSION['message']);

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* -----------------------------
   CHECK IF AGENCY EXISTS
------------------------------*/
function agencyExists($conn, $name, $country){
    $q = $conn->prepare("SELECT id FROM users WHERE role='agency' AND name=? AND country=?");
    $q->bind_param("ss", $name, $country);
    $q->execute();
    $q->store_result();
    return $q->num_rows > 0;
}

/* -----------------------------
   SIGNUP
------------------------------*/
if(isset($_POST['signup'])){

    $name = trim($_POST['name'] ?? '');
    $email = strtolower(trim($_POST['email'] ?? ''));
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm'] ?? '';
    $role = trim($_POST['role'] ?? '');

    $selected_agency = (int)($_POST['selected_agency'] ?? 0);
    $selected_manager = (int)($_POST['selected_manager'] ?? 0);

    $country = ucwords(strtolower(trim($_POST['country'] ?? '')));

    if($name=='' || $email=='' || $password=='' || $confirm=='' || $role==''){
        $message="Please fill all fields.";
    }
    elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $message="Invalid email address.";
    }
    elseif($password != $confirm){
        $message="Passwords do not match.";
    }
    elseif(strtolower($role)=='admin'){
        $message="Signup not allowed for admin role.";
    }
    else{

        $lowerRole = strtolower($role);

        if($lowerRole==='sales_manager' && $selected_agency<=0){
            $message="Please select an agency.";
        }
        elseif($lowerRole==='medical_representative' && $selected_manager<=0){
            $message="Please select a sales manager.";
        }
        elseif(($lowerRole==='agency' || $lowerRole==='sales_manager') && empty($country)){
            $message="Please select your country.";
        }
        else{

            $check=$conn->prepare("SELECT id FROM users WHERE email=?");
            $check->bind_param("s",$email);
            $check->execute();
            $check->store_result();

            if($check->num_rows>0){
                $message="Email already exists";
            }
            elseif($lowerRole==='agency' && agencyExists($conn,$name,$country)){
                $message="Agency already exists in this country";
            }
            else{

                /* APPROVAL RULES */

                if($lowerRole==='agency'){
                    $is_approved=0;
                    $approver_role='admin';
                }
                elseif($lowerRole==='sales_manager'){
                    $is_approved=0;
                    $approver_role='agency';
                }
                elseif($lowerRole==='medical_representative'){
                    $is_approved=0;
                    $approver_role='sales_manager';
                }
                elseif($lowerRole==='ra'){
                    $is_approved=0;
                    $approver_role='admin';
                }
                else{
                    $is_approved=1;
                    $approver_role='admin';
                }

                $agency_id = ($lowerRole==='sales_manager') ? $selected_agency : 0;
                $manager_id = ($lowerRole==='medical_representative') ? $selected_manager : 0;

                /* AUTO COUNTRY FROM MANAGER */

                if($lowerRole==='medical_representative'){
                    $q=$conn->prepare("SELECT country FROM users WHERE id=?");
                    $q->bind_param("i",$selected_manager);
                    $q->execute();
                    $res=$q->get_result();
                    if($row=$res->fetch_assoc()){
                        $country=$row['country'];
                    }
                }

                $country_to_store = ($lowerRole==='agency' || $lowerRole==='sales_manager' || $lowerRole==='medical_representative') ? $country : null;

                /* INSERT USER */

                $insert=$conn->prepare("
                    INSERT INTO users
                    (name,email,password,role,country,is_approved,approver_role,agency_id,manager_id)
                    VALUES (?,?,?,?,?,?,?,?,?)
                ");

                $insert->bind_param(
                    "sssssisii",
                    $name,
                    $email,
                    $password,
                    $role,
                    $country_to_store,
                    $is_approved,
                    $approver_role,
                    $agency_id,
                    $manager_id
                );

                if($insert->execute()){
                    if($is_approved==0){
                        $message=ucfirst($role)." signup request submitted.";
                    }else{
                        $message="Account created successfully. You can login now.";
                    }
                }else{
                    $message="Error creating account.";
                }

                $insert->close();
            }

            $check->close();
        }
    }
}

/* -----------------------------
   LOGIN
------------------------------*/
if(isset($_POST['login'])){

    $email=strtolower(trim($_POST['email']??''));
    $password=$_POST['password']??'';
    $role=strtolower(trim($_POST['role']??''));

    if($email=='' || $password=='' || $role==''){
        $message="Please enter email, password and select a role.";
    }
    else{

        $stmt=$conn->prepare("SELECT * FROM users WHERE email=?");
        $stmt->bind_param("s",$email);
        $stmt->execute();
        $res=$stmt->get_result();

        if($res && $res->num_rows==1){

            $user=$res->fetch_assoc();

            if($password==$user['password']){

                if($role!=strtolower($user['role'])){
                    $message="Wrong role selected.";
                }
                elseif($user['is_approved']==0){
                    $message="Your account is pending approval.";
                }
                else{

                    if(session_status() === PHP_SESSION_ACTIVE){
                        session_regenerate_id(true);
                    }

                    $_SESSION['user']=$user['name'];
                    $_SESSION['role']=$user['role'];
                    $_SESSION['user_id']=$user['id'];

                    if($user['role']=="admin"){
                        header("Location: Admin/admin_dashboard.php");
                    }
                    elseif($user['role']=="sales_manager"){
                        header("Location: SalesManager/sales_manager_dashboard.php");
                    }
                    elseif($user['role']=="medical_representative"){
                        header("Location: medicalrepresentative/medical_representative_dashboard.php");
                    }
                    elseif($user['role']=="agency"){
                        header("Location: agency/agency_dashboard.php");
                    }
                    elseif($user['role']=="ra"){
                        header("Location: Ra/ra_dashboard.php");
                    }
                    else{
                        header("Location: dashboard.php");
                    }

                    exit;
                }

            } else {
                $message="Invalid password.";
            }

        } else {

            $_SESSION['message']="User not found.";
            header("Location: login.php");
            exit;

        }

        $stmt->close();
    }
}

/* -----------------------------
   FETCH AGENCIES
------------------------------*/
$agencies=[];
$q=$conn->prepare("SELECT id,name,email,country FROM users WHERE role='agency' AND is_approved=1 ORDER BY name ASC");
$q->execute();
$r=$q->get_result();
if($r){ $agencies=$r->fetch_all(MYSQLI_ASSOC); }
$q->close();

/* -----------------------------
   FETCH MANAGERS
------------------------------*/
$managers=[];
$q2=$conn->prepare("SELECT id,name,email,country FROM users WHERE role='sales_manager' AND is_approved=1 ORDER BY name ASC");
$q2->execute();
$r2=$q2->get_result();
if($r2){ $managers=$r2->fetch_all(MYSQLI_ASSOC); }
$q2->close();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ERP Login</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
:root{
--primary:#1f4e79;
--primary-light:#2e6aa3;
--bg:#f3f6fb;
--card:#ffffff;
--border:#e6ecf3;
--text:#0f172a;
--muted:#64748b;
--radius:14px;
--shadow:0 20px 50px rgba(15,23,42,0.08);
}

body{
font-family:'Inter',sans-serif;
background:linear-gradient(135deg,#eef3f8,#f8fbff);
display:flex;
align-items:center;
justify-content:center;
height:100vh;
margin:0;
color:var(--text);
}

/* container */
.container{
width:100%;
max-width:600px;
margin:auto;
text-align:center;
}

/* logo */

.logo{
text-align:center;
margin-bottom:20px;
}

.logo h1{
margin:0;
font-size:34px;
font-weight:800;
letter-spacing:1px;
}

.logo p{
margin-top:6px;
color:var(--muted);
font-size:14px;
}

/* role tabs */

.role-tabs{
display:flex;
gap:10px;
margin:25px 0;
background:#eef2f7;
padding:10px;
border-radius:14px;

flex-wrap:nowrap;          /* ❗ force single line */
overflow-x:auto;           /* ✅ scroll if needed */
white-space:nowrap;        /* ✅ no break */
}

.role-tabs button{
flex:0 0 auto; 
padding:10px 14px;
border-radius:12px;
border:none;
background:#e5e9f0;
font-weight:600;
cursor:pointer;
transition:all .25s;
font-size:13px;

/* ADD THESE */
white-space: nowrap;
}
.role-tabs::-webkit-scrollbar{
display:none;
}
.role-tabs button:hover{
background:#dbe1ea;
}

.role-tabs button.active{
background:var(--primary);
color:#fff;
box-shadow:0 8px 20px rgba(31,78,121,0.25);
}

/* login card */

.card{
background:var(--card);
padding:32px;
border-radius:var(--radius);
box-shadow:var(--shadow);
text-align:left;
}

/* inputs */

label{
font-size:13px;
font-weight:600;
color:var(--muted);
}

.input{
width:100%;
padding:12px;
border-radius:10px;
border:1px solid var(--border);
margin-top:6px;
margin-bottom:18px;
font-size:14px;
transition:.2s;
}

.input:focus{
border-color:var(--primary-light);
box-shadow:0 0 0 3px rgba(46,106,163,0.15);
outline:none;
}

/* password */

.pass-wrap{
position:relative;
}

.pass-toggle{
position:absolute;
right:12px;
top:50%;
transform:translateY(-50%);
border:none;
background:none;
color:var(--muted);
font-weight:600;
cursor:pointer;
}

/* remember */

.remember{
display:flex;
align-items:center;
gap:8px;
margin-bottom:18px;
font-size:14px;
color:var(--muted);
}

/* button */

.btn{
width:100%;
padding:14px;
border-radius:10px;
border:none;
background:var(--primary);
color:#fff;
font-weight:700;
font-size:16px;
cursor:pointer;
transition:.25s;
}

.btn:hover{
background:var(--primary-light);
transform:translateY(-1px);
}

/* links */

.links{
margin-top:15px;
display:flex;
justify-content:space-between;
font-size:14px;
}

.links a{
color:var(--primary);
text-decoration:none;
font-weight:600;
}

/* signup */

.signup{
text-align:center;
margin-top:18px;
font-size:14px;
color:var(--muted);
}

.signup a{
color:var(--primary);
font-weight:700;
cursor:pointer;
text-decoration:none;
}

.signup a:hover{
text-decoration:underline;
}

/* responsive */

@media (max-width:480px){

.container{
max-width:95%;
}

.role-tabs{
flex-direction:column;
}

.role-tabs button{
width:100%;
}

}
/* ========== Country picker styles (paste into your stylesheet) ========== */
.country-wrapper { position: relative; margin-top:6px; }
.country-display {
  display:flex;
  align-items:center;
  justify-content:space-between;
  width:100%;
  padding:10px 12px;
  border-radius:10px;
  border:1px solid var(--border);
  background:#fff;
  cursor:pointer;
  text-align:left;
  gap:8px;
}
.country-display .caret { opacity:0.65; font-weight:700; margin-left:8px; }

/* dropdown panel */
.country-dropdown {
  position:absolute;
  left:0;
  right:0;
  top:calc(100% + 8px);
  background:#fff;
  border:1px solid var(--border);
  border-radius:10px;
  box-shadow:0 12px 30px rgba(15,23,42,0.08);
  z-index:2000;
  padding:8px;
}

/* search box inside dropdown */
.country-search { padding:6px; margin-bottom:6px; }
#countrySearch.input { width:100%; padding:8px; box-sizing:border-box; }

/* list */
.country-list { max-height:220px; overflow:auto; }

/* each item */
.country-item {
  display:flex;
  align-items:center;
  gap:10px;
  padding:8px;
  border-radius:8px;
  cursor:pointer;
}
.country-item:hover, .country-item[aria-selected="true"] { background:#f3f7fb; }
.country-flag {
  width:28px; height:20px; border-radius:3px; object-fit:cover; flex: 0 0 28px;
  box-shadow: 0 1px 0 rgba(0,0,0,0.05) inset;
}
.country-name { font-size:14px; color:var(--text); }
.country-code { margin-left:auto; font-size:12px; color:var(--muted); }

/* small visual polish to match screenshot */
.country-dropdown::-webkit-scrollbar { width:10px; }
.country-dropdown::-webkit-scrollbar-thumb { background: rgba(15,23,42,0.06); border-radius:8px; }
</style>
</head>
<body>

<div class="container" role="main" aria-label="ERP login container">

  <div class="card" id="card">
<div class="logo">
    <img src="logoB.png" class="company-logo" alt="Company Logo">
   
</div>
   <div class="role-tabs" role="tablist" aria-label="Select role">
    <button class="active" data-role="admin" onclick="setRole('admin', this)" id="btn_admin">Admin</button>
      <button data-role="ra" onclick="setRole('ra', this)" id="btn_ra">RA </button>
      <button data-role="agency" onclick="setRole('agency', this)" id="btn_ag">Agency</button>
    <button data-role="sales_manager" onclick="setRole('sales_manager', this)" id="btn_sm">Sales Manager</button>
    <button data-role="medical_representative" onclick="setRole('medical_representative', this)" id="btn_se">Medical Representative</button>

  </div>

 <?php if ($message !== ""): ?>
  <?php $isSuccess = stripos($message,'created') !== false; ?>
  <div id="alertMessage" class="message <?php echo $isSuccess ? 'success' : 'error'; ?>">
    <?php echo htmlspecialchars($message); ?>
  </div>
<?php endif; ?>
    <!-- LOGIN -->
    <div id="loginSection">
      <form method="post" onsubmit="return validateLogin()">
        <input type="hidden" name="role" id="roleInput" value="admin">

        <label for="emailInput">Email</label>
        <input id="emailInput" class="input" type="email" name="email" placeholder="your@gmail.com" required>


        <label for="passwordInput">Password</label>
        <div class="pass-wrap">
          <input id="passwordInput" class="input" type="password" name="password" placeholder="Password" required>
          <button type="button" class="pass-toggle" onclick="togglePassword('passwordInput', this)">Show</button>
        </div>

        <div class="remember">
          <input id="remember" type="checkbox" name="remember">
          <label for="remember" style="margin:0;font-weight:600;color:var(--muted);">Remember me</label>
        </div>

        <button type="submit" name="login" class="btn">Login</button>
      </form>

      <div class="links" style="margin-top:12px">
        <div></div>
        <a href="forgot.php">Forgot Password</a>
      </div>

      <div class="signup" style="margin-top:12px">
    <a id="showSignup" onclick="showSignup()">Signup</a>
      </div>
    </div>

    <!-- SIGNUP (hidden by default) -->
    <div id="signupSection" style="display:none;">
      <form method="post" onsubmit="return validateSignup()">
        <input type="hidden" name="role" id="signupRoleInput" value=""> <!-- forced on server too -->

        <label for="signupName"  id="nameLabel">Full name</label>
       <input id="signupName" class="input" type="text" name="name" placeholder="Enter full name" required>


       <label for="selected_agency" id="agencyLabel" style="display:none; margin-top:6px;">Select Agency</label>
        <select id="selected_agency" name="selected_agency" class="input" style="display:none;">
          <option value="0">Choose Agency </option>
          <?php foreach ($agencies as $a): ?>
            <option 
           value="<?php echo (int)$a['id']; ?>"
            data-country="<?php echo htmlspecialchars($a['country'] ?? ''); ?>">
              <?php echo htmlspecialchars($a['name'] . ' (' . $a['country'] . ')'); ?>
            </option>
          <?php endforeach; ?>
        </select> 

        <!-- Manager select for Sales Executive (hidden by default) -->
        <label for="selected_manager" id="managerLabel" style="display:none; margin-top:6px;">Select Sales Manager</label>
        <select id="selected_manager" name="selected_manager" class="input" style="display:none;">
          <option value="0">Choose Sales Manager</option>
          <?php foreach ($managers as $m): ?>
            <option
            value="<?php echo (int)$m['id']; ?>"
            data-country="<?php echo htmlspecialchars($m['country'] ?? ''); ?>">
            <?php echo htmlspecialchars($m['name'] . ' (' . $m['email'] . ')'); ?>
          </option>
          <?php endforeach; ?>
        </select>

       <!-- COUNTRY PICKER START (paste below signupName) -->
<label id="countryLabel" for="countryDisplay" style="display:none; margin-top:8px;">Where are you from?</label>

<!-- hidden input submitted to server -->
<input type="hidden" name="country" id="countryInput" value="">

<!-- visible select-like control -->
<div id="countryWrapper" class="country-wrapper" style="display:none;">
  <button type="button" id="countryDisplay" class="input country-display" aria-haspopup="listbox" aria-expanded="false">
    <span id="countryDisplayText">Select country</span>
    <span class="caret">▾</span>
  </button>

  <div id="countryDropdown" class="country-dropdown" role="listbox" tabindex="-1" style="display:none;">
    <div class="country-search">
      <input id="countrySearch" class="input" placeholder="Search country..." aria-label="Search country" />
    </div>
    <div id="countryList" class="country-list" role="presentation" aria-live="polite"></div>
  </div>
</div>
<!-- COUNTRY PICKER END -->
        <!-- Agency select for Sales Manager (hidden by default) -->
        <label for="signupEmail">Email</label>
        <input id="signupEmail" class="input" type="email" name="email" placeholder="you@company.com" required>
       <label for="signupPassword">Password</label>
<div class="pass-wrap">
  <input id="signupPassword" class="input" type="password" name="password" placeholder="Create password" required>
  <button type="button" class="pass-toggle" onclick="togglePassword('signupPassword', this)">Show</button>
</div>

<label for="signupConfirm">Confirm password</label>
<div class="pass-wrap">
  <input id="signupConfirm" class="input" type="password" name="confirm" placeholder="Confirm password" required>
  <button type="button" class="pass-toggle" onclick="togglePassword('signupConfirm', this)">Show</button>
</div>
        <button type="submit" name="signup" class="btn">Create account</button>
        <button type="button" class="btn secondary" onclick="showLogin()" style="margin-top:10px">Back to login</button>
      </form>
    </div>

  </div> <!-- card -->

</div>

<script>
/* role switching */
function setRole(role, btn) {
  document.getElementById('roleInput').value = role;
  document.getElementById('signupRoleInput').value = role;

  document.querySelectorAll('.role-tabs button').forEach(b => b.classList.remove('active'));
  if (btn) btn.classList.add('active');

  const signupLink = document.getElementById('showSignup');
  const nameLabel = document.getElementById('nameLabel');
  const nameInput = document.getElementById('signupName');

  const agencyLabel = document.getElementById('agencyLabel');
  const agencySelect = document.getElementById('selected_agency');
  const managerLabel = document.getElementById('managerLabel');
  const managerSelect = document.getElementById('selected_manager');

  // Hide signup for admin
  if (role === 'admin') {
      signupLink.style.display = 'none';
  } else {
      signupLink.style.display = 'inline';
  }

  // Change label based on role
  if (role === 'agency') {
      nameLabel.innerText = "Agency Name";
      nameInput.placeholder = "NMC";
  } else {
      nameLabel.innerText = "Full Name";
      nameInput.placeholder = "John Doe";
  }

  // show/hide association dropdowns
  if (role === 'sales_manager') {
      agencyLabel.style.display = 'block';
      agencySelect.style.display = 'block';
  } else {
      agencyLabel.style.display = 'none';
      agencySelect.style.display = 'none';
      agencySelect.value = "0";
  }

  if (role === 'medical_representative') {
    managerLabel.style.display = 'block';
      managerSelect.style.display = 'block';
  } else {
      managerLabel.style.display = 'none';
      managerSelect.style.display = 'none';
      managerSelect.value = "0";
  }

 
// show country picker for agency + sales_manager
if (typeof window.showAgencyCountry === 'function') {
  window.showAgencyCountry(role === 'agency' || role === 'sales_manager' || role === 'medical_representative');
  // ✅ RESET COUNTRY FIELD WHEN ROLE CHANGES
const countryInput = document.getElementById('countryInput');
const countryDisplayText = document.getElementById('countryDisplayText');
const countryDisplay = document.getElementById('countryDisplay');

countryInput.value = '';
countryDisplayText.textContent = 'Select country';

countryDisplay.disabled = false;
countryDisplay.style.opacity = "1";
countryDisplay.style.cursor = "pointer";
}

  setTimeout(()=>{ const e = document.getElementById('emailInput'); if(e) e.focus(); }, 120);
}

/* toggle password visibility */
function togglePassword(id, btn) {
  const input = document.getElementById(id);
  if (!input) return;
  if (input.type === 'password') {
    input.type = 'text';
    btn.innerText = 'Hide';
  } else {
    input.type = 'password';
    btn.innerText = 'Show';
  }
}

/* show/hide signup */
function showSignup() {
  // ensure user selected non-admin role before signup
  const role = document.getElementById('roleInput').value;
  if (role === 'admin') {
    alert('Signup available only for non-admin roles. Please select Executive/Agency/Manager role.');
    return;
  }
  document.getElementById('loginSection').style.display = 'none';
  document.getElementById('signupSection').style.display = 'block';
}

function showLogin() {
  document.getElementById('signupSection').style.display = 'none';
  document.getElementById('loginSection').style.display = 'block';
}

/* validation */
function validateLogin() {
  const role = document.getElementById('roleInput').value;
  if (!role) { alert('Please select a role.'); return false; }
  return true;
}

function validateSignup() {
  const p = document.getElementById('signupPassword').value;
  const c = document.getElementById('signupConfirm').value;
  if (p !== c) { alert('Passwords do not match'); return false; }
  if (p.length < 6) { alert('Password should be at least 6 characters'); return false; }

  const role = document.getElementById('signupRoleInput').value;
  if (role === 'sales_manager') {
    const sel = document.getElementById('selected_agency').value;
    if (!sel || sel === '0') { alert('Please select an agency'); return false; }
  }
 if (role === 'medical_representative') {
    const sel2 = document.getElementById('selected_manager').value;
    if (!sel2 || sel2 === '0') { alert('Please select a sales manager'); return false; }
  }
  if (role === 'agency' || role === 'sales_manager' || role === 'medical_representative') {
  const country = document.getElementById('countryInput').value;
  if (!country || country.length < 3) {
    alert('Please select a valid country');
    return false;
  }
}
  return true;
}

/* init: default role active */
window.addEventListener('load', function() {
  const defaultBtn = document.querySelector('.role-tabs button.active');
  if (defaultBtn) setRole(defaultBtn.dataset.role || 'admin', defaultBtn);
});

/* ========== Country picker logic ========== */
(function(){
  const countryWrapper = document.getElementById('countryWrapper');
  const countryLabel = document.getElementById('countryLabel');
  const countryDisplay = document.getElementById('countryDisplay');
  const countryDisplayText = document.getElementById('countryDisplayText');
  const countryDropdown = document.getElementById('countryDropdown');
  const countrySearch = document.getElementById('countrySearch');
  const countryList = document.getElementById('countryList');
  const countryInput = document.getElementById('countryInput');

  let countries = []; // will hold list of {name, code, flag}

  // you can change this URL if you want a local/static source
  const REST_URL = 'https://restcountries.com/v3.1/all?fields=name,cca2,flags';

  // load countries (lazy)
  async function loadCountries(){
    if (countries.length) return countries;
    try {
      const res = await fetch(REST_URL);
      const data = await res.json();
      countries = data.map(c=>{
        const name = c.name?.common || c.name || '';
        const code = (c.cca2 || '').toLowerCase();
        const flag = code ? `https://flagcdn.com/w40/${code}.png` : (c.flags?.png || '');
        return { name, code, flag };
      }).sort((a,b)=> a.name.localeCompare(b.name));
    } catch (err) {
      // fallback small list (edit below if you want)
      countries = [
        {name:'India', code:'in', flag:'https://flagcdn.com/w40/in.png'},
        {name:'United States', code:'us', flag:'https://flagcdn.com/w40/us.png'},
        {name:'United Kingdom', code:'gb', flag:'https://flagcdn.com/w40/gb.png'},
        {name:'Canada', code:'ca', flag:'https://flagcdn.com/w40/ca.png'},
        {name:'Australia', code:'au', flag:'https://flagcdn.com/w40/au.png'}
      ];
      console.warn('Could not fetch countries, using fallback list', err);
    }
    renderList(countries);
    return countries;
  }

  function renderList(list){
    countryList.innerHTML = '';
    const frag = document.createDocumentFragment();
    list.forEach((c, idx) => {
      const el = document.createElement('div');
      el.className = 'country-item';
      el.tabIndex = 0;
      el.setAttribute('role','option');
      el.dataset.index = idx;
      el.innerHTML = `
        <img class="country-flag" src="${c.flag}" alt="${c.code}" onerror="this.onerror=null;this.src='https://flagcdn.com/w40/xx.png'">
        <div class="country-name">${escapeHtml(c.name)}</div>
        <div class="country-code">${(c.code||'').toUpperCase()}</div>
      `;
      el.addEventListener('click', ()=> selectCountry(c));
      el.addEventListener('keydown', (e)=> { if (e.key === 'Enter') selectCountry(c); });
      frag.appendChild(el);
    });
    countryList.appendChild(frag);
  }

  function filterList(q){
    q = (q || '').trim().toLowerCase();
    if (!q) renderList(countries);
    else renderList(countries.filter(c => c.name.toLowerCase().includes(q) || (c.code||'').toLowerCase().includes(q)));
  }

  function openDropdown(){
    countryDropdown.style.display = 'block';
    countryDisplay.setAttribute('aria-expanded','true');
    countrySearch.focus();
  }
  function closeDropdown(){
    countryDropdown.style.display = 'none';
    countryDisplay.setAttribute('aria-expanded','false');
  }

  function selectCountry(c){
    countryInput.value = c.name; // full name save hoga (India, United States) // store ISO code (IN, US, etc.)
    countryDisplayText.innerHTML = `<img class="country-flag" src="${c.flag}" alt=""> ${escapeHtml(c.name)}`;
    closeDropdown();
  }

  // utility: simple HTML escape for names
  function escapeHtml(s){ return (s+'').replace(/[&<>"']/g, function(m){ return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]); }); }

  // toggle when clicking display
  countryDisplay.addEventListener('click', async function(e){
  if (this.disabled) return; // 🚫 block click if disabled
    else {
      await loadCountries();
      openDropdown();
    }
  });

  // search input
  countrySearch.addEventListener('input', function(){ filterList(this.value); });

  // close on outside click
  document.addEventListener('click', function(e){
    if (!countryWrapper.contains(e.target)) closeDropdown();
  });

  // keyboard: Esc to close
  document.addEventListener('keydown', function(e){
    if (e.key === 'Escape') closeDropdown();
  });

  // expose a helper to show/hide picker when role changes
  window.showAgencyCountry = function(show){
    if (show) {
      countryWrapper.style.display = 'block';
      countryLabel.style.display = 'block';
      loadCountries().catch(()=>{});
    } else {
      countryWrapper.style.display = 'none';
      countryLabel.style.display = 'none';
      countryInput.value = ''; // clear
      countryDisplayText.textContent = 'Select country';
    }
  };

})();



document.getElementById('selected_manager').addEventListener('change', function () {

  const role = document.getElementById('signupRoleInput').value;

  // ❌ DELETE THIS LINE
  // if (role === 'medical_representative') return;

  const selectedOption = this.options[this.selectedIndex];
  const country = selectedOption.getAttribute('data-country');

  const countryInput = document.getElementById('countryInput');
  const countryDisplayText = document.getElementById('countryDisplayText');
  const countryDisplay = document.getElementById('countryDisplay');

  if (!country) return;

  countryInput.value = country;

  // ✅ SAME mapping as Sales Executive
  const countryMap = {
    India: 'in',
    'United States': 'us',
    'United Kingdom': 'gb',
    Canada: 'ca',
    Australia: 'au'
  };

  const code = (countryMap[country] || country.slice(0, 2)).toLowerCase();

  countryDisplayText.innerHTML = `
    <img src="https://flagcdn.com/w40/${code}.png"
         style="width:22px;height:16px;border-radius:3px;margin-right:6px;">
    ${country}
  `;

  // disable dropdown
  countryDisplay.disabled = true;
  countryDisplay.style.background = "#f8fafc";
  countryDisplay.style.color = "#0f172a";
  countryDisplay.style.opacity = "1";
  countryDisplay.style.cursor = "not-allowed";
});



// Auto hide message after 5 seconds
window.addEventListener("load", function () {
  const alertBox = document.getElementById("alertMessage");
  if (alertBox) {
    setTimeout(() => {
      alertBox.style.transition = "opacity 0.5s ease";
      alertBox.style.opacity = "0";

      setTimeout(() => {
        alertBox.remove();
      }, 500);
    }, 5000);
  }
});
</script>

</body>
</html>