<?php
session_start();
include 'config.php';

if (!isset($_SESSION['role']) || !in_array(strtolower($_SESSION['role']), ['superadmin', 'admin', 'md'])) {
    header("Location: index.php");
    exit();
}

$username_session = $_SESSION['username'] ?? '';
$message = '';
$id = $first_name = $last_name = $role = $username = $division = $designation = $location = '';
$division_id = $designation_id = '';

// ── Fetch distinct divisions from users table ──────────────────────────────
$divisions = [];
$res = $conn->query("SELECT DISTINCT division FROM users WHERE division IS NOT NULL AND division != '' ORDER BY division");
if ($res) while ($r = $res->fetch_assoc()) $divisions[] = $r['division'];

// ── Fetch distinct designations from users table ───────────────────────────
$designations = [];
$res = $conn->query("SELECT DISTINCT designation FROM users WHERE designation IS NOT NULL AND designation != '' ORDER BY designation");
if ($res) while ($r = $res->fetch_assoc()) $designations[] = $r['designation'];

// ── Fetch distinct locations from users table ──────────────────────────────
$locations = [];
$res = $conn->query("SELECT DISTINCT location FROM users WHERE location IS NOT NULL AND location != '' ORDER BY location");
if ($res) while ($r = $res->fetch_assoc()) $locations[] = $r['location'];

// ── Handle POST ────────────────────────────────────────────────────────────
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action      = $_POST['action'] ?? 'create';

    // ── Add-on: add new division / designation / location ──────────────────
    if ($action === 'add_division') {
        $new_val = trim($_POST['new_value'] ?? '');
        if ($new_val !== '') {
            $_SESSION['flash_message'] = ['type' => 'info', 'html' => 'Division <strong>' . htmlspecialchars($new_val) . '</strong> noted. It will be saved when the employee is created.'];
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?prefill_division=" . urlencode($new_val));
        exit();
    }

    if ($action === 'add_designation') {
        $new_val = trim($_POST['new_value'] ?? '');
        header("Location: " . $_SERVER['PHP_SELF'] . "?prefill_designation=" . urlencode($new_val));
        exit();
    }

    if ($action === 'add_location') {
        $new_val = trim($_POST['new_value'] ?? '');
        header("Location: " . $_SERVER['PHP_SELF'] . "?prefill_location=" . urlencode($new_val));
        exit();
    }

    // ── Main create ─────────────────────────────────────────────────────────
    $id          = trim($_POST['id'] ?? '');
    $first_name  = trim($_POST['first_name'] ?? '');
    $last_name   = trim($_POST['last_name'] ?? '');
    $role        = trim($_POST['role'] ?? '');
    $username    = trim($_POST['username'] ?? '');
    $password    = $_POST['password'] ?? '';
    $division    = trim($_POST['division'] ?? '');
    $designation = trim($_POST['designation'] ?? '');
    $location    = trim($_POST['location'] ?? '');

    if (empty($id) || empty($first_name) || empty($role) || empty($username) ||
        empty($password) || empty($division) || empty($designation)) {
        $message = ['type' => 'danger', 'text' => 'All fields marked with <strong>*</strong> are required.'];
    } elseif (strlen($password) < 6) {
        $message = ['type' => 'danger', 'text' => 'Password must be at least 6 characters long.'];
    } else {
        $stmt = $conn->prepare("SELECT id, username FROM users WHERE id = ? OR username = ?");
        $stmt->bind_param("ss", $id, $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if ($row['id'] === $id) {
                $message = ['type' => 'danger', 'text' => 'Employee ID <strong>' . htmlspecialchars($id) . '</strong> already exists.'];
            } else {
                $message = ['type' => 'danger', 'text' => 'Username <strong>' . htmlspecialchars($username) . '</strong> already exists.'];
            }
        } else {
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (id, first_name, last_name, username, password, role, division, designation, location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param("sssssssss", $id, $first_name, $last_name, $username, $hashed, $role, $division, $designation, $location);
                if ($stmt->execute()) {
                    $_SESSION['flash_message'] = [
                        'type' => 'success',
                        'html' => 'Employee <strong>' . htmlspecialchars($first_name . ' ' . $last_name) . '</strong> created successfully! ID: <strong>' . htmlspecialchars($id) . '</strong>'
                    ];
                    header("Location: manage_users.php");
                    exit();
                } else {
                    $message = ['type' => 'danger', 'text' => 'Insert failed: ' . htmlspecialchars($stmt->error)];
                }
                $stmt->close();
            } else {
                $message = ['type' => 'danger', 'text' => 'Prepare failed: ' . htmlspecialchars($conn->error)];
            }
        }
    }
}

