<?php
// view_user_details.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Cache-Control: no-cache, must-revalidate, no-store, max-age=0");
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit(); }
require_once __DIR__ . '/config.php';
if (!isset($conn) || !($conn instanceof mysqli)) { http_response_code(500); die("<h2>DB error</h2>"); }

// ── Config ──
$UPLOAD_DIR    = __DIR__ . '/uploads/';
$MAX_FILE_SIZE = 5 * 1024 * 1024;
$ALLOWED_MIMES = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif'];
if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR, 0755, true);

// ── Static Enums ──
$enum_values = [
    'role'                      => ['superadmin', 'admin', 'employee', 'manager', 'md'],
    'level'                     => ['L1', 'L2', 'L3', 'L4', 'L5'],
    'marital_status'            => ['Single', 'Married', 'Divorced'],
    'gender'                    => ['Male', 'Female', 'Others'],
    'status'                    => ['active', 'resigned', 'deleted'],
    'appointment_type'          => ['regular', 'contract', 'intern'],
    'responsibilities_accepted' => ['Pending', 'Accepted', 'Rejected'],
    'details_accepted'          => ['Pending', 'Accepted', 'Rejected'],
    'Company'                   => ['SPICA Tnagar', 'SPICA BANGALORE', 'SPICA HO'],
    'is_superadmin'             => ['0', '1'],
];

// ── Allowed fields ──
$allowed_fields = [
    'id', 'username', 'email', 'official_email', 'personal_email',
    'role', 'mobileno', 'office_mobile_number', 'address',
    'current_address', 'permanent_address',
    'pancard', 'aadharcard', 'photo', 'profile_photo',
    'designation', 'division', 'marital_status', 'anniversary_date', 'gender',
    'dob', 'date_of_joining',
    'father_name', 'mother_name', 'spouse_name',
    'qualification', 'previous_experience', 'company_name', 'last_company_1',
    'last_company_1_years', 'last_company_1_salary', 'total_experience_years',
    'previous_salary', 'uan_no', 'epf_no', 'bloodgroup', 'esic_no', 'bank_name',
    'account_number', 'ifsc_code', 'first_name', 'last_name', 'level',
    'performance', 'appointment_type', 'location', 'work_location',
    'Company', 'KPI', 'kpi_status',
    'responsibilities', 'responsibilities_accepted', 'details_accepted',
    'reporting_manager_id',
    'basic_salary', 'emergency_contact_no',
    'emergency_contact_person', 'emergency_contact_relationship',
    'emergency_contact_name', 'emergency_contact_phone',
    'status', 'resignation_date', 'rejoin_date',
    'is_superadmin',
];

$msg  = '';
$user = null;

// ── Helpers ──
function mk_alert($t, $m) {
    $icon = $t === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    return "<div class='alert alert-{$t}'><i class='fas {$icon}'></i> {$m}</div>";
}

function db_update($conn, $f, $v, $uid) {
    $stmt = $conn->prepare("UPDATE users SET `{$f}` = ? WHERE id = ?");
    if (!$stmt) return mk_alert('danger', 'Prepare failed: ' . htmlspecialchars($conn->error));
    $stmt->bind_param('ss', $v, $uid);
    $ok = $stmt->execute();
    $err = $stmt->error;
    $stmt->close();
    return $ok
        ? mk_alert('success', 'Field updated successfully.')
        : mk_alert('danger', 'DB error: ' . htmlspecialchars($err));
}

// ── Handle POST ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['field_name']) && !empty($_POST['user_id'])) {
    $fn  = trim($_POST['field_name']);
    $uid = trim($_POST['user_id']);

    if (!in_array($fn, $allowed_fields, true)) {
        $msg = mk_alert('danger', 'Invalid field.');
    } elseif ($fn === 'photo' || $fn === 'profile_photo') {
        // ── Photo upload ──
        $f = $_FILES['photo'] ?? null;
        if (!$f || $f['error'] !== UPLOAD_ERR_OK) {
            $msg = mk_alert('danger', 'Upload error (code ' . ($f['error'] ?? '?') . ').');
        } else {
            $mime = (new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
            if (!isset($ALLOWED_MIMES[$mime])) {
                $msg = mk_alert('danger', 'Invalid file type — JPG, PNG or GIF only.');
            } elseif ($f['size'] > $MAX_FILE_SIZE) {
                $msg = mk_alert('danger', 'File too large (max 5 MB).');
            } else {
                $ext  = $ALLOWED_MIMES[$mime];
                $name = 'user_' . preg_replace('/[^0-9A-Za-z_-]/', '', $uid) . '_' . time() . '.' . $ext;
                if (move_uploaded_file($f['tmp_name'], $UPLOAD_DIR . $name)) {
                    @chmod($UPLOAD_DIR . $name, 0644);
                    $msg = db_update($conn, $fn, $name, $uid);
                } else {
                    $msg = mk_alert('danger', 'Failed to move uploaded file.');
                }
            }
        }
    } else {
        // ── Text / select / date fields ──
        $raw = trim($_POST['field_value'] ?? '');
        $err = false;

        $date_fields     = ['resignation_date', 'rejoin_date', 'dob', 'date_of_joining',
                            'anniversary_date', 'probation_end_date', 'confirmation_date'];
        $num_fields      = ['basic_salary', 'previous_salary', 'last_company_1_salary', 'total_experience_years'];
        $int_fields      = ['last_company_1_years', 'performance'];

        // Static enum validation
        if (!$err && isset($enum_values[$fn]) && $raw !== '' && !in_array($raw, $enum_values[$fn], true)) {
            $msg = mk_alert('danger', 'Invalid selection for ' . htmlspecialchars($fn) . '.');
            $err = true;
        }

        // Email
        if (!$err && in_array($fn, ['email','official_email','personal_email']) && $raw !== '' && !filter_var($raw, FILTER_VALIDATE_EMAIL)) {
            $msg = mk_alert('danger', 'Invalid email address.');
            $err = true;
        }

        // Numeric
        if (!$err && in_array($fn, $num_fields, true) && $raw !== '') {
            $n = str_replace(',', '', $raw);
            if (!is_numeric($n)) { $msg = mk_alert('danger', 'Must be a numeric value.'); $err = true; }
            else $raw = $n;
        }

        // Date
        if (!$err && in_array($fn, $date_fields, true) && $raw !== '') {
            $dt = DateTime::createFromFormat('Y-m-d', $raw);
            if (!$dt || $dt->format('Y-m-d') !== $raw) {
                $msg = mk_alert('danger', 'Invalid date — use YYYY-MM-DD format.');
                $err = true;
            }
        }

        // Integer
        if (!$err && in_array($fn, $int_fields, true) && $raw !== '' && !ctype_digit(strval($raw))) {
            $msg = mk_alert('danger', 'Must be a whole number.');
            $err = true;
        }

        if (!$err) {
            $val = (in_array($fn, $date_fields, true) && ($raw === '' || strtolower($raw) === 'n/a'))
                ? null
                : ($raw === '' ? null : $raw);
            $msg = db_update($conn, $fn, $val, $uid);
        }
    }
}

// ── Load user ──
$user_id = trim($_GET['id'] ?? '');
if ($user_id === '') {
    $msg = mk_alert('danger', 'Missing user ID.');
} else {
    $s = $conn->prepare("SELECT * FROM users WHERE id = ?");
    if ($s) {
        $s->bind_param('s', $user_id);
        $s->execute();
        $user = $s->get_result()->fetch_assoc();
        $s->close();
        if (!$user) $msg = mk_alert('danger', 'User not found.');
    }
}