// Prefill from add-on redirects
$prefill_division    = htmlspecialchars($_GET['prefill_division']    ?? $division);
$prefill_designation = htmlspecialchars($_GET['prefill_designation'] ?? $designation);
$prefill_location    = htmlspecialchars($_GET['prefill_location']    ?? $location);

// Flash message (from redirect)
$flash = '';
if (isset($_SESSION['flash_message'])) {
    $flash = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Create New Employee</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;
  --blue:       #1d4ed8; --blue-light: #dbeafe;
  --green:      #059669; --green-light: #d1fae5;
  --amber:      #d97706; --amber-light: #fef3c7;
  --red:        #dc2626; --red-light:   #fee2e2;
  --info:       #0891b2; --info-light:  #cffafe;
  --radius:     12px;
  --shadow:     0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  font-family: 'Sora', system-ui, sans-serif;
}
html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

/* ─── LAYOUT ─────────────────────────────────────────────────── */
.layout { display: flex; min-height: 100vh; }

/* ─── SIDEBAR ────────────────────────────────────────────────── */
.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item    { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  cursor: pointer; border: none; background: none; width: 100%; text-align: left;
  transition: background .15s, color .15s;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; border-top: 1px solid rgba(255,255,255,.06); }

/* ─── CONTENT ────────────────────────────────────────────────── */
.content { flex: 1; margin-left: var(--sidebar-w); min-width: 0; display: flex; flex-direction: column; transition: margin .3s cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }

/* ─── TOPBAR ─────────────────────────────────────────────────── */
.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb a { color: var(--muted); text-decoration: none; }
.topbar-breadcrumb a:hover { color: var(--ink); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.topbar-spacer { flex: 1; }
.topbar-user { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ink-2); font-weight:500; }
.topbar-avatar {
  width: 30px; height: 30px; border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

/* ─── PAGE ───────────────────────────────────────────────────── */
.page { padding: 24px; flex: 1; }

/* ─── CARD ───────────────────────────────────────────────────── */
.card {
  background: var(--surface); border: 1px solid var(--border);
  border-radius: var(--radius); box-shadow: var(--shadow);
  max-width: 820px; margin: 0 auto;
}
.card-header {
  padding: 20px 28px; border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px;
}
.card-header-icon {
  width: 42px; height: 42px; border-radius: 10px;
  background: var(--blue-light); color: var(--blue);
  display: flex; align-items: center; justify-content: center; font-size: 17px; flex-shrink: 0;
}
.card-header-text .card-title   { font-size: 16px; font-weight: 700; color: var(--ink); }
.card-header-text .card-subtitle { font-size: 12px; color: var(--muted); margin-top: 2px; }
.card-body { padding: 28px; }

/* ─── ALERT ──────────────────────────────────────────────────── */
.alert {
  padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 500;
  display: flex; align-items: flex-start; gap: 10px; margin-bottom: 20px;
  border: 1px solid transparent; animation: fadeUp .25s ease;
}
.alert-success { background: var(--green-light); border-color: #6ee7b7; color: #065f46; }
.alert-danger  { background: var(--red-light);   border-color: #fca5a5; color: #991b1b; }
.alert-info    { background: var(--info-light);  border-color: #67e8f9; color: #164e63; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }

/* ─── FORM ───────────────────────────────────────────────────── */
.form-section-title {
  font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.2px;
  color: var(--muted); padding-bottom: 8px;
  border-bottom: 1px solid var(--border); margin-bottom: 16px; margin-top: 8px;
}
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px; }
.form-grid.three { grid-template-columns: 1fr 1fr 1fr; }
.form-grid.single { grid-template-columns: 1fr; }
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group.span-2 { grid-column: span 2; }
.form-label {
  font-size: 11px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .7px; color: var(--ink-2);
}
.form-label .req { color: var(--red); margin-left: 2px; }
.form-control {
  height: 40px; border: 1px solid var(--border); border-radius: 8px;
  padding: 0 12px; font-size: 13px; font-family: 'Sora', sans-serif;
  color: var(--ink); background: var(--bg); outline: none;
  transition: border-color .15s, box-shadow .15s;
}
.form-control:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,.12); background: var(--surface); }
.form-control.error { border-color: var(--red); background: #fff5f5; }
select.form-control { cursor: pointer; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 12px center; padding-right: 36px; }
.form-hint { font-size: 11px; color: var(--muted); margin-top: 2px; }

/* ─── COMBOBOX (select + add-on) ─────────────────────────────── */
.combo-wrap { display: flex; gap: 6px; align-items: center; }
.combo-wrap select.form-control { flex: 1; }
.btn-addon {
  flex-shrink: 0; height: 40px; width: 40px; border-radius: 8px;
  border: 1px solid var(--border); background: var(--surface);
  color: var(--blue); font-size: 16px; cursor: pointer; display: flex;
  align-items: center; justify-content: center; transition: background .15s, border-color .15s;
}
.btn-addon:hover { background: var(--blue-light); border-color: #93c5fd; }

/* ─── INLINE ADD PANEL ───────────────────────────────────────── */
.add-panel {
  display: none; margin-top: 8px; padding: 12px 14px;
  background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
  animation: fadeUp .2s ease;
}
.add-panel.open { display: block; }
.add-panel-row { display: flex; gap: 8px; }
.add-panel-row .form-control { flex: 1; }
.btn-confirm {
  height: 40px; padding: 0 14px; border-radius: 8px; border: none;
  background: var(--blue); color: #fff; font-size: 12px; font-weight: 600;
  font-family: 'Sora', sans-serif; cursor: pointer; transition: opacity .15s;
  white-space: nowrap;
}
.btn-confirm:hover { opacity: .85; }
.btn-cancel-sm {
  height: 40px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); color: var(--ink-2); font-size: 12px; font-weight: 600;
  font-family: 'Sora', sans-serif; cursor: pointer;
}

/* ─── PASSWORD WRAPPER ───────────────────────────────────────── */
.pw-wrap { position: relative; }
.pw-wrap .form-control { padding-right: 40px; }
.pw-toggle {
  position: absolute; right: 12px; top: 50%; transform: translateY(-50%);
  background: none; border: none; cursor: pointer; color: var(--muted); font-size: 13px; padding: 0;
}
.pw-toggle:hover { color: var(--ink-2); }

/* ─── BUTTONS ────────────────────────────────────────────────── */
.btn-row { display: flex; gap: 10px; margin-top: 8px; }
.btn {
  display: inline-flex; align-items: center; gap: 7px; padding: 10px 20px;
  border-radius: 8px; border: 1px solid transparent;
  font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif;
  cursor: pointer; text-decoration: none; transition: all .15s; white-space: nowrap; line-height: 1;
}
.btn:hover { opacity: .88; transform: translateY(-1px); }
.btn:active { transform: translateY(0); opacity: 1; }
.btn-primary  { background: var(--blue);    color: #fff; border-color: var(--blue); flex: 1; justify-content: center; }
.btn-outline  { background: var(--surface); color: var(--ink-2); border-color: var(--border); }
.btn-outline:hover { background: var(--bg); border-color: #94a3b8; }

/* ─── STRENGTH METER ─────────────────────────────────────────── */
.strength-bar { display: flex; gap: 4px; margin-top: 6px; }
.strength-bar span {
  flex: 1; height: 3px; border-radius: 2px; background: var(--border);
  transition: background .2s;
}
.strength-label { font-size: 11px; color: var(--muted); margin-top: 4px; }

/* ─── MODAL OVERLAY ──────────────────────────────────────────── */
.modal-overlay {
  display: none; position: fixed; inset: 0; background: rgba(15,23,42,.45);
  z-index: 500; align-items: center; justify-content: center;
}
.modal-overlay.open { display: flex; animation: fadeIn .2s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal-box {
  background: var(--surface); border-radius: var(--radius);
  padding: 24px; width: 360px; max-width: 94vw;
  box-shadow: 0 20px 60px rgba(15,23,42,.18);
  animation: slideUp .22s ease;
}
@keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: none; opacity: 1; } }
.modal-title { font-size: 15px; font-weight: 700; margin-bottom: 14px; color: var(--ink); }
.modal-actions { display: flex; gap: 8px; margin-top: 16px; justify-content: flex-end; }

/* ─── RESPONSIVE ─────────────────────────────────────────────── */
@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 14px; }
  .form-grid,
  .form-grid.three { grid-template-columns: 1fr; }
  .form-group.span-2 { grid-column: span 1; }
  .card-body { padding: 18px; }
}
</style>
</head>
<body>
<div class="layout">

<!-- ── SIDEBAR ──────────────────────────────────────────────────── -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <li><a href="manage_users.php"         class="nav-link active"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="https://pupa.mypeopleconnect.app/" class="nav-link"><i class="fas fa-id-card"></i> PEP Login</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- ── CONTENT ───────────────────────────────────────────────────── -->
<div class="content" id="content">

  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>DAP</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <a href="manage_users.php">Employee Details</a>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Create Employee</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo htmlspecialchars($username_session ?: 'Admin'); ?>
    </div>
  </div>

  <div class="page">

    <div class="card">
      <div class="card-header">
        <div class="card-header-icon"><i class="fas fa-user-plus"></i></div>
        <div class="card-header-text">
          <div class="card-title">Create New Employee</div>
          <div class="card-subtitle">Fill in the required fields to register a new employee account</div>
        </div>
      </div>

      <div class="card-body">

        <?php if ($flash): ?>
        <div class="alert alert-<?php echo $flash['type']; ?>">
          <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'info-circle'; ?>"></i>
          <span><?php echo $flash['html']; ?></span>
        </div>
        <?php endif; ?>

        <?php if ($message): ?>
        <div class="alert alert-<?php echo $message['type']; ?>">
          <i class="fas fa-<?php echo $message['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
          <span><?php echo $message['text']; ?></span>
        </div>
        <?php endif; ?>

        <form method="POST" id="createForm" novalidate>
          <input type="hidden" name="action" value="create">

          <!-- ── SECTION: Identity & Access ──────────────────── -->
          <div class="form-section-title">Identity &amp; Access</div>
          <div class="form-grid">

            <div class="form-group">
              <label class="form-label">Employee ID <span class="req">*</span></label>
              <input type="text" name="id" class="form-control" required
                     placeholder="e.g. EMP001 or 2025-001"
                     value="<?php echo htmlspecialchars($id); ?>">
              <span class="form-hint">Must be unique across all employees</span>
            </div>

            <div class="form-group">
              <label class="form-label">First Name <span class="req">*</span></label>
              <input type="text" name="first_name" class="form-control" required
                     value="<?php echo htmlspecialchars($first_name); ?>">
            </div>

            <div class="form-group">
              <label class="form-label">Last Name</label>
              <input type="text" name="last_name" class="form-control"
                     value="<?php echo htmlspecialchars($last_name); ?>">
            </div>

            <div class="form-group">
              <label class="form-label">Username <span class="req">*</span></label>
              <input type="text" name="username" class="form-control" required autocomplete="off"
                     value="<?php echo htmlspecialchars($username); ?>">
              <span class="form-hint">Used for login — must be unique</span>
            </div>

            <div class="form-group span-2">
              <label class="form-label">Password <span class="req">*</span></label>
              <div class="pw-wrap">
                <input type="password" name="password" id="pwField" class="form-control" required minlength="6" oninput="checkStrength(this.value)">
                <button type="button" class="pw-toggle" onclick="togglePw()"><i class="fas fa-eye" id="pwIcon"></i></button>
              </div>
              <div class="strength-bar">
                <span id="s1"></span><span id="s2"></span><span id="s3"></span><span id="s4"></span>
              </div>
              <div class="strength-label" id="strengthLabel">Min. 6 characters</div>
            </div>

          </div>

          <!-- ── SECTION: Role & Department ──────────────────── -->
          <div class="form-section-title">Role &amp; Department</div>
          <div class="form-grid">

            <div class="form-group">
              <label class="form-label">Role <span class="req">*</span></label>
              <select name="role" class="form-control" required>
                <option value="" disabled <?php echo $role === '' ? 'selected' : ''; ?>>— Select Role —</option>
                <option value="admin"    <?php echo $role === 'admin'    ? 'selected' : ''; ?>>Admin</option>
                <option value="md"       <?php echo $role === 'md'       ? 'selected' : ''; ?>>MD</option>
                <option value="manager"  <?php echo $role === 'manager'  ? 'selected' : ''; ?>>Manager</option>
                <option value="employee" <?php echo $role === 'employee' ? 'selected' : ''; ?>>Employee</option>
              </select>
            </div>

            <!-- Division combobox -->
            <div class="form-group">
              <label class="form-label">Department <span class="req">*</span></label>
              <div class="combo-wrap">
                <select name="division" id="divisionSelect" class="form-control" required>
                  <option value="" disabled <?php echo $prefill_division === '' ? 'selected' : ''; ?>>— Select Department —</option>
                  <?php foreach ($divisions as $d): ?>
                  <option value="<?php echo htmlspecialchars($d); ?>"
                    <?php echo $prefill_division === htmlspecialchars($d) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($d); ?>
                  </option>
                  <?php endforeach; ?>
                  <?php if ($prefill_division !== '' && !in_array($prefill_division, $divisions)): ?>
                  <option value="<?php echo $prefill_division; ?>" selected><?php echo $prefill_division; ?></option>
                  <?php endif; ?>
                </select>
                <button type="button" class="btn-addon" title="Add new division" onclick="toggleAddPanel('divisionPanel')">
                  <i class="fas fa-plus"></i>
                </button>
              </div>
              <div class="add-panel" id="divisionPanel">
                <div style="font-size:11px;color:var(--muted);margin-bottom:8px;font-weight:600;">ADD NEW DIVISION</div>
                <div class="add-panel-row">
                  <input type="text" id="newDivisionInput" class="form-control" placeholder="e.g. Finance, Operations">
                  <button type="button" class="btn-confirm" onclick="addOptionInline('divisionSelect','newDivisionInput','divisionPanel')">Add</button>
                  <button type="button" class="btn-cancel-sm" onclick="closePanel('divisionPanel')">Cancel</button>
                </div>
              </div>
            </div>

            <!-- Designation combobox -->
            <div class="form-group">
              <label class="form-label">Designation <span class="req">*</span></label>
              <div class="combo-wrap">
                <select name="designation" id="designationSelect" class="form-control" required>
                  <option value="" disabled <?php echo $prefill_designation === '' ? 'selected' : ''; ?>>— Select Designation —</option>
                  <?php foreach ($designations as $d): ?>
                  <option value="<?php echo htmlspecialchars($d); ?>"
                    <?php echo $prefill_designation === htmlspecialchars($d) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($d); ?>
                  </option>
                  <?php endforeach; ?>
                  <?php if ($prefill_designation !== '' && !in_array($prefill_designation, $designations)): ?>
                  <option value="<?php echo $prefill_designation; ?>" selected><?php echo $prefill_designation; ?></option>
                  <?php endif; ?>
                </select>
                <button type="button" class="btn-addon" title="Add new designation" onclick="toggleAddPanel('designationPanel')">
                  <i class="fas fa-plus"></i>
                </button>
              </div>
              <div class="add-panel" id="designationPanel">
                <div style="font-size:11px;color:var(--muted);margin-bottom:8px;font-weight:600;">ADD NEW DESIGNATION</div>
                <div class="add-panel-row">
                  <input type="text" id="newDesignationInput" class="form-control" placeholder="e.g. Manager, Executive">
                  <button type="button" class="btn-confirm" onclick="addOptionInline('designationSelect','newDesignationInput','designationPanel')">Add</button>
                  <button type="button" class="btn-cancel-sm" onclick="closePanel('designationPanel')">Cancel</button>
                </div>
              </div>
            </div>

            <!-- Location combobox -->
            <div class="form-group">
              <label class="form-label">Location</label>
              <div class="combo-wrap">
                <select name="location" id="locationSelect" class="form-control">
                  <option value="" <?php echo $prefill_location === '' ? 'selected' : ''; ?>>— Select Location —</option>
                  <?php foreach ($locations as $l): ?>
                  <option value="<?php echo htmlspecialchars($l); ?>"
                    <?php echo $prefill_location === htmlspecialchars($l) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($l); ?>
                  </option>
                  <?php endforeach; ?>
                  <?php if ($prefill_location !== '' && !in_array($prefill_location, $locations)): ?>
                  <option value="<?php echo $prefill_location; ?>" selected><?php echo $prefill_location; ?></option>
                  <?php endif; ?>
                </select>
                <button type="button" class="btn-addon" title="Add new location" onclick="toggleAddPanel('locationPanel')">
                  <i class="fas fa-plus"></i>
                </button>
              </div>
              <div class="add-panel" id="locationPanel">
                <div style="font-size:11px;color:var(--muted);margin-bottom:8px;font-weight:600;">ADD NEW LOCATION</div>
                <div class="add-panel-row">
                  <input type="text" id="newLocationInput" class="form-control" placeholder="e.g. Chennai, Mumbai">
                  <button type="button" class="btn-confirm" onclick="addOptionInline('locationSelect','newLocationInput','locationPanel')">Add</button>
                  <button type="button" class="btn-cancel-sm" onclick="closePanel('locationPanel')">Cancel</button>
                </div>
              </div>
            </div>

          </div>

          <div class="btn-row">
            <a href="manage_users.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back</a>
            <button type="submit" class="btn btn-primary"><i class="fas fa-user-plus"></i> Create Employee</button>
          </div>

        </form>
      </div>
    </div>

  </div>
</div>
</div>

<script>
/* ── Sidebar ─────────────────────────────────────────────── */
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.classList.toggle('open');
  btn.nextElementSibling.classList.toggle('open');
}