// ── Compute age from DOB ──
$computed_age = null;
if (!empty($user['dob'])) {
    try {
        $dob = new DateTime($user['dob']);
        $now = new DateTime();
        $computed_age = (int)$now->diff($dob)->y;
    } catch (Exception $e) {
        $computed_age = null;
    }
}

// ── Fetch distinct non-empty values from a column ──
function fetch_distinct($conn, $col) {
    $list = [];
    $sql  = "SELECT DISTINCT `{$col}` FROM users WHERE `{$col}` IS NOT NULL AND `{$col}` != '' ORDER BY `{$col}`";
    if ($r = $conn->query($sql)) {
        while ($row = $r->fetch_row()) $list[] = $row[0];
        $r->free();
    }
    return $list;
}

$division_options      = fetch_distinct($conn, 'division');
$designation_options   = fetch_distinct($conn, 'designation');
$location_options      = fetch_distinct($conn, 'location');
$work_location_options = fetch_distinct($conn, 'work_location');

$division_json      = json_encode($division_options,      JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$designation_json   = json_encode($designation_options,   JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$location_json      = json_encode($location_options,      JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$work_location_json = json_encode($work_location_options, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// ── Manager list ──
$manager_options = [];
$s = $conn->prepare("SELECT id, CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,''),' (',username,')') AS label FROM users WHERE status='active' ORDER BY first_name");
if ($s) {
    $s->execute();
    $res = $s->get_result();
    while ($row = $res->fetch_assoc()) $manager_options[$row['id']] = trim($row['label']);
    $s->close();
}
$manager_json = json_encode($manager_options, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// ── Photo URL ──
function photo_url($fn) {
    $base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/uploads/';
    if ($fn && is_file(__DIR__ . '/uploads/' . $fn)) return $base . rawurlencode($fn);
    if (is_file(__DIR__ . '/uploads/default-profile.png')) return $base . 'default-profile.png';
    return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
}
$photo     = $user ? photo_url($user['photo'] ?? $user['profile_photo'] ?? null) . '?cb=' . time() : '';
$enum_json = json_encode($enum_values, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// ── Reporting manager display ──
$reporting_manager_name = '—';
if (!empty($user['reporting_manager_id']) && isset($manager_options[$user['reporting_manager_id']])) {
    $reporting_manager_name = $manager_options[$user['reporting_manager_id']];
}

// ── Render helpers ──
function js_esc($s) {
    return addslashes(htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'));
}

function frow($label, $key, $user) {
    $raw = $user[$key] ?? '';
    $val = ($raw === '' || $raw === null)
        ? '<span class="na">—</span>'
        : nl2br(htmlspecialchars($raw));
    $uid = js_esc($user['id']);
    $k   = js_esc($key);
    $v   = js_esc($raw ?? '');
    echo "<div class='fr'>
            <span class='fl'>" . htmlspecialchars($label) . "</span>
            <span class='fv'>{$val}</span>
            <button type='button' class='eb' onclick=\"openModal('{$k}','{$v}','{$uid}')\" title='Edit'>
              <i class='fas fa-pen'></i>
            </button>
          </div>";
}

function frow_readonly($label, $value_display) {
    $val = ($value_display === '' || $value_display === null)
        ? '<span class="na">—</span>'
        : nl2br(htmlspecialchars((string)$value_display));
    echo "<div class='fr'>
            <span class='fl'>" . htmlspecialchars($label) . "</span>
            <span class='fv'>{$val}</span>
            <span class='eb-ro' title='Read only'><i class='fas fa-lock'></i></span>
          </div>";
}

function frow_bool($label, $key, $user) {
    $raw = $user[$key] ?? '0';
    $display = $raw ? '<span class="badge-yes"><i class="fas fa-check"></i> Yes</span>'
                    : '<span class="badge-no"><i class="fas fa-times"></i> No</span>';
    $uid = js_esc($user['id']);
    $k   = js_esc($key);
    $v   = js_esc($raw ?? '');
    echo "<div class='fr'>
            <span class='fl'>" . htmlspecialchars($label) . "</span>
            <span class='fv'>{$display}</span>
            <button type='button' class='eb' onclick=\"openModal('{$k}','{$v}','{$uid}')\" title='Edit'>
              <i class='fas fa-pen'></i>
            </button>
          </div>";
}

function frow_manager($label, $raw_id, $display_name, $user_id_val) {
    $val = ($raw_id === '' || $raw_id === null)
        ? '<span class="na">—</span>'
        : htmlspecialchars($display_name);
    $uid = js_esc($user_id_val);
    $v   = js_esc($raw_id ?? '');
    echo "<div class='fr'>
            <span class='fl'>" . htmlspecialchars($label) . "</span>
            <span class='fv'>{$val}</span>
            <button type='button' class='eb' onclick=\"openModal('reporting_manager_id','{$v}','{$uid}')\" title='Edit'>
              <i class='fas fa-pen'></i>
            </button>
          </div>";
}

function sec($title, $icon, $color, $open = true) {
    $c = $open ? '' : 'collapsed';
    echo "<div class='sc {$c}'>
            <div class='sh' onclick='toggleSec(this)'>
              <span class='si' style='background:{$color}1a;color:{$color}'><i class='{$icon}'></i></span>
              <span class='st'>{$title}</span>
              <i class='fas fa-chevron-down sa'></i>
            </div>
            <div class='sb'>";
}
function endsec() { echo "</div></div>"; }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Employee Profile — MPC</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root {
  --sw: 256px; --sw-collapsed: 56px;
  --sb-bg: #0d1b2a; --sb-bdr: rgba(255,255,255,.07); --sb-txt: #c8d6e5;
  --sb-mut: #55687a; --sb-hov: rgba(255,255,255,.055);
  --sb-act-bg: rgba(59,130,246,.18); --sb-act: #93c5fd; --sb-acc: #3b82f6;
  --topbar-h: 54px;
  --bg: #f1f5f9; --sur: #fff; --bdr: #e2e8f0;
  --txt: #0f172a; --mut: #94a3b8; --sec: #475569;
  --bl: #2563eb; --bl-l: #eff6ff;
  --gn: #16a34a; --gn-l: #f0fdf4;
  --rd: #dc2626; --rd-l: #fff1f2;
  --am: #d97706; --am-l: #fffbeb;
  --r: 10px; --rs: 6px;
  --sh: 0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
  --sh2: 0 4px 20px rgba(0,0,0,.08);
  --t: .22s ease;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', sans-serif; font-size: 14px; background: var(--bg); color: var(--txt); min-height: 100vh; display: flex; }

/* ═══ SIDEBAR ═══ */
.sidebar {
  width: var(--sw); background: var(--sb-bg); color: var(--sb-txt);
  position: fixed; left: 0; top: 0; bottom: 0;
  display: flex; flex-direction: column; overflow: hidden;
  z-index: 1100; border-right: 1px solid var(--sb-bdr);
  transition: width var(--t), transform var(--t);
}
.sidebar.sb-collapsed { width: var(--sw-collapsed); }
.sidebar.sb-collapsed .sb-name,
.sidebar.sb-collapsed .sb-sub,
.sidebar.sb-collapsed .sb-label,
.sidebar.sb-collapsed .nav-link span,
.sidebar.sb-collapsed .nav-dropdown-toggle span:not(.arrow),
.sidebar.sb-collapsed .nav-dropdown-toggle .arrow,
.sidebar.sb-collapsed .nav-submenu { display: none; }
.sidebar.sb-collapsed .nav-link,
.sidebar.sb-collapsed .nav-dropdown-toggle { justify-content: center; padding-left: 0; padding-right: 0; }
.sidebar.sb-collapsed .nav-link i,
.sidebar.sb-collapsed .nav-dropdown-toggle i:first-child { width: auto; margin: 0; font-size: 14px; }
.sidebar.sb-collapsed .nav-link[data-label]:hover::after,
.sidebar.sb-collapsed .nav-dropdown-toggle[data-label]:hover::after {
  content: attr(data-label); position: absolute;
  left: calc(var(--sw-collapsed) + 8px); top: 50%; transform: translateY(-50%);
  background: #1e293b; color: #e2e8f0; font-size: 12px; font-weight: 500;
  padding: 5px 10px; border-radius: 6px; white-space: nowrap;
  z-index: 9999; pointer-events: none; box-shadow: 0 2px 8px rgba(0,0,0,.3);
}
.sidebar.sb-collapsed .nav-dropdown-toggle { cursor: default; }
.sidebar.sb-collapsed .sb-brand { justify-content: center; padding: 16px 0 13px; }
.sidebar.sb-collapsed .sb-footer { padding: 10px 0 0; }
.sidebar.sb-collapsed .sb-footer .nav-link { padding-left: 0; justify-content: center; }
.sidebar.sb-collapsed .sb-footer .nav-link i { width: auto; }
.sidebar.sb-collapsed .sb-footer .nav-link .sb-logout-txt { display: none; }
.sb-toggle-btn {
  display: flex; align-items: center; justify-content: center;
  width: 100%; padding: 10px 0;
  background: none; border: none; border-top: 1px solid var(--sb-bdr);
  color: var(--sb-mut); cursor: pointer; font-size: 13px; gap: 7px;
  transition: background var(--t), color var(--t); flex-shrink: 0;
}
.sb-toggle-btn:hover { background: var(--sb-hov); color: #fff; }
.sb-toggle-btn .toggle-label { font-size: 12px; font-weight: 500; white-space: nowrap; overflow: hidden; }
.sidebar.sb-collapsed .sb-toggle-btn .toggle-label { display: none; }
.sb-brand {
  display: flex; align-items: center; gap: 10px;
  padding: 16px 18px 13px; border-bottom: 1px solid var(--sb-bdr);
  flex-shrink: 0; transition: padding var(--t);
}
.sb-logo {
  width: 32px; height: 32px; background: var(--sb-acc); border-radius: 8px;
  display: flex; align-items: center; justify-content: center;
  font-weight: 700; font-size: 13px; color: #fff; flex-shrink: 0;
}
.sb-name { font-size: 14px; font-weight: 700; color: #fff; white-space: nowrap; overflow: hidden; }
.sb-sub  { font-size: 10px; color: var(--sb-mut); text-transform: uppercase; letter-spacing: .5px; white-space: nowrap; overflow: hidden; }
.sb-nav {
  flex: 1; overflow-y: auto; overflow-x: hidden; padding: 10px 0 6px;
  scrollbar-width: thin; scrollbar-color: rgba(255,255,255,.08) transparent;
}
.sb-nav::-webkit-scrollbar { width: 3px; }
.sb-nav::-webkit-scrollbar-thumb { background: rgba(255,255,255,.1); border-radius: 3px; }
.sb-label { font-size: 9.5px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; color: var(--sb-mut); padding: 10px 18px 3px; white-space: nowrap; overflow: hidden; }
.nav-link {
  display: flex; align-items: center; gap: 9px; padding: 7.5px 18px;
  color: var(--sb-txt); text-decoration: none; font-size: 13px; font-weight: 400;
  position: relative; transition: background var(--t), color var(--t); white-space: nowrap;
}
.nav-link i { width: 16px; text-align: center; font-size: 12px; opacity: .8; flex-shrink: 0; }
.nav-link:hover { background: var(--sb-hov); color: #fff; }
.nav-link.active { background: var(--sb-act-bg); color: var(--sb-act); font-weight: 500; }
.nav-link.active::before { content: ''; position: absolute; left: 0; top: 4px; bottom: 4px; width: 3px; background: var(--sb-acc); border-radius: 0 3px 3px 0; }
.nav-dropdown-toggle {
  display: flex; align-items: center; gap: 9px; width: 100%; padding: 7.5px 18px;
  background: none; border: none; color: var(--sb-txt); font-size: 13px; font-weight: 500;
  cursor: pointer; text-align: left; transition: background var(--t), color var(--t); white-space: nowrap;
}
.nav-dropdown-toggle i:first-child { width: 16px; text-align: center; font-size: 12px; opacity: .8; flex-shrink: 0; }
.nav-dropdown-toggle:hover { background: var(--sb-hov); color: #fff; }
.nav-dropdown-toggle .arrow { margin-left: auto; font-size: 9px; opacity: .55; transition: transform var(--t); }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style: none; margin: 0; padding: 0; max-height: 0; overflow: hidden; background: rgba(0,0,0,.14); transition: max-height .32s cubic-bezier(.4,0,.2,1); }
.nav-submenu.open { max-height: 700px; }
.nav-submenu .nav-link { padding-left: 43px; font-size: 12.5px; }
.sb-footer { padding: 10px 18px 0; border-top: 1px solid var(--sb-bdr); flex-shrink: 0; transition: padding var(--t); }
.sb-backdrop { display: none; position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 1050; }
.sb-backdrop.active { display: block; }

/* ═══ TOPBAR ═══ */
.topbar {
  position: fixed; top: 0; left: var(--sw); right: 0; height: var(--topbar-h);
  background: var(--sur); border-bottom: 1px solid var(--bdr);
  display: flex; align-items: center; gap: 10px; padding: 0 22px;
  z-index: 900; box-shadow: var(--sh); transition: left var(--t);
}
.topbar.sb-collapsed-offset { left: var(--sw-collapsed); }
.tb-hamburger { display: none; background: none; border: none; color: var(--sec); font-size: 18px; cursor: pointer; padding: 5px 7px; border-radius: var(--rs); transition: background var(--t); }
.tb-hamburger:hover { background: var(--bg); }
.tb-sep { color: var(--mut); font-size: 9px; }
.tb-link { color: var(--mut); text-decoration: none; font-size: 13px; }
.tb-link:hover { color: var(--bl); }
.tb-cur { color: var(--txt); font-weight: 500; font-size: 13px; }
.tb-right { margin-left: auto; display: flex; align-items: center; gap: 8px; }
.tb-id { font-size: 11.5px; color: var(--mut); background: var(--bg); padding: 3px 10px; border-radius: 20px; border: 1px solid var(--bdr); }
.tb-back { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; background: var(--sur); border: 1px solid var(--bdr); border-radius: var(--rs); color: var(--sec); font-size: 13px; font-weight: 500; text-decoration: none; transition: all var(--t); }
.tb-back:hover { background: var(--bl-l); border-color: #bfdbfe; color: var(--bl); }

/* ═══ MAIN ═══ */
.main-wrap { margin-left: var(--sw); padding-top: var(--topbar-h); flex: 1; min-width: 0; transition: margin-left var(--t); }
.main-wrap.sb-collapsed-offset { margin-left: var(--sw-collapsed); }
.page { padding: 22px 24px 60px; }

/* ═══ ALERT ═══ */
.alert {
  padding: 10px 16px; border-radius: var(--rs); margin-bottom: 14px;
  font-size: 13.5px; font-weight: 500; border-left: 4px solid;
  display: flex; align-items: center; gap: 8px;
}
.alert-success { background: var(--gn-l); color: #15803d; border-color: #22c55e; }
.alert-danger  { background: var(--rd-l); color: #be123c;  border-color: #f43f5e; }
.alert-info    { background: #cffafe;     color: #164e63;  border-color: #67e8f9; }

/* ═══ HERO ═══ */
.hero {
  background: var(--sur); border: 1px solid var(--bdr); border-radius: var(--r);
  box-shadow: var(--sh2); padding: 22px 26px; margin-bottom: 18px;
  display: flex; align-items: center; gap: 20px; position: relative; overflow: hidden;
}
.hero::before {
  content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
  background: linear-gradient(90deg, var(--bl), #818cf8, #06b6d4);
}
.pw { position: relative; flex-shrink: 0; }
.uimg { width: 82px; height: 82px; object-fit: cover; border-radius: 50%; border: 3px solid var(--sur); box-shadow: 0 0 0 3px var(--bl), var(--sh); display: block; cursor: pointer; }
.cam {
  position: absolute; bottom: 1px; right: 1px; width: 24px; height: 24px;
  background: var(--bl); color: #fff; border: 2px solid var(--sur);
  border-radius: 50%; display: flex; align-items: center; justify-content: center;
  font-size: 10px; cursor: pointer; transition: all var(--t); border: none;
}
.cam:hover { background: #1d4ed8; transform: scale(1.1); }
.pname  { font-size: 18px; font-weight: 700; line-height: 1.2; margin-bottom: 3px; }
.pdesig { font-size: 13px; color: var(--sec); margin-bottom: 8px; }
.ptags  { display: flex; flex-wrap: wrap; gap: 6px; }
.ptag   { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 20px; font-size: 11.5px; font-weight: 500; }
.t-bl { background: var(--bl-l); color: var(--bl); }
.t-gn { background: var(--gn-l); color: var(--gn); }
.t-gr { background: var(--bg); color: var(--sec); border: 1px solid var(--bdr); }
.t-rd { background: var(--rd-l); color: var(--rd); }
.t-am { background: var(--am-l); color: var(--am); }
.t-pu { background: #f5f3ff; color: #7c3aed; }

/* ═══ GRID ═══ */
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
.span2 { grid-column: span 2; }
.span3 { grid-column: span 3; }
@media (max-width: 1200px) { .grid { grid-template-columns: repeat(2, 1fr); } .span2 { grid-column: auto; } .span3 { grid-column: span 2; } }
@media (max-width: 700px)  { .grid { grid-template-columns: 1fr; } .span2 { grid-column: auto; } .span3 { grid-column: auto; } }

/* ═══ SECTION CARDS ═══ */
.sc { background: var(--sur); border: 1px solid var(--bdr); border-radius: var(--r); box-shadow: var(--sh); overflow: hidden; }
.sh { display: flex; align-items: center; gap: 9px; padding: 11px 15px; border-bottom: 1px solid var(--bdr); background: #fafbfc; cursor: pointer; user-select: none; }
.sh:hover { background: #f1f5f9; }
.si { width: 26px; height: 26px; border-radius: var(--rs); display: flex; align-items: center; justify-content: center; font-size: 11px; flex-shrink: 0; }
.st { font-size: 12.5px; font-weight: 600; flex: 1; }
.sa { font-size: 10px; color: var(--mut); transition: transform var(--t); }
.sc.collapsed .sa { transform: rotate(-90deg); }
.sb { padding: 0 15px; overflow: hidden; transition: max-height .26s ease; }
.sc.collapsed .sb { max-height: 0 !important; padding: 0 15px; }

/* ═══ FIELD ROWS ═══ */
.fr { display: flex; align-items: flex-start; gap: 10px; padding: 9px 0; border-bottom: 1px solid #f1f5f9; }
.fr:last-child { border-bottom: none; }
.fl { min-width: 150px; max-width: 150px; font-size: 10.5px; font-weight: 500; color: var(--mut); text-transform: uppercase; letter-spacing: .35px; padding-top: 2px; flex-shrink: 0; }
.fv { flex: 1; font-size: 13px; color: var(--txt); word-break: break-word; }
.na { font-size: 12px; color: var(--mut); font-style: italic; }
.eb { background: none; border: 1px solid transparent; color: var(--mut); padding: 2px 6px; border-radius: 5px; cursor: pointer; font-size: 11px; transition: all var(--t); flex-shrink: 0; line-height: 1; }
.eb:hover { background: var(--bl-l); color: var(--bl); border-color: #bfdbfe; }
.eb-ro { display: inline-flex; align-items: center; justify-content: center; color: var(--mut); opacity: .4; padding: 2px 6px; font-size: 11px; flex-shrink: 0; }

/* ═══ BADGE BOOL ═══ */
.badge-yes { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 600; color: var(--gn); background: var(--gn-l); padding: 2px 8px; border-radius: 20px; }
.badge-no  { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 600; color: var(--mut); background: var(--bg); padding: 2px 8px; border-radius: 20px; border: 1px solid var(--bdr); }

/* ═══ AGE BADGE ═══ */
.age-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 600; color: #0284c7; background: #e0f2fe; padding: 2px 9px; border-radius: 20px; }

/* ═══ MODAL ═══ */
.modal-content { border: none; border-radius: var(--r); box-shadow: 0 20px 60px rgba(0,0,0,.14); }
.modal-header  { border-bottom: 1px solid var(--bdr); padding: 15px 20px; }
.modal-title   { font-size: 14px; font-weight: 600; }
.modal-body    { padding: 18px 20px; }
.modal-footer  { border-top: 1px solid var(--bdr); padding: 11px 20px; }
.form-label    { font-size: 11px; font-weight: 600; color: var(--sec); text-transform: uppercase; letter-spacing: .4px; }
.form-control, .form-select { border: 1px solid var(--bdr); border-radius: var(--rs); font-family: 'Inter', sans-serif; font-size: 14px; }
.form-control:focus, .form-select:focus { border-color: var(--bl); box-shadow: 0 0 0 3px rgba(37,99,235,.1); }
.src-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 600; border-radius: 4px; padding: 2px 7px; margin-bottom: 8px; }

/* Combo-box style for division/designation/location in modal */
.modal-combo-row { display: flex; gap: 6px; width: 100%; align-items: center; }
.modal-combo-row .form-select { flex: 1; }
.btn-add-new {
  flex-shrink: 0; height: 38px; width: 38px; border-radius: var(--rs);
  border: 1px solid var(--bdr); background: var(--sur); color: var(--bl);
  font-size: 15px; cursor: pointer; display: flex; align-items: center;
  justify-content: center; transition: background var(--t), border-color var(--t);
}
.btn-add-new:hover { background: var(--bl-l); border-color: #93c5fd; }
.new-entry-panel {
  display: none; width: 100%; margin-top: 6px;
  padding: 10px 12px; background: var(--bg);
  border: 1px solid var(--bdr); border-radius: var(--rs); animation: fadeUp .18s ease;
}
.new-entry-panel.open { display: block; }
.new-entry-row { display: flex; gap: 6px; }
.new-entry-row .form-control { flex: 1; }
.btn-confirm-sm { height: 38px; padding: 0 12px; border-radius: var(--rs); border: none; background: var(--bl); color: #fff; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; }
.btn-confirm-sm:hover { opacity: .85; }
.btn-cancel-sm  { height: 38px; padding: 0 10px; border-radius: var(--rs); border: 1px solid var(--bdr); background: var(--sur); color: var(--sec); font-size: 12px; font-weight: 600; cursor: pointer; }

@keyframes fadeUp { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }

/* ═══ RESPONSIVE ═══ */
@media (max-width: 1024px) {
  .sidebar { transform: translateX(calc(-1 * var(--sw))); width: var(--sw) !important; }
  .sidebar.open { transform: translateX(0); box-shadow: var(--sh2); }
  .sidebar.sb-collapsed { transform: translateX(calc(-1 * var(--sw))); }
  .main-wrap { margin-left: 0 !important; } .topbar { left: 0 !important; }
  .tb-hamburger { display: flex; } .sb-toggle-btn { display: none; }
}
@media (max-width: 600px) {
  .page { padding: 14px 14px 60px; }
  .hero { flex-direction: column; gap: 14px; padding: 18px; }
  .fl  { min-width: 110px; max-width: 110px; }
}
</style>
</head>
<body>

<!-- ═══════════════════════════════
     SIDEBAR
═══════════════════════════════ -->
<aside class="sidebar" id="sidebar">
  <div class="sb-brand">
    <div class="sb-logo">MPC</div>
    <div><div class="sb-name">MPC Portal</div><div class="sb-sub">HR Management</div></div>
  </div>
  <div class="sb-nav">
    <a href="dashboard_admin.php" class="nav-link" data-label="Organisation Chart">
      <i class="fas fa-sitemap"></i> <span>Organisation Chart</span>
    </a>
    <div class="sb-label">Modules</div>

    <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)" data-label="DAP">
      <i class="fas fa-folder-open"></i> <span>DAP</span> <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>

    <button class="nav-dropdown-toggle" onclick="toggleMenu(this)" data-label="CAB">
      <i class="fas fa-calendar-alt"></i> <span>CAB</span> <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>

    <button class="nav-dropdown-toggle" onclick="toggleMenu(this)" data-label="PEP">
      <i class="fas fa-user-tie"></i> <span>PEP</span> <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>

    <button class="nav-dropdown-toggle" onclick="toggleMenu(this)" data-label="L&amp;D">
      <i class="fas fa-book-open"></i> <span>L&amp;D</span> <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>

    <button class="nav-dropdown-toggle" onclick="toggleMenu(this)" data-label="AAA">
      <i class="fas fa-star"></i> <span>AAA</span> <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>
  </div>

  <div class="sb-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;padding-left:18px;" data-label="Logout">
      <i class="fas fa-sign-out-alt"></i> <span class="sb-logout-txt">Logout</span>
    </a>
  </div>
  <button class="sb-toggle-btn" id="sbToggleBtn" title="Toggle sidebar">
    <i class="fas fa-chevron-left" id="sbToggleIcon"></i>
    <span class="toggle-label">Collapse</span>
  </button>
</aside>

<div class="sb-backdrop" id="sbBackdrop"></div>

<!-- ═══════════════════════════════
     TOPBAR
═══════════════════════════════ -->
<div class="topbar" id="topbar">
  <button class="tb-hamburger" id="hamburgerBtn"><i class="fas fa-bars" id="hIcon"></i></button>
  <a href="dashboard_admin.php" class="tb-link" style="font-weight:700;color:var(--bl);">MPC</a>
  <span class="tb-sep"><i class="fas fa-chevron-right"></i></span>
  <a href="manage_users.php" class="tb-link">Employees</a>
  <span class="tb-sep"><i class="fas fa-chevron-right"></i></span>
  <span class="tb-cur">
    <?php if ($user) echo htmlspecialchars(trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?: ($user['username'] ?? 'Profile'));
    else echo 'Profile'; ?>
  </span>
  <div class="tb-right">
    <?php if ($user): ?>
      <span class="tb-id">ID: <?= htmlspecialchars($user['id']) ?></span>
    <?php endif; ?>
    <a href="manage_users.php" class="tb-back"><i class="fas fa-arrow-left"></i> Back</a>
  </div>
</div>

<!-- ═══════════════════════════════
     MAIN CONTENT
═══════════════════════════════ -->
<div class="main-wrap" id="mainWrap">
  <div class="page">

    <?php if ($msg) echo $msg; ?>

    <?php if ($user): ?>

    <!-- HERO -->
    <div class="hero">
      <div class="pw">
        <img id="uimg" src="<?= htmlspecialchars($photo) ?>" class="uimg" alt="Photo"
             onclick="openModal('photo','','<?= js_esc($user['id']) ?>')">
        <button type="button" class="cam"
                onclick="openModal('photo','','<?= js_esc($user['id']) ?>')" title="Change photo">
          <i class="fas fa-camera"></i>
        </button>
      </div>
      <div>
        <div class="pname">
          <?= htmlspecialchars(trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?: ($user['username'] ?? '—')) ?>
        </div>
        <div class="pdesig">
          <?= htmlspecialchars(($user['designation'] ?? '') ?: 'No designation') ?>
          <?php if (!empty($user['division'])): ?> · <?= htmlspecialchars($user['division']) ?><?php endif; ?>
        </div>
        <div class="ptags">
          <?php if (!empty($user['level'])): ?>
            <span class="ptag t-bl"><i class="fas fa-layer-group"></i> <?= htmlspecialchars($user['level']) ?></span>
          <?php endif; ?>
          <?php if (!empty($user['location'])): ?>
            <span class="ptag t-gr"><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($user['location']) ?></span>
          <?php endif; ?>
          <?php $st = $user['status'] ?? 'active'; ?>
          <span class="ptag <?= $st === 'active' ? 't-gn' : ($st === 'resigned' ? 't-rd' : 't-gr') ?>">
            <i class="fas fa-circle" style="font-size:7px"></i> <?= ucfirst(htmlspecialchars($st)) ?>
          </span>
          <?php if (!empty($user['appointment_type'])): ?>
            <?php $apt = $user['appointment_type']; ?>
            <span class="ptag <?= $apt === 'intern' ? 't-pu' : 't-gr' ?>">
              <i class="fas fa-briefcase"></i> <?= ucfirst(htmlspecialchars($apt)) ?>
            </span>
          <?php endif; ?>
          <?php if (!empty($user['Company'])): ?>
            <span class="ptag t-am"><i class="fas fa-building"></i> <?= htmlspecialchars($user['Company']) ?></span>
          <?php endif; ?>
          <?php if ($computed_age !== null): ?>
            <span class="ptag t-gr"><i class="fas fa-birthday-cake"></i> <?= $computed_age ?> yrs</span>
          <?php endif; ?>
          <?php if (!empty($user['is_superadmin'])): ?>
            <span class="ptag t-rd"><i class="fas fa-crown"></i> Super Admin</span>
          <?php endif; ?>
        </div>
      </div>
    </div><!-- /hero -->

    <!-- GRID -->
    <div class="grid">

      <!-- ── 1. Account ── -->
      <?php sec('Account', 'fas fa-shield-alt', '#2563eb'); ?>
        <?php
          frow('ID',              'id',             $user);
          frow('Username',        'username',       $user);
          frow('Official Email',  'official_email', $user);
          frow('Personal Email',  'personal_email', $user);
          frow('Role',            'role',           $user);
          frow('Status',          'status',         $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 2. Employment ── -->
      <?php sec('Employment', 'fas fa-id-badge', '#7c3aed'); ?>
        <?php
          frow('First Name',       'first_name',       $user);
          frow('Last Name',        'last_name',        $user);
          frow('Designation',      'designation',      $user);
          frow('Department',       'division',         $user);
          frow('Level',            'level',            $user);
          frow('Appt. Type',       'appointment_type', $user);
          frow('Company',          'Company',          $user);
          frow('Location',         'location',         $user);
          frow('Work Location',    'work_location',    $user);
          frow('Date of Joining',  'date_of_joining',  $user);
          frow_manager('Reporting Manager', $user['reporting_manager_id'] ?? '', $reporting_manager_name, $user['id']);
        ?>
      <?php endsec(); ?>

      <!-- ── 3. Personal ── -->
      <?php sec('Personal', 'fas fa-heart', '#e11d48'); ?>
        <?php
          frow('Father Name',    'father_name',      $user);
          frow('Mother Name',    'mother_name',      $user);
          frow('Spouse Name',    'spouse_name',      $user);
          frow('Marital Status', 'marital_status',   $user);
          frow('Anniversary',    'anniversary_date', $user);
          frow('Gender',         'gender',           $user);
          frow('Date of Birth',  'dob',              $user);
          frow_readonly('Age', $computed_age !== null ? $computed_age . ' years' : '');
          frow('Blood Group',    'bloodgroup',       $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 4. Contact & ID ── -->
      <?php sec('Contact & ID', 'fas fa-address-card', '#0f766e'); ?>
        <?php
          frow('Personal Mobile',   'mobileno',             $user);
          frow('Office Mobile',     'office_mobile_number', $user);
          frow('Address',           'address',              $user);
          frow('Current Address',   'current_address',      $user);
          frow('Permanent Address', 'permanent_address',    $user);
          frow('PAN',               'pancard',              $user);
          frow('Aadhar',            'aadharcard',           $user);
          frow('UAN No',            'uan_no',               $user);
          frow('EPF No',            'epf_no',               $user);
          frow('ESIC No',           'esic_no',              $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 5. Emergency Contact ── -->
      <?php sec('Emergency Contact', 'fas fa-first-aid', '#dc2626'); ?>
        <?php
          frow('Contact Person',   'emergency_contact_person',       $user);
          frow('Contact Name',     'emergency_contact_name',         $user);
          frow('Contact No',       'emergency_contact_no',           $user);
          frow('Contact Phone',    'emergency_contact_phone',        $user);
          frow('Relationship',     'emergency_contact_relationship',  $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 6. Financial & Bank ── -->
      <?php sec('Financial & Bank', 'fas fa-university', '#d97706'); ?>
        <?php
          frow('Basic Salary',  'basic_salary',  $user);
          frow('Bank Name',     'bank_name',     $user);
          frow('Account No',    'account_number', $user);
          frow('IFSC',          'ifsc_code',     $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 7. Individual KPI ── -->
      <?php sec('Individual KPI', 'fas fa-bullseye', '#059669'); ?>
        <?php
          frow('KPI',         'KPI',         $user);
          frow('KPI Status',  'kpi_status',  $user);
          frow('Performance', 'performance', $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 8. Experience ── -->
      <?php sec('Experience', 'fas fa-briefcase', '#4338ca'); ?>
        <?php
          frow('Qualification',    'qualification',          $user);
          frow('Prev. Experience', 'previous_experience',    $user);
          frow('Total Exp. Yrs',   'total_experience_years', $user);
          frow('Company',          'company_name',           $user);
          frow('Last Company',     'last_company_1',         $user);
          frow('LC Years',         'last_company_1_years',   $user);
          frow('LC Salary',        'last_company_1_salary',  $user);
        ?>
      <?php endsec(); ?>

      <!-- ── 9. Resignation / Rejoining (full width) ── -->
      <div class="span3">
        <?php sec('Resignation & Rejoining', 'fas fa-door-open', '#64748b', false); ?>
          <?php
            frow('Resignation Date', 'resignation_date', $user);
            frow('Rejoin Date',      'rejoin_date',      $user);
          ?>
        <?php endsec(); ?>
      </div>

      <!-- ── 10. Responsibilities (full width) ── -->
      <div class="span3">
        <?php sec('Responsibilities & Acceptance', 'fas fa-clipboard-check', '#0284c7'); ?>
          <?php
            frow('Responsibilities',  'responsibilities',          $user);
            frow('Resp. Accepted',    'responsibilities_accepted', $user);
            frow('Details Accepted',  'details_accepted',          $user);
          ?>
        <?php endsec(); ?>
      </div>

    </div><!-- /grid -->

    <?php else: ?>
      <div class="sc"><div style="padding:40px;text-align:center;color:var(--mut)">
        <i class="fas fa-user-slash" style="font-size:32px;display:block;margin-bottom:12px"></i>
        No user data found.
      </div></div>
    <?php endif; ?>

  </div>
</div>

<!-- ═══════════════════════════════
     EDIT MODAL
═══════════════════════════════ -->
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <form class="modal-content" method="POST" enctype="multipart/form-data" id="editForm">

      <div class="modal-header">
        <h5 class="modal-title" id="mTitle">Edit Field</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" name="user_id"    id="fUid">
        <input type="hidden" name="field_name" id="fName">
        <!-- SINGLE authoritative field_value — JS copies the active control's value here before submit -->
        <input type="hidden" name="field_value" id="fValue">

        <div id="srcBadge" style="display:none" class="src-badge mb-2"></div>
        <label id="fLbl" class="form-label mb-1 d-block"></label>

        <!-- 1. Plain text / date / email / tel -->
        <input type="text" class="form-control" id="fText" autocomplete="off" style="display:none">

        <!-- 2. Textarea -->
        <textarea class="form-control" id="fTextarea" rows="4" style="display:none;resize:vertical"></textarea>

        <!-- 3. Static enum select -->
        <select class="form-select" id="fSel" style="display:none"></select>

        <!-- 4. Department (division) — combo: existing + add new -->
        <div id="fDivWrap" style="display:none">
          <div class="modal-combo-row">
            <select class="form-select" id="fDivSel"></select>
            <button type="button" class="btn-add-new" title="Add new department" onclick="toggleNewEntry('divNewPanel','divNewInput')">
              <i class="fas fa-plus"></i>
            </button>
          </div>
          <div class="new-entry-panel" id="divNewPanel">
            <div style="font-size:10px;font-weight:600;color:var(--mut);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px;">New Department</div>
            <div class="new-entry-row">
              <input type="text" class="form-control" id="divNewInput" placeholder="e.g. Finance, Operations">
              <button type="button" class="btn-confirm-sm" onclick="applyNewEntry('fDivSel','divNewInput','divNewPanel')">Add</button>
              <button type="button" class="btn-cancel-sm"  onclick="closeNewEntry('divNewPanel','divNewInput')">Cancel</button>
            </div>
          </div>
        </div>

        <!-- 5. Designation — combo: existing + add new -->
        <div id="fDesWrap" style="display:none">
          <div class="modal-combo-row">
            <select class="form-select" id="fDesSel"></select>
            <button type="button" class="btn-add-new" title="Add new designation" onclick="toggleNewEntry('desNewPanel','desNewInput')">
              <i class="fas fa-plus"></i>
            </button>
          </div>
          <div class="new-entry-panel" id="desNewPanel">
            <div style="font-size:10px;font-weight:600;color:var(--mut);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px;">New Designation</div>
            <div class="new-entry-row">
              <input type="text" class="form-control" id="desNewInput" placeholder="e.g. Manager, Executive">
              <button type="button" class="btn-confirm-sm" onclick="applyNewEntry('fDesSel','desNewInput','desNewPanel')">Add</button>
              <button type="button" class="btn-cancel-sm"  onclick="closeNewEntry('desNewPanel','desNewInput')">Cancel</button>
            </div>
          </div>
        </div>

        <!-- 6. Location — combo: existing + add new -->
        <div id="fLocWrap" style="display:none">
          <div class="modal-combo-row">
            <select class="form-select" id="fLocSel"></select>
            <button type="button" class="btn-add-new" title="Add new location" onclick="toggleNewEntry('locNewPanel','locNewInput')">
              <i class="fas fa-plus"></i>
            </button>
          </div>
          <div class="new-entry-panel" id="locNewPanel">
            <div style="font-size:10px;font-weight:600;color:var(--mut);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px;">New Location</div>
            <div class="new-entry-row">
              <input type="text" class="form-control" id="locNewInput" placeholder="e.g. Chennai, Mumbai">
              <button type="button" class="btn-confirm-sm" onclick="applyNewEntry('fLocSel','locNewInput','locNewPanel')">Add</button>
              <button type="button" class="btn-cancel-sm"  onclick="closeNewEntry('locNewPanel','locNewInput')">Cancel</button>
            </div>
          </div>
        </div>

        <!-- 7. Work Location — combo: existing + add new -->
        <div id="fWLocWrap" style="display:none">
          <div class="modal-combo-row">
            <select class="form-select" id="fWLocSel"></select>
            <button type="button" class="btn-add-new" title="Add new work location" onclick="toggleNewEntry('wlocNewPanel','wlocNewInput')">
              <i class="fas fa-plus"></i>
            </button>
          </div>
          <div class="new-entry-panel" id="wlocNewPanel">
            <div style="font-size:10px;font-weight:600;color:var(--mut);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px;">New Work Location</div>
            <div class="new-entry-row">
              <input type="text" class="form-control" id="wlocNewInput" placeholder="e.g. Remote, Head Office">
              <button type="button" class="btn-confirm-sm" onclick="applyNewEntry('fWLocSel','wlocNewInput','wlocNewPanel')">Add</button>
              <button type="button" class="btn-cancel-sm"  onclick="closeNewEntry('wlocNewPanel','wlocNewInput')">Cancel</button>
            </div>
          </div>
        </div>

        <!-- 8. Reporting Manager -->
        <select class="form-select" id="fMgrSel" style="display:none"></select>

        <!-- 9. Photo upload -->
        <input type="file" class="form-control" id="fFile" name="photo" accept="image/*" style="display:none">

        <!-- hint text -->
        <p id="modalHint" class="mt-2 mb-0 small text-muted" style="display:none"></p>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary btn-sm px-4" id="saveBtn">
          <i class="fas fa-save"></i> Save
        </button>
      </div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ═══════════════════════════════════════════════════════════════
   PHP DATA
═══════════════════════════════════════════════════════════════ */
const ENUMS         = <?= $enum_json ?>;
const MANAGERS      = <?= $manager_json ?>;
const DEPARTMENTS   = <?= $division_json ?>;
const DESIGNATIONS  = <?= $designation_json ?>;
const LOCATIONS     = <?= $location_json ?>;
const WORK_LOCS     = <?= $work_location_json ?>;

const DATE_FIELDS     = ['dob','date_of_joining','resignation_date','rejoin_date',
                         'anniversary_date','probation_end_date','confirmation_date'];
const TEXTAREA_FIELDS = ['address','current_address','permanent_address','responsibilities','KPI'];

/* ═══════════════════════════════════════════════════════════════
   SIDEBAR
═══════════════════════════════════════════════════════════════ */
const sidebar      = document.getElementById('sidebar');
const backdrop     = document.getElementById('sbBackdrop');
const hIcon        = document.getElementById('hIcon');
const mainWrap     = document.getElementById('mainWrap');
const topbar       = document.getElementById('topbar');
const sbToggleBtn  = document.getElementById('sbToggleBtn');
const sbToggleIcon = document.getElementById('sbToggleIcon');
const isMobile     = () => window.innerWidth <= 1024;

function applyCollapsed(c) {
  if (c) {
    sidebar.classList.add('sb-collapsed');
    mainWrap.classList.add('sb-collapsed-offset');
    topbar.classList.add('sb-collapsed-offset');
    sbToggleIcon.className = 'fas fa-chevron-right';
    sbToggleBtn.querySelector('.toggle-label').textContent = '';
  } else {
    sidebar.classList.remove('sb-collapsed');
    mainWrap.classList.remove('sb-collapsed-offset');
    topbar.classList.remove('sb-collapsed-offset');
    sbToggleIcon.className = 'fas fa-chevron-left';
    sbToggleBtn.querySelector('.toggle-label').textContent = 'Collapse';
  }
}
if (!isMobile()) applyCollapsed(localStorage.getItem('sb_collapsed') === 'true');

sbToggleBtn.addEventListener('click', () => {
  const n = !sidebar.classList.contains('sb-collapsed');
  applyCollapsed(n);
  localStorage.setItem('sb_collapsed', n);
});

document.getElementById('hamburgerBtn').addEventListener('click', () => {
  const o = sidebar.classList.toggle('open');
  backdrop.classList.toggle('active', o);
  hIcon.className = o ? 'fas fa-times' : 'fas fa-bars';
});

backdrop.addEventListener('click', () => {
  sidebar.classList.remove('open');
  backdrop.classList.remove('active');
  hIcon.className = 'fas fa-bars';
});

window.addEventListener('resize', () => {
  if (!isMobile()) {
    sidebar.classList.remove('open');
    backdrop.classList.remove('active');
    hIcon.className = 'fas fa-bars';
    applyCollapsed(localStorage.getItem('sb_collapsed') === 'true');
  } else {
    sidebar.classList.remove('sb-collapsed');
    mainWrap.classList.remove('sb-collapsed-offset');
    topbar.classList.remove('sb-collapsed-offset');
  }
});

function toggleMenu(btn) {
  if (sidebar.classList.contains('sb-collapsed') && !isMobile()) return;
  const sub  = btn.nextElementSibling;
  const open = btn.classList.toggle('open');
  if (sub) sub.classList.toggle('open', open);
}

/* ═══════════════════════════════════════════════════════════════
   SECTION COLLAPSE / EXPAND
═══════════════════════════════════════════════════════════════ */
document.querySelectorAll('.sc').forEach(card => {
  const body        = card.querySelector('.sb');
  const isCollapsed = card.classList.contains('collapsed');
  body.style.maxHeight = isCollapsed ? '0' : 'none';
});

function toggleSec(hdr) {
  const card    = hdr.closest('.sc');
  const body    = card.querySelector('.sb');
  const closing = !card.classList.contains('collapsed');
  if (closing) {
    body.style.maxHeight = body.scrollHeight + 'px';
    requestAnimationFrame(() => requestAnimationFrame(() => {
      card.classList.add('collapsed');
      body.style.maxHeight = '0';
    }));
  } else {
    card.classList.remove('collapsed');
    body.style.maxHeight = body.scrollHeight + 'px';
    body.addEventListener('transitionend', () => {
      if (!card.classList.contains('collapsed')) body.style.maxHeight = 'none';
    }, { once: true });
  }
}

/* ═══════════════════════════════════════════════════════════════
   MODAL — helpers
═══════════════════════════════════════════════════════════════ */
const ALL_INPUTS = [
  'fText','fTextarea','fSel',
  'fDivWrap','fDesWrap','fLocWrap','fWLocWrap',
  'fMgrSel','fFile'
];

function hideAllInputs() {
  ALL_INPUTS.forEach(id => {
    const el = document.getElementById(id);
    if (el) el.style.display = 'none';
  });
  ['divNewPanel','desNewPanel','locNewPanel','wlocNewPanel'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.classList.remove('open');
  });
  document.getElementById('modalHint').style.display = 'none';
  document.getElementById('srcBadge').style.display  = 'none';
}

function showBadge(icon, label, bg, color) {
  const b = document.getElementById('srcBadge');
  b.style.background = bg;
  b.style.color      = color;
  b.style.display    = 'inline-flex';
  b.innerHTML        = `<i class="${icon}" style="margin-right:4px"></i>${label}`;
}

function esc(s) {
  return String(s ?? '')
    .replace(/&/g,'&amp;').replace(/"/g,'&quot;')
    .replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

function buildSelectFromArray(selId, arr, currentVal, placeholder) {
  const sel  = document.getElementById(selId);
  let   html = `<option value="">${esc(placeholder)}</option>`;
  arr.forEach(v => {
    const sel_attr = String(v) === String(currentVal) ? ' selected' : '';
    html += `<option value="${esc(v)}"${sel_attr}>${esc(v)}</option>`;
  });
  if (currentVal && currentVal !== '' && !arr.includes(currentVal)) {
    html += `<option value="${esc(currentVal)}" selected>${esc(currentVal)} (current)</option>`;
  }
  sel.innerHTML = html;
}

/* ═══════════════════════════════════════════════════════════════
   MODAL — OPEN
═══════════════════════════════════════════════════════════════ */
function openModal(fn, fv, uid) {
  hideAllInputs();

  document.getElementById('fUid').value  = uid;
  document.getElementById('fName').value = fn;

  const label = fn.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  document.getElementById('mTitle').textContent = 'Edit — ' + label;
  document.getElementById('fLbl').textContent   = label;

  /* ── Photo ── */
  if (fn === 'photo' || fn === 'profile_photo') {
    document.getElementById('fFile').style.display = 'block';
    const hint = document.getElementById('modalHint');
    hint.textContent = 'JPG, PNG or GIF · Max 5 MB';
    hint.style.display = 'block';

  /* ── Reporting Manager ── */
  } else if (fn === 'reporting_manager_id') {
    const sel = document.getElementById('fMgrSel');
    let html  = '<option value="">— Select Manager —</option>';
    Object.entries(MANAGERS).forEach(([id, name]) => {
      const selected = String(id) === String(fv) ? ' selected' : '';
      html += `<option value="${esc(id)}"${selected}>${esc(name)}</option>`;
    });
    sel.innerHTML = html;
    sel.style.display = 'block';
    showBadge('fas fa-users', 'Active employees', '#7c3aed1a', '#7c3aed');

  /* ── Department / division ── */
  } else if (fn === 'division') {
    buildSelectFromArray('fDivSel', DEPARTMENTS, fv, '— Select Department —');
    document.getElementById('fDivWrap').style.display = 'block';
    showBadge('fas fa-database', 'Existing departments + add new', '#2563eb1a', '#2563eb');

  /* ── Designation ── */
  } else if (fn === 'designation') {
    buildSelectFromArray('fDesSel', DESIGNATIONS, fv, '— Select Designation —');
    document.getElementById('fDesWrap').style.display = 'block';
    showBadge('fas fa-database', 'Existing designations + add new', '#7c3aed1a', '#7c3aed');

  /* ── Location ── */
  } else if (fn === 'location') {
    buildSelectFromArray('fLocSel', LOCATIONS, fv, '— Select Location —');
    document.getElementById('fLocWrap').style.display = 'block';
    showBadge('fas fa-database', 'Existing locations + add new', '#0f766e1a', '#0f766e');

  /* ── Work Location ── */
  } else if (fn === 'work_location') {
    buildSelectFromArray('fWLocSel', WORK_LOCS, fv, '— Select Work Location —');
    document.getElementById('fWLocWrap').style.display = 'block';
    showBadge('fas fa-database', 'Existing work locations + add new', '#0f766e1a', '#0f766e');

  /* ── Static enum ── */
  } else if (ENUMS[fn]) {
    const sel = document.getElementById('fSel');
    sel.innerHTML = `<option value="">— Select —</option>` + ENUMS[fn].map(o =>
      `<option value="${esc(o)}"${o === fv ? ' selected' : ''}>${esc(o)}</option>`
    ).join('');
    sel.style.display = 'block';

  /* ── Textarea fields ── */
  } else if (TEXTAREA_FIELDS.includes(fn)) {
    const ta = document.getElementById('fTextarea');
    ta.value = fv || '';
    ta.style.display = 'block';

  /* ── Plain text / date / email / tel ── */
  } else {
    const t = document.getElementById('fText');
    if (['email','official_email','personal_email'].includes(fn))     t.type = 'email';
    else if (['mobileno','office_mobile_number',
              'emergency_contact_no','emergency_contact_phone'].includes(fn)) t.type = 'tel';
    else if (DATE_FIELDS.includes(fn))   t.type = 'date';
    else                                 t.type = 'text';
    t.value = fv || '';
    t.style.display = 'block';
  }

  const modal = new bootstrap.Modal(document.getElementById('editModal'));
  modal.show();

  document.getElementById('editModal').addEventListener('shown.bs.modal', () => {
    const active = ALL_INPUTS.map(id => document.getElementById(id))
      .find(el => el && el.style.display !== 'none');
    if (active && active.tagName !== 'DIV') {
      try { active.focus(); } catch(e) {}
    }
  }, { once: true });
}

/* ═══════════════════════════════════════════════════════════════
   NEW ENTRY PANEL
═══════════════════════════════════════════════════════════════ */
function toggleNewEntry(panelId, inputId) {
  const panel  = document.getElementById(panelId);
  const isOpen = panel.classList.contains('open');
  ['divNewPanel','desNewPanel','locNewPanel','wlocNewPanel'].forEach(id =>
    document.getElementById(id).classList.remove('open')
  );
  if (!isOpen) {
    panel.classList.add('open');
    document.getElementById(inputId).focus();
  }
}

function closeNewEntry(panelId, inputId) {
  document.getElementById(panelId).classList.remove('open');
  document.getElementById(inputId).value = '';
}

function applyNewEntry(selectId, inputId, panelId) {
  const sel   = document.getElementById(selectId);
  const input = document.getElementById(inputId);
  const val   = input.value.trim();
  if (!val) { input.focus(); return; }
  const existing = Array.from(sel.options).find(o => o.value.toLowerCase() === val.toLowerCase());
  if (existing) {
    sel.value = existing.value;
  } else {
    const opt = new Option(val, val, true, true);
    sel.appendChild(opt);
    sel.value = val;
  }
  input.value = '';
  document.getElementById(panelId).classList.remove('open');
}

/* ═══════════════════════════════════════════════════════════════
   FORM SUBMIT
═══════════════════════════════════════════════════════════════ */
document.getElementById('editForm').addEventListener('submit', function (e) {
  const fn  = document.getElementById('fName').value;
  const out = document.getElementById('fValue');

  if (fn === 'photo' || fn === 'profile_photo') {
    // uses name="photo" file input directly
  } else if (fn === 'reporting_manager_id') {
    out.value = document.getElementById('fMgrSel').value;
  } else if (fn === 'division') {
    out.value = document.getElementById('fDivSel').value;
  } else if (fn === 'designation') {
    out.value = document.getElementById('fDesSel').value;
  } else if (fn === 'location') {
    out.value = document.getElementById('fLocSel').value;
  } else if (fn === 'work_location') {
    out.value = document.getElementById('fWLocSel').value;
  } else if (document.getElementById('fSel').style.display !== 'none') {
    out.value = document.getElementById('fSel').value;
  } else if (document.getElementById('fTextarea').style.display !== 'none') {
    out.value = document.getElementById('fTextarea').value;
  } else {
    out.value = document.getElementById('fText').value;
  }

  const btn = document.getElementById('saveBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving…';
});

// Live photo preview
document.getElementById('fFile').addEventListener('change', function () {
  if (this.files && this.files[0]) {
    const reader = new FileReader();
    reader.onload = e => document.getElementById('uimg').src = e.target.result;
    reader.readAsDataURL(this.files[0]);
  }
});
</script>
</body>
</html>
<?php $conn->close(); ?>