/* ── Password ────────────────────────────────────────────── */
function togglePw() {
  var f = document.getElementById('pwField');
  var i = document.getElementById('pwIcon');
  if (f.type === 'password') { f.type = 'text'; i.className = 'fas fa-eye-slash'; }
  else { f.type = 'password'; i.className = 'fas fa-eye'; }
}
function checkStrength(v) {
  var bars   = ['s1','s2','s3','s4'].map(function(id){ return document.getElementById(id); });
  var label  = document.getElementById('strengthLabel');
  var colors = ['#dc2626','#d97706','#3b82f6','#059669'];
  var labels = ['Too short','Weak','Good','Strong'];
  bars.forEach(function(b){ b.style.background = 'var(--border)'; });
  if (!v.length) { label.textContent = 'Min. 6 characters'; label.style.color = 'var(--muted)'; return; }
  var score = 0;
  if (v.length >= 6)  score++;
  if (v.length >= 10) score++;
  if (/[A-Z]/.test(v) && /[0-9]/.test(v)) score++;
  if (/[^A-Za-z0-9]/.test(v)) score++;
  score = Math.max(1, score);
  for (var i = 0; i < score; i++) bars[i].style.background = colors[score - 1];
  label.textContent = labels[score - 1];
  label.style.color = colors[score - 1];
}

/* ── Add-on panels ───────────────────────────────────────── */
function toggleAddPanel(panelId) {
  var panel = document.getElementById(panelId);
  var isOpen = panel.classList.contains('open');
  // close all panels first
  document.querySelectorAll('.add-panel').forEach(function(p){ p.classList.remove('open'); });
  if (!isOpen) panel.classList.add('open');
}
function closePanel(panelId) {
  document.getElementById(panelId).classList.remove('open');
}

/**
 * Adds a new <option> to a select, selects it, then closes the panel.
 * Prevents duplicates (case-insensitive).
 */
function addOptionInline(selectId, inputId, panelId) {
  var sel   = document.getElementById(selectId);
  var input = document.getElementById(inputId);
  var val   = input.value.trim();
  if (!val) { input.focus(); return; }

  // Check for duplicate
  var dup = false;
  for (var i = 0; i < sel.options.length; i++) {
    if (sel.options[i].value.toLowerCase() === val.toLowerCase()) { dup = true; break; }
  }
  if (dup) {
    sel.value = sel.options[[...sel.options].findIndex(function(o){ return o.value.toLowerCase() === val.toLowerCase(); })].value;
    input.value = '';
    closePanel(panelId);
    return;
  }

  var opt = document.createElement('option');
  opt.value = val;
  opt.textContent = val;
  sel.appendChild(opt);
  sel.value = val;
  input.value = '';
  closePanel(panelId);
}

/* ── Client-side validation ──────────────────────────────── */
document.getElementById('createForm').addEventListener('submit', function(e) {
  var required = this.querySelectorAll('[required]');
  var ok = true;
  required.forEach(function(el) {
    el.classList.remove('error');
    if (!el.value.trim()) { el.classList.add('error'); ok = false; }
  });
  var pw = document.getElementById('pwField');
  if (pw.value.length > 0 && pw.value.length < 6) { pw.classList.add('error'); ok = false; }
  if (!ok) {
    e.preventDefault();
    // Scroll to first error
    var first = document.querySelector('.error');
    if (first) first.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
});

// Remove error highlight on input
document.querySelectorAll('.form-control').forEach(function(el) {
  el.addEventListener('input', function() { this.classList.remove('error'); });
  el.addEventListener('change', function() { this.classList.remove('error'); });
});

// Close add panel when clicking outside
document.addEventListener('click', function(e) {
  if (!e.target.closest('.form-group')) {
    document.querySelectorAll('.add-panel').forEach(function(p){ p.classList.remove('open'); });
  }
});
</script>
</body>
</html>