<?php
/* Enhanced Employee Master Details - Ant Design UI Theme */
/* Preserves ALL xcrud logic, relations, nested tables, user-role access */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('Employee Master Details');
include('includes/newheader.php');

$userid = $_SESSION['UserID'];
?>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
<script src="angular/angular.min.js"></script>

<style>
:root{--emp-primary:#2AABB3;--emp-primary-dark:#1E8F96;--emp-primary-light:#E6F7F8;--emp-success:#52C41A;--emp-warning:#FAAD14;--emp-danger:#FF4D4F;--emp-bg:#F5F6FA;--emp-card:#FFFFFF;--emp-text:#1F2937;--emp-text-sec:#6B7280;--emp-border:#E5E7EB;--emp-radius:8px;--emp-shadow:0 1px 3px rgba(0,0,0,.04),0 4px 12px rgba(0,0,0,.03);--emp-font:'Poppins',-apple-system,BlinkMacSystemFont,sans-serif}
.m-content{padding:0!important}.m-portlet{margin:0!important;box-shadow:none!important;border:none!important}.m-portlet__body{padding:0!important}.m-subheader{display:none!important}

/* Page Header */
.emp-hdr{background:linear-gradient(135deg,#187278 0%,#1E8F96 30%,#2AABB3 70%,#38C4CC 100%);border-radius:14px;padding:28px 32px;margin:16px 20px 20px;color:#fff;position:relative;overflow:hidden;font-family:var(--emp-font);animation:empIn .4s ease-out}
.emp-hdr::before{content:'';position:absolute;top:-50%;right:-5%;width:320px;height:320px;background:radial-gradient(circle,rgba(255,255,255,.1) 0%,transparent 70%);border-radius:50%;pointer-events:none}
.emp-hdr h1{margin:0 0 4px;font-size:22px;font-weight:600;letter-spacing:-.3px;position:relative;z-index:1}
.emp-hdr p{margin:0;font-size:13px;opacity:.85;position:relative;z-index:1}
.emp-hdr .bc{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;opacity:.75;margin-top:10px;position:relative;z-index:1}
.emp-hdr .bc a{color:#fff;text-decoration:none}.emp-hdr .bc a:hover{text-decoration:underline}
.emp-wrap{padding:0 20px 20px;font-family:var(--emp-font);animation:empIn .4s ease-out .1s both}
@keyframes empIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

/* Table List View */
.xcrud-row-list,.xcrud-row-list .xcrud-list-container{border-radius:12px!important;overflow:hidden!important}
.xcrud-row-list{background:var(--emp-card);border-radius:12px;box-shadow:var(--emp-shadow);border:1px solid var(--emp-border);overflow:hidden;margin-bottom:20px}
table.xcrud-list{border-collapse:collapse!important;width:100%!important;font-family:var(--emp-font)!important;font-size:13px!important}
table.xcrud-list thead tr{background:linear-gradient(180deg,#FAFBFC 0%,#F3F4F6 100%)!important;border-bottom:2px solid var(--emp-border)!important}
table.xcrud-list thead th{font-weight:600!important;font-size:11.5px!important;text-transform:uppercase!important;letter-spacing:.5px!important;color:var(--emp-text-sec)!important;padding:12px 14px!important;border:none!important;border-bottom:2px solid var(--emp-border)!important;white-space:nowrap!important;font-family:var(--emp-font)!important}
table.xcrud-list tbody td{padding:11px 14px!important;border:none!important;border-bottom:1px solid #F3F4F6!important;color:var(--emp-text)!important;font-family:var(--emp-font)!important;vertical-align:middle!important;font-size:13px!important}
table.xcrud-list tbody tr{transition:background .15s ease!important}
table.xcrud-list tbody tr:hover{background:#F0FDFE!important}
table.xcrud-list tbody tr:nth-child(even){background:#FAFBFC}
table.xcrud-list tbody tr:nth-child(even):hover{background:#F0FDFE!important}

/* Table Name */
.xcrud-top-actions h3,h3.xcrud-table-name,.xcrud-table-name{font-family:var(--emp-font)!important;font-size:18px!important;font-weight:600!important;color:var(--emp-text)!important;margin:0 0 4px!important;letter-spacing:-.2px!important}

/* Buttons */
a.xcrud-action,button.xcrud-action,.xcrud-nav a,.xcrud-button,.xcrud-top-actions a,input.xcrud-button,input[type="submit"].xcrud-button{font-family:var(--emp-font)!important;font-size:13px!important;font-weight:500!important;border-radius:6px!important;padding:7px 16px!important;transition:all .2s ease!important;border:1px solid var(--emp-border)!important;background:#fff!important;color:var(--emp-text)!important;cursor:pointer!important;text-decoration:none!important;display:inline-flex!important;align-items:center!important;gap:6px!important;line-height:1.5!important}
a.xcrud-action:hover,button.xcrud-action:hover,.xcrud-button:hover,.xcrud-top-actions a:hover{border-color:var(--emp-primary)!important;color:var(--emp-primary)!important;background:var(--emp-primary-light)!important;text-decoration:none!important}
.xcrud-top-actions .xcrud-action[data-task="create"],.xcrud-detail-cell input[type="submit"],input.btn.btn-primary{background:linear-gradient(135deg,var(--emp-primary-dark) 0%,var(--emp-primary) 100%)!important;color:#fff!important;border:none!important;padding:8px 20px!important;font-weight:600!important;box-shadow:0 2px 6px rgba(42,171,179,.25)!important}
.xcrud-top-actions .xcrud-action[data-task="create"]:hover,.xcrud-detail-cell input[type="submit"]:hover{background:linear-gradient(135deg,#187278 0%,var(--emp-primary-dark) 100%)!important;box-shadow:0 4px 12px rgba(42,171,179,.35)!important;transform:translateY(-1px)}

/* Tabs - Ant Design Style */
.xcrud-nav.nav-tabs,ul.xcrud-nav,.xcrud-nav{display:flex!important;flex-wrap:wrap!important;gap:0!important;border-bottom:2px solid var(--emp-border)!important;margin-bottom:24px!important;padding:0!important;list-style:none!important;background:transparent!important}
.xcrud-nav li{list-style:none!important}
.xcrud-nav li a,.xcrud-nav a,.xcrud-tab a{display:inline-flex!important;align-items:center!important;gap:6px!important;padding:10px 18px!important;font-family:var(--emp-font)!important;font-size:13px!important;font-weight:500!important;color:var(--emp-text-sec)!important;text-decoration:none!important;border:none!important;border-bottom:2px solid transparent!important;margin-bottom:-2px!important;background:transparent!important;transition:all .2s ease!important;cursor:pointer!important;white-space:nowrap!important;border-radius:0!important}
.xcrud-nav li a:hover,.xcrud-nav a:hover{color:var(--emp-primary)!important;border-bottom-color:var(--emp-primary)!important;background:var(--emp-primary-light)!important}
.xcrud-nav li.active a,.xcrud-nav li a.active,.xcrud-nav a.active,.xcrud-tab.active a,.xcrud-nav .active>a{color:var(--emp-primary)!important;font-weight:600!important;border-bottom:2px solid var(--emp-primary)!important;background:transparent!important}

/* Edit Form */
.xcrud-row-edit,.xcrud-row-detail,.xcrud-row-create{background:var(--emp-card);border-radius:12px;box-shadow:var(--emp-shadow);border:1px solid var(--emp-border);overflow:hidden;padding:0}
.xcrud-detail table,.xcrud-edit-container table{width:100%!important;border-collapse:collapse!important}
.xcrud-detail td,.xcrud-edit-container td{padding:10px 16px!important;border:none!important;border-bottom:1px solid #F3F4F6!important;font-family:var(--emp-font)!important;font-size:13px!important;vertical-align:middle!important}
td.xcrud-auto-label,.xcrud-in label,td.xcrud-label,.xcrud-edit-container td.xcrud-edit-label{font-weight:600!important;color:var(--emp-text)!important;font-size:12.5px!important;text-transform:capitalize!important;white-space:nowrap!important;min-width:160px!important;font-family:var(--emp-font)!important}

/* Input Fields */
.xcrud-edit-container input[type="text"],.xcrud-edit-container input[type="number"],.xcrud-edit-container input[type="email"],.xcrud-edit-container input[type="date"],.xcrud-edit-container textarea,.xcrud-edit-container select,.xcrud-input,.xcrud-in input[type="text"],.xcrud-in input[type="number"],.xcrud-in select,.xcrud-in textarea,input.xcrud-input{font-family:var(--emp-font)!important;font-size:13.5px!important;padding:8px 12px!important;border:1.5px solid var(--emp-border)!important;border-radius:6px!important;background:#FAFBFC!important;color:var(--emp-text)!important;transition:all .2s ease!important;width:100%!important;max-width:450px!important;box-sizing:border-box!important}
.xcrud-edit-container input:focus,.xcrud-edit-container select:focus,.xcrud-edit-container textarea:focus,.xcrud-input:focus,.xcrud-in input:focus,.xcrud-in select:focus,input.xcrud-input:focus{border-color:var(--emp-primary)!important;background:#fff!important;box-shadow:0 0 0 3px rgba(42,171,179,.1)!important;outline:none!important}
.xcrud-edit-container input[type="checkbox"],.xcrud-in input[type="checkbox"]{width:18px!important;height:18px!important;accent-color:var(--emp-primary)!important;cursor:pointer!important}

/* Nested Tables */
.xcrud-nested,.xcrud-row-nested{margin-top:8px!important;border:1px solid var(--emp-border)!important;border-radius:10px!important;overflow:hidden!important;background:#FAFBFC!important}
.xcrud-nested .xcrud-top{background:linear-gradient(180deg,#F8FAFB 0%,#F0F2F5 100%)!important;padding:14px 18px!important;border-bottom:1px solid var(--emp-border)!important}
.xcrud-nested .xcrud-top h4,.xcrud-nested h4{font-family:var(--emp-font)!important;font-size:14px!important;font-weight:600!important;color:var(--emp-text)!important;margin:0!important}
.xcrud-nested table.xcrud-list{font-size:12.5px!important}
.xcrud-nested table.xcrud-list thead th{font-size:10.5px!important;padding:10px 12px!important;background:#F3F5F7!important}
.xcrud-nested table.xcrud-list tbody td{padding:9px 12px!important;font-size:12.5px!important}

/* Pagination */
.xcrud-pagination,.xcrud-nav-pagination,.xcrud-page-nav{display:flex!important;align-items:center!important;gap:4px!important;padding:14px 18px!important;font-family:var(--emp-font)!important}
.xcrud-pagination a,.xcrud-page-nav a,.xcrud-page-nav span{display:inline-flex!important;align-items:center!important;justify-content:center!important;min-width:32px!important;height:32px!important;padding:0 8px!important;border:1px solid var(--emp-border)!important;border-radius:6px!important;font-size:13px!important;font-weight:500!important;color:var(--emp-text)!important;background:#fff!important;text-decoration:none!important;transition:all .15s ease!important;font-family:var(--emp-font)!important}
.xcrud-pagination a:hover,.xcrud-page-nav a:hover{border-color:var(--emp-primary)!important;color:var(--emp-primary)!important}
.xcrud-pagination a.xcrud-page-active,.xcrud-page-nav .active,.xcrud-page-nav a.active{background:var(--emp-primary)!important;border-color:var(--emp-primary)!important;color:#fff!important}

/* Search */
.xcrud-search input,input.xcrud-search{font-family:var(--emp-font)!important;padding:8px 14px!important;border:1.5px solid var(--emp-border)!important;border-radius:8px!important;font-size:13px!important;background:#FAFBFC!important;transition:all .2s!important;min-width:250px!important}
.xcrud-search input:focus,input.xcrud-search:focus{border-color:var(--emp-primary)!important;box-shadow:0 0 0 3px rgba(42,171,179,.1)!important;outline:none!important}

/* Misc */
.xcrud-overlay{background:rgba(255,255,255,.85)!important;backdrop-filter:blur(2px)!important}
.xcrud-top-actions,.xcrud-top{padding:16px 18px!important;display:flex!important;align-items:center!important;flex-wrap:wrap!important;gap:10px!important;border-bottom:1px solid #F0F2F5!important}
table.xcrud-list tfoot td,table.xcrud-list tr.xcrud-sum td{font-weight:700!important;background:#F0FDFE!important;color:var(--emp-primary-dark)!important;border-top:2px solid var(--emp-primary)!important;font-family:var(--emp-font)!important}
.xcrud-error{background:#FFF2F0!important;border:1px solid #FFCCC7!important;color:var(--emp-danger)!important;font-family:var(--emp-font)!important;font-size:12.5px!important;padding:10px 16px!important;border-radius:6px!important}
.xcrud-success{background:#F6FFED!important;border:1px solid #B7EB8F!important;color:var(--emp-success)!important}
.xcrud-img,img.xcrud-img{border-radius:8px!important;box-shadow:0 2px 8px rgba(0,0,0,.08)!important;border:2px solid #fff!important}
.xcrud-upload,.xcrud-file-upload{border:2px dashed var(--emp-border)!important;border-radius:8px!important;padding:16px!important;background:#FAFBFC!important;transition:all .2s!important}
.xcrud-upload:hover,.xcrud-file-upload:hover{border-color:var(--emp-primary)!important;background:var(--emp-primary-light)!important}
.xcrud-benchmark{font-family:var(--emp-font)!important;font-size:11px!important;color:#9CA3AF!important;padding:8px 16px!important}
.xcrud-limit select{font-family:var(--emp-font)!important;padding:6px 10px!important;border:1px solid var(--emp-border)!important;border-radius:6px!important;font-size:12px!important;background:#fff!important}
.tab-content>.tab-pane{padding:20px 4px!important}
.xcrud-modal{border-radius:12px!important;box-shadow:0 12px 48px rgba(0,0,0,.15)!important;font-family:var(--emp-font)!important}
.xcrud-body::-webkit-scrollbar{width:6px;height:6px}.xcrud-body::-webkit-scrollbar-track{background:#F3F4F6;border-radius:3px}.xcrud-body::-webkit-scrollbar-thumb{background:#CBD5E1;border-radius:3px}.xcrud-body::-webkit-scrollbar-thumb:hover{background:#94A3B8}
@media(max-width:768px){.emp-hdr{margin:10px 12px 14px;padding:22px 20px}.emp-hdr h1{font-size:18px}.emp-wrap{padding:0 12px 16px}.xcrud-nav li a,.xcrud-nav a{padding:8px 12px!important;font-size:12px!important}table.xcrud-list thead th{font-size:10px!important;padding:10px 8px!important}table.xcrud-list tbody td{padding:9px 8px!important;font-size:12px!important}}
</style>

<div class="emp-hdr">
  <h1><i class="fas fa-users" style="margin-right:10px;opacity:.8"></i>Employee Master Details</h1>
  <p>Manage employee records, leave, payroll, training, certifications & more</p>
  <div class="bc"><a href="index.php"><i class="fas fa-home"></i> Dashboard</a><span>›</span><span>HRMS</span><span>›</span><span>Employee Master</span></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<style>
/* Dashboard Styles */
.dash-grid{display:grid;gap:16px;margin-bottom:24px}
.dash-grid-4{grid-template-columns:repeat(4,1fr)}
.dash-grid-3{grid-template-columns:repeat(3,1fr)}
.dash-grid-2{grid-template-columns:1fr 1fr}

.dash-card{background:#fff;border-radius:12px;border:1px solid var(--emp-border);box-shadow:var(--emp-shadow);overflow:hidden;transition:all .2s ease}
.dash-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.07);transform:translateY(-1px)}
.dash-card-body{padding:20px}
.dash-card-title{font-family:var(--emp-font);font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--emp-text-sec);margin:0 0 12px;display:flex;align-items:center;gap:8px}
.dash-card-title i{font-size:14px;opacity:.6}
.dash-card-title .badge-count{margin-left:auto;padding:2px 10px;border-radius:10px;font-size:11px}

/* KPI Cards */
.kpi-card{position:relative;overflow:hidden;padding:22px 24px}
.kpi-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:14px}
.kpi-value{font-family:var(--emp-font);font-size:32px;font-weight:700;line-height:1;margin-bottom:4px}
.kpi-label{font-family:var(--emp-font);font-size:12.5px;color:var(--emp-text-sec);font-weight:500}
.kpi-sub{font-family:var(--emp-font);font-size:11px;color:var(--emp-text-sec);margin-top:6px;opacity:.75}
.kpi-progress{margin-top:10px;height:6px;background:#F3F4F6;border-radius:3px;overflow:hidden}
.kpi-progress-fill{height:100%;border-radius:3px;transition:width .8s ease}

/* Scrollable Panels */
.panel-list{max-height:320px;overflow-y:auto;padding-right:4px}
.panel-list::-webkit-scrollbar{width:4px}.panel-list::-webkit-scrollbar-thumb{background:#D1D5DB;border-radius:2px}
.panel-item{display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:8px;transition:background .15s;border-bottom:1px solid #F3F4F6}
.panel-item:last-child{border-bottom:none}
.panel-item:hover{background:#F0FDFE}
.panel-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid var(--emp-primary-light);flex-shrink:0}
.panel-avatar-ph{width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:600;font-size:14px;flex-shrink:0}
.panel-info{flex:1;min-width:0}
.panel-name{font-weight:600;font-size:13px;color:var(--emp-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.panel-meta{font-size:11px;color:var(--emp-text-sec)}
.panel-tag{font-size:11px;font-weight:600;text-align:right;white-space:nowrap;flex-shrink:0}
.panel-empty{text-align:center;padding:30px;color:var(--emp-text-sec);font-size:13px}

/* Guard tabs */
.guard-tabs{display:flex;gap:0;margin-bottom:12px;border-bottom:2px solid var(--emp-border)}
.guard-tab{padding:8px 16px;font-size:12px;font-weight:600;color:var(--emp-text-sec);cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .2s;font-family:var(--emp-font)}
.guard-tab:hover{color:var(--emp-primary)}
.guard-tab.active{color:var(--emp-primary);border-bottom-color:var(--emp-primary)}
.guard-tab .tab-count{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:20px;border-radius:10px;font-size:10px;margin-left:6px;padding:0 6px}

/* Alerts */
.alert-row{display:flex;align-items:center;gap:14px;padding:14px 16px;border-radius:10px;margin-bottom:8px;transition:all .15s}
.alert-row:hover{transform:translateX(2px)}
.alert-icon{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0}
.alert-info{flex:1}
.alert-title{font-weight:600;font-size:13px;color:var(--emp-text)}
.alert-desc{font-size:11px;color:var(--emp-text-sec)}
.alert-count{font-size:20px;font-weight:700;flex-shrink:0}

/* Milestones */
.milestone-yrs{display:inline-flex;align-items:center;justify-content:center;width:42px;height:28px;border-radius:6px;font-size:11px;font-weight:700;flex-shrink:0}

/* Tenure bars */
.tenure-row{display:flex;align-items:center;gap:10px;margin-bottom:10px}
.tenure-label{font-size:11.5px;font-weight:500;color:var(--emp-text-sec);width:70px;flex-shrink:0;text-align:right}
.tenure-bar-bg{flex:1;height:22px;background:#F3F4F6;border-radius:5px;overflow:hidden}
.tenure-bar-fill{height:100%;border-radius:5px;display:flex;align-items:center;padding-left:8px;font-size:10px;font-weight:600;color:#fff;transition:width .8s ease}
.tenure-count{font-size:12px;font-weight:600;color:var(--emp-text);width:35px;flex-shrink:0}

/* Gender */
.gender-wrap{display:flex;align-items:center;gap:20px}
.gender-chart-box{width:140px;height:140px;flex-shrink:0}
.gender-legend{flex:1}
.gender-row{display:flex;align-items:center;gap:8px;padding:6px 0;font-size:13px;font-weight:500;color:var(--emp-text)}
.gender-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}

/* Charts */
.chart-container{position:relative;width:100%;max-height:280px}
.chart-container canvas{max-height:280px}

/* Toggle */
.dash-toggle{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;cursor:pointer;background:linear-gradient(135deg,#F8FAFB,#F0F2F5);border-radius:12px;border:1px solid var(--emp-border);margin-bottom:20px;transition:all .2s;user-select:none}
.dash-toggle:hover{border-color:var(--emp-primary);background:var(--emp-primary-light)}
.dash-toggle h3{margin:0;font-family:var(--emp-font);font-size:14px;font-weight:600;color:var(--emp-text);display:flex;align-items:center;gap:8px}
.dash-toggle .arrow{font-size:18px;color:var(--emp-text-sec);transition:transform .3s}
.dash-toggle.collapsed .arrow{transform:rotate(-90deg)}
.dash-panel{transition:max-height .5s ease,opacity .3s ease;overflow:hidden;max-height:5000px;opacity:1}
.dash-panel.collapsed{max-height:0;opacity:0;margin-bottom:0}

/* Skeleton loading */
@keyframes shimmer{0%{background-position:-400px 0}100%{background-position:400px 0}}
.skel{background:linear-gradient(90deg,#F3F4F6 25%,#E5E7EB 50%,#F3F4F6 75%);background-size:800px 100%;animation:shimmer 1.5s infinite;border-radius:6px}
.skel-kpi{height:130px;border-radius:12px}
.skel-panel{height:320px;border-radius:12px}
.skel-chart{height:250px;border-radius:12px}

@media(max-width:1200px){.dash-grid-4{grid-template-columns:repeat(2,1fr)}.dash-grid-3{grid-template-columns:1fr 1fr}}
@media(max-width:768px){.dash-grid-4{grid-template-columns:1fr}.dash-grid-3{grid-template-columns:1fr}.dash-grid-2{grid-template-columns:1fr}.gender-wrap{flex-direction:column}}
</style>

<div style="padding:0 20px 4px;font-family:var(--emp-font)">

<!-- Dashboard Toggle -->
<div class="dash-toggle" id="dashToggle" onclick="toggleDashboard()">
    <h3><i class="fas fa-chart-bar" style="color:var(--emp-primary)"></i> HR Analytics Dashboard</h3>
    <span class="arrow">&#9660;</span>
</div>

<div class="dash-panel" id="dashPanel">

    <!-- Skeleton Loading State -->
    <div id="dashSkeleton">
        <div class="dash-grid dash-grid-4" style="margin-bottom:16px">
            <div class="skel skel-kpi"></div><div class="skel skel-kpi"></div><div class="skel skel-kpi"></div><div class="skel skel-kpi"></div>
        </div>
        <div class="dash-grid dash-grid-2" style="margin-bottom:16px">
            <div class="skel skel-panel"></div><div class="skel skel-panel"></div>
        </div>
        <div class="dash-grid dash-grid-3">
            <div class="skel skel-chart"></div><div class="skel skel-chart"></div><div class="skel skel-chart"></div>
        </div>
    </div>

    <!-- Actual Dashboard (hidden until loaded) -->
    <div id="dashContent" style="display:none"></div>

</div>
</div>

<script>
// ═══════════════════════════════════════════
// DASHBOARD TOGGLE (restore state)
// ═══════════════════════════════════════════
function toggleDashboard(){
    var p=document.getElementById('dashPanel'),t=document.getElementById('dashToggle');
    p.classList.toggle('collapsed');t.classList.toggle('collapsed');
    localStorage.setItem('empDashCollapsed',p.classList.contains('collapsed')?'1':'0');
}
(function(){if(localStorage.getItem('empDashCollapsed')==='1'){document.getElementById('dashPanel').classList.add('collapsed');document.getElementById('dashToggle').classList.add('collapsed')}})();

// ═══════════════════════════════════════════
// AJAX LOAD DASHBOARD
// ═══════════════════════════════════════════
(function(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET','employee_dashboard_api.php',true);
    xhr.onload = function(){
        if(xhr.status===200){
            try {
                var d = JSON.parse(xhr.responseText);
                if(d.error){
                    document.getElementById('dashSkeleton').innerHTML='<div style="padding:20px;color:#FF4D4F;font-size:13px"><i class="fas fa-exclamation-triangle"></i> '+d.error+'</div>';
                    return;
                }
                renderDashboard(d);
            } catch(e){
                document.getElementById('dashSkeleton').innerHTML='<div style="padding:20px;color:#FF4D4F;font-size:13px"><i class="fas fa-exclamation-triangle"></i> Dashboard parse error: '+e.message+'<br><small style="color:#999">Response: '+xhr.responseText.substring(0,200)+'</small></div>';
            }
        } else {
            document.getElementById('dashSkeleton').innerHTML='<div style="padding:20px;color:#FF4D4F;font-size:13px"><i class="fas fa-exclamation-triangle"></i> Dashboard HTTP '+xhr.status+'</div>';
        }
    };
    xhr.onerror = function(){
        document.getElementById('dashSkeleton').innerHTML='<div style="padding:20px;color:#FF4D4F;font-size:13px"><i class="fas fa-exclamation-triangle"></i> Dashboard unavailable</div>';
    };
    xhr.send();
})();

// ═══════════════════════════════════════════
// RENDER DASHBOARD
// ═══════════════════════════════════════════
function renderDashboard(d){
    var k = d.kpi, html = '';
    var fnpfColor = (k.fnpf_pct>=90)?'#52C41A':(k.fnpf_pct>=70)?'#FAAD14':'#FF4D4F';
    var fnpfBg = (k.fnpf_pct>=90)?'#F6FFED':'#FFF7E6';
    var fnpfTxt = (k.fnpf_pct>=90)?'#389E0D':(k.fnpf_pct>=70)?'#D48806':'#CF1322';

    // ═══ ROW 1: KPIs ═══
    html += '<div class="dash-grid dash-grid-4">';
    // Active
    html += '<div class="dash-card kpi-card" style="border-left:4px solid #2AABB3">';
    html += '<div class="kpi-icon" style="background:#E6F7F8;color:#2AABB3"><i class="fas fa-users"></i></div>';
    html += '<div class="kpi-value" style="color:#2AABB3">'+int(k.active)+'</div>';
    html += '<div class="kpi-label">Active Employees</div>';
    html += '<div class="kpi-sub">of '+int(k.total)+' total &bull; '+int(k.warnings)+' on warnings</div></div>';
    // FNPF
    html += '<div class="dash-card kpi-card" style="border-left:4px solid '+fnpfColor+'">';
    html += '<div class="kpi-icon" style="background:'+fnpfBg+';color:'+fnpfTxt+'"><i class="fas fa-id-badge"></i></div>';
    html += '<div class="kpi-value" style="color:'+fnpfTxt+'">'+k.fnpf_pct+'%</div>';
    html += '<div class="kpi-label">FNPF Compliance</div>';
    html += '<div class="kpi-sub">'+int(k.fnpf_yes)+' registered &bull; '+int(k.fnpf_no)+' missing</div>';
    html += '<div class="kpi-progress"><div class="kpi-progress-fill" style="width:'+k.fnpf_pct+'%;background:'+fnpfColor+'"></div></div></div>';
    // New Hires
    html += '<div class="dash-card kpi-card" style="border-left:4px solid #52C41A">';
    html += '<div class="kpi-icon" style="background:#F6FFED;color:#52C41A"><i class="fas fa-user-plus"></i></div>';
    html += '<div class="kpi-value" style="color:#389E0D">'+int(k.new_hires)+'</div>';
    html += '<div class="kpi-label">New Hires ('+d.cur_year+')</div>';
    html += '<div class="kpi-sub">'+int(k.exits_yr)+' exits &bull; '+k.turnover+'% turnover</div></div>';
    // Avg Service
    html += '<div class="dash-card kpi-card" style="border-left:4px solid #722ED1">';
    html += '<div class="kpi-icon" style="background:#F9F0FF;color:#722ED1"><i class="fas fa-business-time"></i></div>';
    html += '<div class="kpi-value" style="color:#531DAB">'+(k.avg_service||'—')+'<span style="font-size:16px;font-weight:500"> yrs</span></div>';
    html += '<div class="kpi-label">Avg Service Length</div>';
    html += '<div class="kpi-sub">Avg age: '+(k.avg_age||'—')+' years</div></div>';
    html += '</div>';

    // ═══ ROW 2: Birthdays + Guard Licence ═══
    html += '<div class="dash-grid dash-grid-2">';
    // Birthdays - sort today's birthdays to the top
    d.birthdays.sort(function(a,b){
        var aToday=(parseInt(a.bday)==d.cur_day)?0:1;
        var bToday=(parseInt(b.bday)==d.cur_day)?0:1;
        if(aToday!==bToday) return aToday-bToday;
        return parseInt(a.bday)-parseInt(b.bday);
    });
    html += '<div class="dash-card"><div class="dash-card-body">';
    html += '<div class="dash-card-title"><i class="fas fa-birthday-cake" style="color:#EB2F96"></i> Birthdays in '+d.month_name+' <span class="badge-count" style="background:#FFF0F6;color:#EB2F96">'+d.birthdays.length+'</span></div>';
    if(d.birthdays.length>0){
        html += '<div class="panel-list">';
        for(var i=0;i<d.birthdays.length;i++){
            var b=d.birthdays[i], isToday=(parseInt(b.bday)==d.cur_day);
            var bini=ini(b.first_name,b.last_name);
            html += '<div class="panel-item"'+(isToday?' style="background:#FFFBE6;border:1px solid #FFE58F;border-radius:8px"':'')+'>';
            html += '<div class="panel-avatar-ph" style="background:linear-gradient(135deg,#FCE4EC,#F8BBD0);color:#C2185B">'+bini+'</div>';
            html += '<div class="panel-info"><div class="panel-name">'+esc(s(b.first_name)+' '+s(b.last_name))+'</div>';
            html += '<div class="panel-meta">ID: '+b.employeeid+' &bull; Turning '+(parseInt(b.age)+1)+'</div></div>';
            if(isToday) html += '<div class="panel-tag"><span style="background:#FFF7E6;border:1px solid #FFE58F;border-radius:6px;padding:2px 8px;font-size:10px;font-weight:700;color:#D48806">🎂 TODAY!</span></div>';
            else html += '<div class="panel-tag"><span style="color:#2AABB3;font-weight:600;font-size:12px">'+fmtDate(d.cur_year,b.bday)+'</span></div>';
            html += '</div>';
        }
        html += '</div>';
    } else { html += '<div class="panel-empty"><i class="fas fa-birthday-cake" style="font-size:28px;opacity:.3;display:block;margin-bottom:8px"></i>No birthdays this month</div>'; }
    html += '</div></div>';

    // Guard Licence
    html += '<div class="dash-card"><div class="dash-card-body">';
    html += '<div class="dash-card-title"><i class="fas fa-shield-alt" style="color:#1890FF"></i> Security Guard Licence Status <span class="badge-count" style="background:#E6F7FF;color:#1890FF">'+d.guard_total+' guards</span></div>';
    if(d.guard_total>0){
        html += '<div class="guard-tabs">';
        html += '<div class="guard-tab active" onclick="switchGuardTab(\'lic\',this)"><i class="fas fa-check-circle" style="color:#52C41A;font-size:11px"></i> Licensed <span class="tab-count" style="background:#F6FFED;color:#389E0D">'+d.guard_lic_count+'</span></div>';
        html += '<div class="guard-tab" onclick="switchGuardTab(\'unlic\',this)"><i class="fas fa-exclamation-triangle" style="color:#FF4D4F;font-size:11px"></i> Unlicensed <span class="tab-count" style="background:#FFF2F0;color:#CF1322">'+d.guard_unlic_count+'</span></div>';
        html += '</div>';
        html += guardList(d.guards_licensed,'lic','#E8F5E9','#C8E6C9','#2E7D32','badge-lic','Licensed',true);
        html += guardList(d.guards_unlicensed,'unlic','#FFEBEE','#FFCDD2','#C62828','badge-unlic','No Licence',false);
        var lp=d.guard_lic_pct, lc=(lp>=80)?'#52C41A':(lp>=50)?'#FAAD14':'#FF4D4F';
        html += '<div style="margin-top:12px;padding-top:12px;border-top:1px solid #F3F4F6"><div style="display:flex;justify-content:space-between;font-size:11px;font-weight:600;color:#6B7280;margin-bottom:4px"><span>Licence Compliance</span><span>'+lp+'%</span></div>';
        html += '<div class="kpi-progress"><div class="kpi-progress-fill" style="width:'+lp+'%;background:'+lc+'"></div></div></div>';
    } else { html += '<div class="panel-empty"><i class="fas fa-shield-alt" style="font-size:28px;opacity:.3;display:block;margin-bottom:8px"></i>No Security Officers/Supervisors found</div>'; }
    html += '</div></div></div>';

    // ═══ ROW 3: Dept Chart + Gender + Employment Type ═══
    html += '<div class="dash-grid dash-grid-3">';
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-building" style="color:#1890FF"></i> Department Headcount</div><div class="chart-container"><canvas id="deptChart"></canvas></div></div></div>';
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-venus-mars" style="color:#13C2C2"></i> Gender Distribution</div>';
    html += '<div class="gender-wrap"><div class="gender-chart-box"><canvas id="genderChart"></canvas></div>';
    html += '<div class="gender-legend"><div class="gender-row"><span class="gender-dot" style="background:#1890FF"></span> Male: <strong>'+int(k.male)+'</strong> <span style="color:#6B7280;font-size:11px">('+k.male_pct+'%)</span></div>';
    html += '<div class="gender-row"><span class="gender-dot" style="background:#EB2F96"></span> Female: <strong>'+int(k.female)+'</strong> <span style="color:#6B7280;font-size:11px">('+k.female_pct+'%)</span></div></div></div>';
    html += '</div></div>';
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-briefcase" style="color:#FA8C16"></i> Employment Type</div><div class="chart-container" style="max-height:200px"><canvas id="empTypeChart"></canvas></div></div></div>';
    html += '</div>';

    // ═══ ROW 4: Recent Hires + Staff Alerts + Long Service ═══
    html += '<div class="dash-grid dash-grid-3">';

    // Recent Hires
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-user-plus" style="color:#52C41A"></i> Recent Hires <span class="badge-count" style="background:#F6FFED;color:#389E0D">'+d.recent_hires.length+'</span></div><div class="panel-list">';
    for(var i=0;i<d.recent_hires.length;i++){
        var rh=d.recent_hires[i], ri=ini(rh.first_name,rh.last_name);
        var da=parseInt(rh.days_ago);
        html += '<div class="panel-item"><div class="panel-avatar-ph" style="background:linear-gradient(135deg,#E8F5E9,#A5D6A7);color:#2E7D32">'+ri+'</div>';
        html += '<div class="panel-info"><div class="panel-name">'+esc(s(rh.first_name)+' '+s(rh.last_name))+'</div><div class="panel-meta">'+esc(s(rh.dept))+' &bull; '+esc(s(rh.job_role))+'</div></div>';
        html += '<div class="panel-tag"><div style="font-size:12px;font-weight:600;color:#2AABB3">'+fmtStartDate(rh.start_date)+'</div><div style="font-size:10px;color:#6B7280">'+(da<=90?da+'d ago':s(rh.start_date).substring(0,4))+'</div></div></div>';
    }
    html += '</div></div></div>';

    // Staff Alerts
    var alertDefs = [
        {f:'no_tin',icon:'fas fa-file-alt',label:'Missing TIN',desc:'No Tax ID Number',bg:'#FFF7E6',ic:'#D48806'},
        {f:'no_fnpf',icon:'fas fa-id-badge',label:'Missing FNPF',desc:'No FNPF number',bg:'#FFF2F0',ic:'#CF1322'},
        {f:'no_email',icon:'fas fa-envelope',label:'Missing Email',desc:'No email address',bg:'#F0F5FF',ic:'#2F54EB'},
        {f:'no_photo',icon:'fas fa-camera',label:'No Photo',desc:'Photo not uploaded',bg:'#F9F0FF',ic:'#722ED1'},
        {f:'no_mobile',icon:'fas fa-mobile-alt',label:'Missing Mobile',desc:'No mobile number',bg:'#E6FFFB',ic:'#13C2C2'},
        {f:'no_dob',icon:'fas fa-calendar',label:'Missing DOB',desc:'No date of birth',bg:'#FFF0F6',ic:'#EB2F96'},
        {f:'no_emergency',icon:'fas fa-phone-alt',label:'No Emergency Contact',desc:'Emergency contact missing',bg:'#FFF1F0',ic:'#F5222D'}
    ];
    var totalAlerts=0; for(var i=0;i<alertDefs.length;i++) totalAlerts+=int(k[alertDefs[i].f]);
    var abg=totalAlerts>0?'#FFF2F0':'#F6FFED', ac=totalAlerts>0?'#CF1322':'#389E0D';
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-exclamation-circle" style="color:#FF4D4F"></i> Data Completeness Alerts <span class="badge-count" style="background:'+abg+';color:'+ac+'">'+totalAlerts+'</span></div>';
    if(totalAlerts>0){
        for(var i=0;i<alertDefs.length;i++){
            var a=alertDefs[i], cnt=int(k[a.f]);
            if(cnt===0) continue;
            html += '<div class="alert-row" style="background:'+a.bg+'"><div class="alert-icon" style="background:rgba(255,255,255,.7);color:'+a.ic+'"><i class="'+a.icon+'"></i></div>';
            html += '<div class="alert-info"><div class="alert-title">'+a.label+'</div><div class="alert-desc">'+a.desc+'</div></div>';
            html += '<div class="alert-count" style="color:'+a.ic+'">'+cnt+'</div></div>';
        }
    } else { html += '<div class="panel-empty" style="color:#52C41A"><i class="fas fa-check-circle" style="font-size:28px;display:block;margin-bottom:8px"></i>All employee data is complete!</div>'; }
    html += '</div></div>';

    // Long Service Milestones
    var msColors={5:{bg:'#E6F7FF',c:'#1890FF'},10:{bg:'#F6FFED',c:'#52C41A'},15:{bg:'#FFF7E6',c:'#FAAD14'},20:{bg:'#FFF0F6',c:'#EB2F96'},25:{bg:'#F9F0FF',c:'#722ED1'},30:{bg:'#FFF1F0',c:'#F5222D'}};
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-award" style="color:#FAAD14"></i> Service Milestones ('+d.cur_year+') <span class="badge-count" style="background:#FFF7E6;color:#D48806">'+d.milestones.length+'</span></div>';
    if(d.milestones.length>0){
        html += '<div class="panel-list">';
        for(var i=0;i<d.milestones.length;i++){
            var ms=d.milestones[i], mi=ini(ms.first_name,ms.last_name);
            var yrs=parseInt(ms.yrs), mc=msColors[yrs]||{bg:'#F3F4F6',c:'#6B7280'};
            html += '<div class="panel-item"><div class="panel-avatar-ph" style="background:'+mc.bg+';color:'+mc.c+'">'+mi+'</div>';
            html += '<div class="panel-info"><div class="panel-name">'+esc(s(ms.first_name)+' '+s(ms.last_name))+'</div><div class="panel-meta">'+esc(s(ms.job_role))+' &bull; Since '+s(ms.start_date).substring(0,7)+'</div></div>';
            html += '<div class="milestone-yrs" style="background:'+mc.bg+';color:'+mc.c+'"><i class="fas fa-trophy" style="font-size:10px;margin-right:3px"></i>'+yrs+'y</div></div>';
        }
        html += '</div>';
    } else { html += '<div class="panel-empty"><i class="fas fa-award" style="font-size:28px;opacity:.3;display:block;margin-bottom:8px"></i>No milestones this year</div>'; }
    html += '</div></div></div>';

    // ═══ ROW 5: Tenure + Location ═══
    html += '<div class="dash-grid dash-grid-2">';
    // Tenure
    var tenureLabels=['< 1 yr','1–3 yrs','3–5 yrs','5–10 yrs','10+ yrs'];
    var tenureColors=['#BAE7FF','#69C0FF','#1890FF','#0050B3','#002766'];
    var tenureKeys=['under1','1to3','3to5','5to10','over10'];
    var tenureMax=1; for(var i=0;i<tenureKeys.length;i++) tenureMax=Math.max(tenureMax,d.tenure[tenureKeys[i]]||0);
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-hourglass-half" style="color:#722ED1"></i> Tenure Distribution</div>';
    for(var i=0;i<tenureKeys.length;i++){
        var tv=d.tenure[tenureKeys[i]]||0, pct=Math.round((tv/tenureMax)*100);
        html += '<div class="tenure-row"><div class="tenure-label">'+tenureLabels[i]+'</div><div class="tenure-bar-bg"><div class="tenure-bar-fill" style="width:'+pct+'%;background:'+tenureColors[i]+'">'+(pct>15?tv:'')+'</div></div><div class="tenure-count">'+tv+'</div></div>';
    }
    html += '</div></div>';
    // Location
    html += '<div class="dash-card"><div class="dash-card-body"><div class="dash-card-title"><i class="fas fa-map-marker-alt" style="color:#F5222D"></i> Staff Location (Suburb)</div><div class="chart-container"><canvas id="locChart"></canvas></div></div></div>';
    html += '</div>';

    // Inject & show
    document.getElementById('dashContent').innerHTML = html;
    document.getElementById('dashSkeleton').style.display = 'none';
    document.getElementById('dashContent').style.display = 'block';

    // Init Charts
    initCharts(d);
}

// ═══════════════════════════════════════════
// CHART INIT
// ═══════════════════════════════════════════
function initCharts(d){
    Chart.defaults.font.family="'Poppins',-apple-system,sans-serif";
    Chart.defaults.font.size=11;
    Chart.defaults.color='#6B7280';
    var ttOpts={backgroundColor:'#1F2937',padding:10,cornerRadius:8};

    new Chart(document.getElementById('deptChart'),{type:'bar',data:{labels:d.departments.map(function(x){return x.name}),datasets:[{data:d.departments.map(function(x){return parseInt(x.cnt)}),backgroundColor:'rgba(42,171,179,0.75)',borderColor:'#2AABB3',borderWidth:1,borderRadius:4,barThickness:20}]},options:{indexAxis:'y',responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:ttOpts},scales:{x:{grid:{color:'#F3F4F6'},ticks:{stepSize:1}},y:{grid:{display:false},ticks:{font:{size:11,weight:'500'}}}}}});

    new Chart(document.getElementById('genderChart'),{type:'doughnut',data:{labels:['Male','Female'],datasets:[{data:[int(d.kpi.male),int(d.kpi.female)],backgroundColor:['#1890FF','#EB2F96'],borderWidth:0,cutout:'70%'}]},options:{responsive:true,maintainAspectRatio:true,plugins:{legend:{display:false},tooltip:ttOpts}}});

    new Chart(document.getElementById('empTypeChart'),{type:'doughnut',data:{labels:d.emp_types.map(function(x){return x.jtype}),datasets:[{data:d.emp_types.map(function(x){return parseInt(x.cnt)}),backgroundColor:['#2AABB3','#FA8C16','#722ED1','#8C8C8C'],borderWidth:0,cutout:'55%'}]},options:{responsive:true,maintainAspectRatio:true,plugins:{legend:{position:'bottom',labels:{padding:12,usePointStyle:true,pointStyle:'circle',font:{size:11,weight:'500'}}},tooltip:ttOpts}}});

    new Chart(document.getElementById('locChart'),{type:'bar',data:{labels:d.locations.map(function(x){return x.name}),datasets:[{data:d.locations.map(function(x){return parseInt(x.cnt)}),backgroundColor:['#FF6B6B','#FFA94D','#FFD43B','#69DB7C','#38D9A9','#4DABF7','#748FFC','#DA77F2'],borderRadius:6,barThickness:28}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:ttOpts},scales:{x:{grid:{display:false},ticks:{font:{size:10.5,weight:'500'}}},y:{grid:{color:'#F3F4F6'},ticks:{stepSize:1}}}}});
}

// ═══════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════
function int(v){return parseInt(v)||0}
function esc(s){if(!s)return'';var d=document.createElement('div');d.textContent=String(s);return d.innerHTML}
function s(v){return(v==null)?'':String(v)}
function ini(f,l){f=s(f);l=s(l);return(f.charAt(0)||'?').toUpperCase()+(l.charAt(0)||'').toUpperCase()}
function fmtDate(yr,day){var m=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];return m[new Date().getMonth()]+' '+parseInt(day)}
function fmtStartDate(ds){if(!ds)return'';var p=String(ds).split('-');var m=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];return m[parseInt(p[1])-1]+' '+parseInt(p[2])}

function guardList(arr,id,bg1,bg2,txtC,badgeCls,badgeTxt,show){
    var h='<div class="panel-list" id="guardList_'+id+'" style="display:'+(show?'block':'none')+'">';
    if(arr.length>0){
        for(var i=0;i<arr.length;i++){
            var g=arr[i],gi=ini(g.first_name,g.last_name);
            var isBadge=badgeTxt==='Licensed';
            h+='<div class="panel-item"><div class="panel-avatar-ph" style="background:linear-gradient(135deg,'+bg1+','+bg2+');color:'+txtC+'">'+gi+'</div>';
            h+='<div class="panel-info"><div class="panel-name">'+esc(s(g.first_name)+' '+s(g.last_name))+'</div>';
            h+='<div class="panel-meta">'+esc(s(g.job_role))+(isBadge?' &bull; Lic: '+esc(s(g.security_licence)):' &bull; ID: '+g.employeeid)+'</div></div>';
            if(isBadge) h+='<span style="background:#F6FFED;color:#389E0D;border:1px solid #B7EB8F;padding:3px 10px;border-radius:10px;font-size:10.5px;font-weight:600"><i class="fas fa-check" style="margin-right:3px"></i>Licensed</span>';
            else h+='<span style="background:#FFF2F0;color:#CF1322;border:1px solid #FFCCC7;padding:3px 10px;border-radius:10px;font-size:10.5px;font-weight:600"><i class="fas fa-times" style="margin-right:3px"></i>No Licence</span>';
            h+='</div>';
        }
    } else {
        h+='<div class="panel-empty">'+(isBadge?'No licensed guards':'All guards are licensed! 🎉')+'</div>';
    }
    h+='</div>';
    return h;
}

function switchGuardTab(tab,el){
    var tabs=document.querySelectorAll('.guard-tab');
    for(var i=0;i<tabs.length;i++) tabs[i].classList.remove('active');
    el.classList.add('active');
    document.getElementById('guardList_lic').style.display=(tab==='lic')?'block':'none';
    document.getElementById('guardList_unlic').style.display=(tab==='unlic')?'block':'none';
}
</script>
<div class="emp-wrap">
<?php
echo '<div class="col-sm-12">';

// ═══════════════════════════════════════════
// ADMIN USERS — admin, pchand, sharukh, mkhan
// Full access to all fields, tabs, nested tables
// ═══════════════════════════════════════════
if ($userid == 'admin' || $userid == 'pchand' || $userid == 'sharukh' || $userid == 'mkhan') { 
    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
	$xcrud->table('employeemaster');
	$xcrud->table_name('Employee Master Details');
	Xcrud_config::$editor_url = dirname($_SERVER["SCRIPT_NAME"]).'/editors/ckeditor/ckeditor.js'; 
	
	$xcrud->columns('employeeid,first_name,middle_name,last_name,tin,fnpf,department,job_role,email_address,status,log');
	$xcrud->unset_remove();
		
    $xcrud->fields('employeeid,management,tin,fnpfmember,fnpf_member,fnpf,jointcard,security_licence,union_member,first_name,middle_name,last_name,fnpf_firstname,fnpf_othernames,photo,date_of_birth,age,gender,department,status,log', false, 'Basic Profile');
	$xcrud->fields('fathers_name,height,weight,marital,spouse,children,spouse_occupation,transport_mode', false, 'Personal Details');
	$xcrud->fields('mob,ph,street,suburb,postal,email_address', false, 'Contact & Address');
	$xcrud->fields('emergency_contact,emergency_number', false, 'Emergency Contact Details');
    $xcrud->fields('start_date,years_service,employment_type,contract,job_role,system_role,job_type,agreement,previous_employer,previous_employers_tin', false, 'Employement details');
    $xcrud->fields('qualifications,certifications,otherskills,tertiary,high_school', false, 'Education');
    $xcrud->fields('smoker,health_report', false, 'Health');
    $xcrud->fields('sick_leave_available,annual_leave_available,bereavement_leave_available,familycare_leave_available,paternity_leave_available,maternity_leave_available,ytd_sick_leave,ytd_annual_leave,ytd_bereavement_leave,ytd_familycare_leave,ytd_paternity_leave,ytd_maternity_leave', false, 'Leave Status');
	$xcrud->fields('max_hours_to_work,salary_type,paycycle,cyclevalue, annualsalary,base_wage_rate,ytd_gross,payment_method,bank_code,bank_name,bank_branch,account_number,account_name,second_bankname,second_accountname,second_accountnumber,second_amount', false, 'Payment Details');
	$xcrud->fields('cv,hobbies,remarks', false, 'Miscellaneous');
	$xcrud->fields('non_resident,completed_pay_period,annual_income_plus_bonus,ytd_income_tax_withheld,ytd_srt_tax_withheld,ytd_ecal_tax_withheld',false,'Tax Details');
	$xcrud->fields('fnpf_deducted_till_date',false,'FNPF Details');
	$xcrud->fields('current_sites,other_approved_sites,termination_date,incremental_date', false, 'Patrol Location Data');
	$xcrud->relation('department','department','departmentid','departmentname');
	  
	$xcrud->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
	$xcrud->change_type('agreement', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('cv', 'file', '', array('not_rename'=>true));
	$xcrud->validation_pattern('email_address', 'email');
	$xcrud->change_type('status','select','Active','Active,On Leave,trainee,attachee,Final Warning,Terminated,InActive');
	$xcrud->change_type('marital','select','Married','Married,Separated,Partner,Single,Divorcee,Widower,Widow');
	$xcrud->change_type('transport_mode','select','Public Transportation','Public Transportation,Own Transport,Walk,Bicycle');
	$xcrud->change_type('suburb','select','Suva','Nausori,Suva,Lami,Navua,Pacific Harbour,Sigatoka, Nadroga,Nadi,Lautoka,Ba,Tavua,Rakiraki,Tailevu,Labasa,Savusavu,Levuka');
	$xcrud->change_type('employment_type','select','Primary','Primary,Secondary');
	$xcrud->change_type('salary_type','select','Fixed','Fixed,Varies');
	$xcrud->change_type('job_type','select','Full-Time','Full-time,Part-Time,Casual');
	$xcrud->change_type('gender','select','Male','Male,Female, Others');
	$xcrud->change_type('payment_method','select','Transfer to Bank','Transfer to Bank,Cash,cheque');
	$xcrud->change_type('bank_name','select','No Bank Yet','No Bank Yet,Westpac,BRED,ANZ,HFC,BOB, BSP');
	$xcrud->relation('paycycle','paycycle','paycycleid','name');
	$xcrud->relation('cyclevalue','paycycle','paycycleid','frequency','','','',' ','','paycycleid','paycycle');
	$xcrud->label('last_name','Surname');
	$xcrud->column_pattern('employeeid', '<a href="#" class="xcrud-action" data-task="edit" data-primary="{employeeid}">{value}</a>');
	$xcrud->limit_list('20,50,100,1000');
    $xcrud->benchmark();
	$xcrud->label('fnpf_deducted_till_date','YTD FNPF');

	$timenow = date('Y-m-d H:i:s');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$xcrud->pass_default('log',$log);
	$xcrud->pass_var('log',$log);
	$xcrud->before_update('update_log');
	$xcrud->disabled('log');

	// Nested tables
	$leavebreak = $xcrud->nested_table('Leave Breakdown','employeeid','absent','employeeid');
    $leavebreak->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$leavebreak->label('id','calender_id');
	
	$fixeddeductions = $xcrud->nested_table('Fixed Deductions','employeeid','fixeddeductions','employeeid');
	$fixeddeductions->unset_remove();
	$fixeddeductions->order_by('id','desc');
	$fixeddeductions->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
	$fixeddeductions->relation('name','fixed_deduction_codecategory','id',array('name','code'));
	$fixeddeductions->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
	$fixeddeductions->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
	$fixeddeductions->change_type('status','select','pending','pending,completed,cancelled');
	$fixeddeductions->before_insert('fixed_deductions');
	$fixeddeductions->before_update('fixed_deductions');
	$fixeddeductions->set_attr('type',array('id'=>'type'));
	$fixeddeductions->set_attr('allow_upto_75_percent',array('id'=>'allow'));
	$fixeddeductions->relation('department','department','departmentid','departmentname');

	$ebusiness1 = $xcrud->nested_table('Pay Runs/Paysip','employeeid','payrun_details','employeeid');
	$ebusiness1->relation('employeeid','employeemaster','employeeid',array('first_name','middle_name','last_name','employeeid'));
	$ebusiness1->button('PaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Print Payslip','glyphicon glyphicon-download','payslip');
	$ebusiness1->button('EmailPaySlipsIndividualNew.php?payid={payid}&employeeid={employeeid}', 'Email Payslip','glyphicon glyphicon-envelope','payslipemail');
	$ebusiness1->sum('normal_pay,premium,stay_away,normal_hours,timehalf_hours,double_hours,timehalf_amount,double_amount,stay_away,leave_allowances,other_allowances_fnpf,other_allowances_nonfnpf,meal_allowance,employee_fnpf,fnpf_employer,fixed_deductions,net_pay');
	$ebusiness1->relation('department','department','departmentid','departmentname');
	$ebusiness1->unset_remove();

	$training = $xcrud->nested_table('Training Management','employeeid','training','employeeid');
	$training->relation('type','certifications','certificateid','certificationname');
	$training->unset_remove();
	$training->pass_default('log',$log);
	$training->pass_var('log',$log);
	$training->before_update('update_log1');

	$productivity = $xcrud->nested_table('Productivity Measurement','employeeid','productivity','employeeid');
	$productivity->unset_remove();

	$ir = $xcrud->nested_table('Industrial Relations','employeeid','industrial_relations','employeeid');
	$ir->change_type('attachments', 'file', '', array('not_rename'=>true));
	$ir->unset_remove();
	$ir->pass_default('log',$log);
	$ir->pass_var('log',$log);
	$ir->before_update('update_log2');

	$certification = $xcrud->nested_table('Certifications','employeeid','certificates','employeeid');
	$certification->relation('certificate','certifications','certificateid','certificationname');
	$certification->change_type('attachments', 'file', '', array('not_rename'=>true));
	$certification->unset_remove();
	$certification->pass_var('entered_date',$timenow);
	$certification->pass_var('entered_by',$userid);
	$certification->disabled('entered_date,entered_by,log');
	$certification->pass_default('log',$log);
	$certification->pass_var('log',$log);
	$certification->before_update('update_log3');

	$ir->pass_var('entered_date',$timenow);
	$ir->pass_var('entered_by',$userid);
	$ir->disabled('entered_date,entered_by,log');

	$training->pass_var('entered_date',$timenow);
	$training->pass_var('entered_by',$userid);
	$training->disabled('entered_date,entered_by');
	$training->change_type('status','select','Scheduled','Scheduled,Underprogress,Completed,Cancelled');

	$productivity->pass_var('entered_date',$timenow);
	$productivity->pass_var('entered_by',$userid);
	$productivity->disabled('entered_date,entered_by,log');
	$productivity->pass_default('log',$log);
	$productivity->pass_var('log',$log);
	$productivity->before_update('update_log4');

	$uniform = $xcrud->nested_table('Uniform','employeeid','stockrequest','employee');
	$uniform->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$uniform->relation('employee','employeemaster','employeeid',array('first_name','last_name','employeeid'));
	$uniform->relation('client','debtorsmaster','debtorno','name');
	$uniform->relation('jobno','projectdetails','projectid',array('projectid','project_name'));
	$uniform->order_by('dispatchid','desc');
	$uniform->unset_remove();
	$uniform->unset_add();
	$uniform->unset_edit();
	$uniform->label('dispatchid','Request No');
	$uniform->label('closed','Completed');
	$uniform->label('despatchdate','Date');
	$uniform->button('StockRequestPrint.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}', 'Print Request','glyphicon glyphicon-download-alt');
	$uniform->column_pattern('dispatchid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{dispatchid}">{value}</a>');
	$stockrequestdetails = $uniform->nested_table('Stock Request Details','dispatchid','stockrequestitems','dispatchid');
	$stockrequestdetails->unset_remove();
	$stockrequestdetails->unset_add();
	$stockrequestdetails->unset_edit();

	$vaccination = $xcrud->nested_table('vaccination','employeeid','vaccination','employeeid');
	$vaccination->change_type('type','select','jab1','jab1,jab2');
	$vaccination->change_type('card_image', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement1', 'file', '', array('not_rename'=>true));
	$vaccination->unset_remove();
	$vaccination->pass_default('log',$log);
	$vaccination->pass_var('log',$log);
	$vaccination->before_update('update_log5');
	$vaccination->disabled('log');

    echo $xcrud->render();
}
// ═══════════════════════════════════════════
// HR USERS — walesi, amelia, businessanalyst, ranjeeta
// Edit access but no management employees, no salary fields
// ═══════════════════════════════════════════
elseif ($userid == 'walesi' || $userid == 'amelia' || $userid =='businessanalyst' || $userid == 'ranjeeta') { 
    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
	$xcrud->table('employeemaster');
	$xcrud->table_name('Employee Master Details');
	Xcrud_config::$editor_url = dirname($_SERVER["SCRIPT_NAME"]).'/editors/ckeditor/ckeditor.js'; 
	$xcrud->where('management=',0);
	$xcrud->disabled('log');
	$xcrud->columns('employeeid,first_name,middle_name,last_name,tin,fnpf,department,job_role,email_address,status,log');
	$xcrud->unset_remove();
    $xcrud->fields('employeeid,management,tin,fnpfmember,fnpf_member,fnpf,jointcard,security_licence,union_member,first_name,middle_name,last_name,fnpf_firstname,fnpf_othernames,photo,date_of_birth,gender,department,status,log', false, 'Basic Profile');
	$xcrud->fields('fathers_name,height,weight,marital,spouse,children,spouse_occupation,transport_mode', false, 'Personal Details');
	$xcrud->fields('mob,ph,street,suburb,postal,email_address', false, 'Contact & Address');
	$xcrud->fields('emergency_contact,emergency_number', false, 'Emergency Contact Details');
    $xcrud->fields('start_date,years_service,employment_type,contract,job_role,system_role,job_type,agreement,previous_employer,previous_employers_tin', false, 'Employement details');
    $xcrud->fields('qualifications,certifications,otherskills,tertiary,high_school', false, 'Education');
    $xcrud->fields('smoker,health_report', false, 'Health');
    $xcrud->fields('sick_leave_available,annual_leave_available,bereavement_leave_available,familycare_leave_available,paternity_leave_available,maternity_leave_available,ytd_sick_leave,ytd_annual_leave,ytd_bereavement_leave,ytd_familycare_leave,ytd_paternity_leave,ytd_maternity_leave', false, 'Leave Status');
	$xcrud->fields('max_hours_to_work,payment_method,bank_code,bank_name,bank_branch,account_number,account_name', false, 'Payment Details');
	$xcrud->fields('cv,hobbies,remarks', false, 'Miscellaneous');
	$xcrud->fields('current_sites,other_approved_sites,termination_date,incremental_date', false, 'Patrol Location Data');
	$xcrud->relation('department','department','departmentid','departmentname');
	$xcrud->validation_pattern('email_address', 'email');
	$xcrud->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
	$xcrud->change_type('agreement', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('cv', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('status','select','Active','Active,On Leave,trainee,attachee,Final Warning,Terminated,InActive');
	$xcrud->change_type('marital','select','Married','Married,Separated,Partner,Single,Divorcee,Widower,Widow');
	$xcrud->change_type('transport_mode','select','Public Transportation','Public Transportation,Own Transport,Walk,Bicycle');
	$xcrud->change_type('suburb','select','Suva','Nausori,Suva,Lami,Navua,Pacific Harbour,Sigatoka, Nadroga,Nadi,Lautoka,Ba,Tavua,Rakiraki,Tailevu,Labasa,Savusavu,Levuka');
	$xcrud->change_type('employment_type','select','Primary','Primary,Secondary');
	$xcrud->change_type('salary_type','select','Fixed','Fixed,Varies');
	$xcrud->change_type('job_type','select','Full-Time','Full-time,Part-Time,Casual');
	$xcrud->change_type('gender','select','Male','Male,Female, Others');
	$xcrud->change_type('payment_method','select','Transfer to Bank','Transfer to Bank,Cash,cheque');
	$xcrud->change_type('bank_name','select','No Bank Yet','No Bank Yet,Westpac,BRED,ANZ,HFC,BOB, BSP');
	$xcrud->relation('paycycle','paycycle','paycycleid','name');
	$xcrud->relation('cyclevalue','paycycle','paycycleid','frequency','','','',' ','','paycycleid','paycycle');
	$xcrud->label('last_name','Surname');
	$xcrud->column_pattern('employeeid', '<a href="#" class="xcrud-action" data-task="edit" data-primary="{employeeid}">{value}</a>');
	$xcrud->limit_list('20,50,100,1000');
    $xcrud->benchmark();
	$xcrud->label('fnpf_deducted_till_date','YTD FNPF');
	$xcrud->unset_remove();

	$timenow = date('Y-m-d H:i:s');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$xcrud->pass_default('log',$log);
	$xcrud->pass_var('log',$log);
	$xcrud->before_update('update_log');
	$xcrud->disabled('log');

	$leavebreak = $xcrud->nested_table('Leave Breakdown','employeeid','absent','employeeid');
    $leavebreak->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$leavebreak->label('id','calender_id');
	$fixeddeductions = $xcrud->nested_table('Fixed Deductions','employeeid','fixeddeductions','employeeid');
	$fixeddeductions->unset_remove();
	$fixeddeductions->order_by('id','desc');
	$fixeddeductions->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
	$fixeddeductions->relation('name','fixed_deduction_codecategory','id',array('name','code'));
	$fixeddeductions->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
	$fixeddeductions->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
	$fixeddeductions->change_type('status','select','pending','pending,completed,cancelled');
	$fixeddeductions->before_insert('fixed_deductions');
	$fixeddeductions->before_update('fixed_deductions');
	$fixeddeductions->set_attr('type',array('id'=>'type'));
	$fixeddeductions->set_attr('allow_upto_75_percent',array('id'=>'allow'));
	$fixeddeductions->relation('department','department','departmentid','departmentname');

	$ebusiness1 = $xcrud->nested_table('Pay Runs/Paysip','employeeid','payrun_details','employeeid');
	$ebusiness1->relation('employeeid','employeemaster','employeeid',array('first_name','middle_name','last_name','employeeid'));
	$ebusiness1->button('PaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Print Payslip','glyphicon glyphicon-download','payslip');
	$ebusiness1->button('EmailPaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Email Payslip','glyphicon glyphicon-envelope','payslipemail');
	$ebusiness1->sum('normal_pay,premium,stay_away,normal_hours,timehalf_hours,double_hours,timehalf_amount,double_amount,stay_away,leave_allowances,other_allowances_fnpf,other_allowances_nonfnpf,meal_allowance,employee_fnpf,fnpf_employer,fixed_deductions,net_pay');
	$ebusiness1->relation('department','department','departmentid','departmentname');
	$ebusiness1->unset_remove();

	$training = $xcrud->nested_table('Training Management','employeeid','training','employeeid');
	$training->relation('type','certifications','certificateid','certificationname');
	$training->unset_remove();
	$training->pass_default('log',$log);
	$training->pass_var('log',$log);
	$training->before_update('update_log1');

	$productivity = $xcrud->nested_table('Productivity Measurement','employeeid','productivity','employeeid');
	$productivity->unset_remove();

	$ir = $xcrud->nested_table('Industrial Relations','employeeid','industrial_relations','employeeid');
	$ir->change_type('attachments', 'file', '', array('not_rename'=>true));
	$ir->unset_remove();
	$ir->pass_default('log',$log);
	$ir->pass_var('log',$log);
	$ir->before_update('update_log2');

	$certification = $xcrud->nested_table('Certifications','employeeid','certificates','employeeid');
	$certification->relation('certificate','certifications','certificateid','certificationname');
	$certification->change_type('attachments', 'file', '', array('not_rename'=>true));
	$certification->unset_remove();
	$certification->pass_var('entered_date',$timenow);
	$certification->pass_var('entered_by',$userid);
	$certification->disabled('entered_date,entered_by,log');
	$certification->pass_default('log',$log);
	$certification->pass_var('log',$log);
	$certification->before_update('update_log3');
	$ir->pass_var('entered_date',$timenow);
	$ir->pass_var('entered_by',$userid);
	$ir->disabled('entered_date,entered_by,log');
	$training->pass_var('entered_date',$timenow);
	$training->pass_var('entered_by',$userid);
	$training->disabled('entered_date,entered_by');
	$training->change_type('status','select','Scheduled','Scheduled,Underprogress,Completed,Cancelled');
	$productivity->pass_var('entered_date',$timenow);
	$productivity->pass_var('entered_by',$userid);
	$productivity->disabled('entered_date,entered_by,log');
	$productivity->pass_default('log',$log);
	$productivity->pass_var('log',$log);
	$productivity->before_update('update_log4');

	$uniform = $xcrud->nested_table('Uniform','employeeid','stockrequest','employee');
	$uniform->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$uniform->relation('employee','employeemaster','employeeid',array('first_name','last_name','employeeid'));
	$uniform->relation('client','debtorsmaster','debtorno','name');
	$uniform->relation('jobno','projectdetails','projectid',array('projectid','project_name'));
	$uniform->order_by('dispatchid','desc');
	$uniform->unset_remove();
	$uniform->unset_add();
	$uniform->unset_edit();
	$uniform->label('dispatchid','Request No');
	$uniform->label('closed','Completed');
	$uniform->label('despatchdate','Date');
	$uniform->button('StockRequestPrint.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}', 'Print Request','glyphicon glyphicon-download-alt');
	$uniform->column_pattern('dispatchid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{dispatchid}">{value}</a>');
	$stockrequestdetails = $uniform->nested_table('Stock Request Details','dispatchid','stockrequestitems','dispatchid');
	$stockrequestdetails->unset_remove();
	$stockrequestdetails->unset_add();
	$stockrequestdetails->unset_edit();

	$vaccination = $xcrud->nested_table('vaccination','employeeid','vaccination','employeeid');
	$vaccination->change_type('type','select','jab1','jab1,jab2');
	$vaccination->change_type('card_image', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement1', 'file', '', array('not_rename'=>true));
	$vaccination->unset_remove();
	$vaccination->pass_default('log',$log);
	$vaccination->pass_var('log',$log);
	$vaccination->before_update('update_log5');
	$vaccination->disabled('log');

    echo $xcrud->render();
}
// ═══════════════════════════════════════════
// VIEW-ONLY USERS — waisake, lani, duta, elina
// No add/edit/remove, view all nested tables
// ═══════════════════════════════════════════
elseif ($userid == 'waisake' || $userid == 'lani' || $userid == 'duta' || $userid == 'elina') { 
    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
	$xcrud->table('employeemaster');
	$xcrud->table_name('Employee Master Details');
	Xcrud_config::$editor_url = dirname($_SERVER["SCRIPT_NAME"]).'/editors/ckeditor/ckeditor.js'; 
	$xcrud->where('management=',0);
	$xcrud->disabled('log');
	$xcrud->columns('employeeid,first_name,middle_name,last_name,tin,fnpf,department,job_role,email_address,status,log');
	$xcrud->unset_remove();
    $xcrud->fields('employeeid,management,tin,fnpfmember,fnpf_member,fnpf,jointcard,security_licence,union_member,first_name,middle_name,last_name,fnpf_firstname,fnpf_othernames,photo,date_of_birth,gender,department,status,log', false, 'Basic Profile');
	$xcrud->fields('fathers_name,height,weight,marital,spouse,children,spouse_occupation,transport_mode', false, 'Personal Details');
	$xcrud->fields('mob,ph,street,suburb,postal,email_address', false, 'Contact & Address');
	$xcrud->fields('emergency_contact,emergency_number', false, 'Emergency Contact Details');
    $xcrud->fields('start_date,years_service,employment_type,contract,job_role,system_role,job_type,agreement,previous_employer,previous_employers_tin', false, 'Employement details');
    $xcrud->fields('qualifications,certifications,otherskills,tertiary,high_school', false, 'Education');
    $xcrud->fields('smoker,health_report', false, 'Health');
    $xcrud->fields('sick_leave_available,annual_leave_available,bereavement_leave_available,familycare_leave_available,paternity_leave_available,maternity_leave_available,ytd_sick_leave,ytd_annual_leave,ytd_bereavement_leave,ytd_familycare_leave,ytd_paternity_leave,ytd_maternity_leave', false, 'Leave Status');
	$xcrud->fields('max_hours_to_work,payment_method,bank_code,bank_name,bank_branch,account_number,account_name', false, 'Payment Details');
	$xcrud->fields('cv,hobbies,remarks', false, 'Miscellaneous');
	$xcrud->fields('current_sites,other_approved_sites,termination_date,incremental_date', false, 'Patrol Location Data');
	$xcrud->relation('department','department','departmentid','departmentname');
	$xcrud->validation_pattern('email_address', 'email');
	$xcrud->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
	$xcrud->change_type('agreement', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('cv', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('status','select','Active','Active,On Leave,trainee,attachee,Final Warning,Terminated,InActive');
	$xcrud->change_type('marital','select','Married','Married,Separated,Partner,Single,Divorcee,Widower,Widow');
	$xcrud->change_type('transport_mode','select','Public Transportation','Public Transportation,Own Transport,Walk,Bicycle');
	$xcrud->change_type('suburb','select','Suva','Nausori,Suva,Lami,Navua,Pacific Harbour,Sigatoka, Nadroga,Nadi,Lautoka,Ba,Tavua,Rakiraki,Tailevu,Labasa,Savusavu,Levuka');
	$xcrud->change_type('employment_type','select','Primary','Primary,Secondary');
	$xcrud->change_type('salary_type','select','Fixed','Fixed,Varies');
	$xcrud->change_type('job_type','select','Full-Time','Full-time,Part-Time,Casual');
	$xcrud->change_type('gender','select','Male','Male,Female, Others');
	$xcrud->change_type('payment_method','select','Transfer to Bank','Transfer to Bank,Cash,cheque');
	$xcrud->change_type('bank_name','select','No Bank Yet','No Bank Yet,Westpac,BRED,ANZ,HFC,BOB, BSP');
	$xcrud->relation('paycycle','paycycle','paycycleid','name');
	$xcrud->relation('cyclevalue','paycycle','paycycleid','frequency','','','',' ','','paycycleid','paycycle');
	$xcrud->label('last_name','Surname');
	$xcrud->column_pattern('employeeid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{employeeid}">{value}</a>');
	$xcrud->limit_list('20,50,100,1000');
    $xcrud->benchmark();
	$xcrud->label('fnpf_deducted_till_date','YTD FNPF');
	$xcrud->unset_remove();
	$xcrud->unset_add();
	$xcrud->unset_edit();

	$timenow = date('Y-m-d H:i:s');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$xcrud->pass_default('log',$log);
	$xcrud->pass_var('log',$log);
	$xcrud->before_update('update_log');
	$xcrud->disabled('log');

	$leavebreak = $xcrud->nested_table('Leave Breakdown','employeeid','absent','employeeid');
    $leavebreak->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$leavebreak->label('id','calender_id');
	$fixeddeductions = $xcrud->nested_table('Fixed Deductions','employeeid','fixeddeductions','employeeid');
	$fixeddeductions->unset_remove();
	$fixeddeductions->order_by('id','desc');
	$fixeddeductions->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
	$fixeddeductions->relation('name','fixed_deduction_codecategory','id',array('name','code'));
	$fixeddeductions->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
	$fixeddeductions->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
	$fixeddeductions->change_type('status','select','pending','pending,completed,cancelled');
	$fixeddeductions->before_insert('fixed_deductions');
	$fixeddeductions->before_update('fixed_deductions');
	$fixeddeductions->set_attr('type',array('id'=>'type'));
	$fixeddeductions->set_attr('allow_upto_75_percent',array('id'=>'allow'));
	$fixeddeductions->relation('department','department','departmentid','departmentname');

	$ebusiness1 = $xcrud->nested_table('Pay Runs/Paysip','employeeid','payrun_details','employeeid');
	$ebusiness1->relation('employeeid','employeemaster','employeeid',array('first_name','middle_name','last_name','employeeid'));
	$ebusiness1->button('PaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Print Payslip','glyphicon glyphicon-download','payslip');
	$ebusiness1->button('EmailPaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Email Payslip','glyphicon glyphicon-envelope','payslipemail');
	$ebusiness1->sum('normal_pay,premium,stay_away,normal_hours,timehalf_hours,double_hours,timehalf_amount,double_amount,stay_away,leave_allowances,other_allowances_fnpf,other_allowances_nonfnpf,meal_allowance,employee_fnpf,fnpf_employer,fixed_deductions,net_pay');
	$ebusiness1->relation('department','department','departmentid','departmentname');
	$ebusiness1->unset_remove();

	$training = $xcrud->nested_table('Training Management','employeeid','training','employeeid');
	$training->relation('type','certifications','certificateid','certificationname');
	$training->unset_remove();
	$training->pass_default('log',$log);
	$training->pass_var('log',$log);
	$training->before_update('update_log1');
	$productivity = $xcrud->nested_table('Productivity Measurement','employeeid','productivity','employeeid');
	$productivity->unset_remove();
	$ir = $xcrud->nested_table('Industrial Relations','employeeid','industrial_relations','employeeid');
	$ir->change_type('attachments', 'file', '', array('not_rename'=>true));
	$ir->unset_remove();
	$ir->pass_default('log',$log);
	$ir->pass_var('log',$log);
	$ir->before_update('update_log2');
	$certification = $xcrud->nested_table('Certifications','employeeid','certificates','employeeid');
	$certification->relation('certificate','certifications','certificateid','certificationname');
	$certification->change_type('attachments', 'file', '', array('not_rename'=>true));
	$certification->unset_remove();
	$certification->pass_var('entered_date',$timenow);
	$certification->pass_var('entered_by',$userid);
	$certification->disabled('entered_date,entered_by,log');
	$certification->pass_default('log',$log);
	$certification->pass_var('log',$log);
	$certification->before_update('update_log3');
	$ir->pass_var('entered_date',$timenow);
	$ir->pass_var('entered_by',$userid);
	$ir->disabled('entered_date,entered_by,log');
	$training->pass_var('entered_date',$timenow);
	$training->pass_var('entered_by',$userid);
	$training->disabled('entered_date,entered_by');
	$training->change_type('status','select','Scheduled','Scheduled,Underprogress,Completed,Cancelled');
	$productivity->pass_var('entered_date',$timenow);
	$productivity->pass_var('entered_by',$userid);
	$productivity->disabled('entered_date,entered_by,log');
	$productivity->pass_default('log',$log);
	$productivity->pass_var('log',$log);
	$productivity->before_update('update_log4');

	$uniform = $xcrud->nested_table('Uniform','employeeid','stockrequest','employee');
	$uniform->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$uniform->relation('employee','employeemaster','employeeid',array('first_name','last_name','employeeid'));
	$uniform->relation('client','debtorsmaster','debtorno','name');
	$uniform->relation('jobno','projectdetails','projectid',array('projectid','project_name'));
	$uniform->order_by('dispatchid','desc');
	$uniform->unset_remove();
	$uniform->unset_add();
	$uniform->unset_edit();
	$uniform->label('dispatchid','Request No');
	$uniform->label('closed','Completed');
	$uniform->label('despatchdate','Date');
	$uniform->button('StockRequestPrint.php?dispatchid={dispatchid}&loccode={loccode}&departmentid={departmentid}&despatchdate={despatchdate}&jobno={jobno}&authorised={authorised}&authorized_by={authorized_by}&narrative{narrative}&initiator={initiator}&transtype={transtype}&producttype={producttype}&client={client}&account={account}', 'Print Request','glyphicon glyphicon-download-alt');
	$uniform->column_pattern('dispatchid', '<a href="#" class="xcrud-action" data-task="view" data-primary="{dispatchid}">{value}</a>');
	$stockrequestdetails = $uniform->nested_table('Stock Request Details','dispatchid','stockrequestitems','dispatchid');
	$stockrequestdetails->unset_remove();
	$stockrequestdetails->unset_add();
	$stockrequestdetails->unset_edit();
	$vaccination = $xcrud->nested_table('vaccination','employeeid','vaccination','employeeid');
	$vaccination->change_type('type','select','jab1','jab1,jab2');
	$vaccination->change_type('card_image', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement', 'file', '', array('not_rename'=>true));
	$vaccination->change_type('other_attachement1', 'file', '', array('not_rename'=>true));
	$vaccination->unset_remove();
	$vaccination->pass_default('log',$log);
	$vaccination->pass_var('log',$log);
	$vaccination->before_update('update_log5');
	$vaccination->disabled('log');

    echo $xcrud->render();
}
// ═══════════════════════════════════════════
// PAYROLL USER — jprasad (full pay + tax access, no nested HR tables)
// ═══════════════════════════════════════════
elseif ($userid == 'jprasad') { 
    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
	$xcrud->table('employeemaster');
	$xcrud->table_name('Employee Master Details');
	Xcrud_config::$editor_url = dirname($_SERVER["SCRIPT_NAME"]).'/editors/ckeditor/ckeditor.js'; 
	$xcrud->disabled('log');
	$xcrud->columns('employeeid,first_name,middle_name,last_name,tin,fnpf,department,job_role,email_address,status,log');
	$xcrud->unset_remove();
    $xcrud->fields('employeeid,management,tin,fnpfmember,fnpf_member,fnpf,jointcard,security_licence,union_member,first_name,middle_name,last_name,fnpf_firstname,fnpf_othernames,photo,date_of_birth,gender,department,status,log', false, 'Basic Profile');
	$xcrud->fields('fathers_name,height,weight,marital,spouse,children,spouse_occupation,transport_mode', false, 'Personal Details');
	$xcrud->fields('mob,ph,street,suburb,postal,email_address', false, 'Contact & Address');
	$xcrud->fields('emergency_contact,emergency_number', false, 'Emergency Contact Details');
    $xcrud->fields('start_date,years_service,employment_type,contract,job_role,system_role,job_type,agreement,previous_employer,previous_employers_tin', false, 'Employement details');
    $xcrud->fields('qualifications,certifications,otherskills,tertiary,high_school', false, 'Education');
    $xcrud->fields('smoker,health_report', false, 'Health');
    $xcrud->fields('sick_leave_available,annual_leave_available,bereavement_leave_available,familycare_leave_available,paternity_leave_available,maternity_leave_available,ytd_sick_leave,ytd_annual_leave,ytd_bereavement_leave,ytd_familycare_leave,ytd_paternity_leave,ytd_maternity_leave', false, 'Leave Status');
	$xcrud->fields('max_hours_to_work,salary_type,paycycle,cyclevalue, annualsalary,base_wage_rate,ytd_gross,payment_method,bank_code,bank_name,bank_branch,account_number,account_name,second_bankname,second_accountname,second_accountnumber,second_amount', false, 'Payment Details');
	$xcrud->fields('cv,hobbies,remarks', false, 'Miscellaneous');
	$xcrud->fields('non_resident,completed_pay_period,annual_income_plus_bonus,ytd_income_tax_withheld,ytd_srt_tax_withheld,ytd_ecal_tax_withheld',false,'Tax Details');
	$xcrud->fields('fnpf_deducted_till_date',false,'FNPF Details');
	$xcrud->fields('current_sites,other_approved_sites,termination_date,incremental_date', false, 'Patrol Location Data');
	$xcrud->relation('department','department','departmentid','departmentname');
	$xcrud->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
	$xcrud->change_type('agreement', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('cv', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('status','select','Active','Active,On Leave,trainee,attachee,Final Warning,Terminated,InActive');
	$xcrud->change_type('marital','select','Married','Married,Separated,Partner,Single,Divorcee,Widower,Widow');
	$xcrud->change_type('transport_mode','select','Public Transportation','Public Transportation,Own Transport,Walk,Bicycle');
	$xcrud->change_type('suburb','select','Suva','Nausori,Suva,Lami,Navua,Pacific Harbour,Sigatoka, Nadroga,Nadi,Lautoka,Ba,Tavua,Rakiraki,Tailevu,Labasa,Savusavu,Levuka');
	$xcrud->change_type('employment_type','select','Primary','Primary,Secondary');
	$xcrud->validation_pattern('email_address', 'email');
	$xcrud->change_type('salary_type','select','Fixed','Fixed,Varies');
	$xcrud->change_type('job_type','select','Full-Time','Full-time,Part-Time,Casual');
	$xcrud->change_type('gender','select','Male','Male,Female, Others');
	$xcrud->change_type('payment_method','select','Transfer to Bank','Transfer to Bank,Cash,cheque');
	$xcrud->change_type('bank_name','select','No Bank Yet','No Bank Yet,Westpac,BRED,ANZ,HFC,BOB, BSP');
	$xcrud->relation('paycycle','paycycle','paycycleid','name');
	$xcrud->relation('cyclevalue','paycycle','paycycleid','frequency','','','',' ','','paycycleid','paycycle');
	$xcrud->label('last_name','Surname');
	$xcrud->column_pattern('employeeid', '<a href="#" class="xcrud-action" data-task="edit" data-primary="{employeeid}">{value}</a>');
	$xcrud->limit_list('20,50,100,1000');
    $xcrud->benchmark();
	$xcrud->label('fnpf_deducted_till_date','YTD FNPF');

	$timenow = date('Y-m-d H:i:s');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$xcrud->pass_default('log',$log);
	$xcrud->pass_var('log',$log);
	$xcrud->before_update('update_log');
	$xcrud->disabled('log');

	$leavebreak = $xcrud->nested_table('Leave Breakdown','employeeid','absent','employeeid');
    $leavebreak->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$leavebreak->label('id','calender_id');
	$fixeddeductions = $xcrud->nested_table('Fixed Deductions','employeeid','fixeddeductions','employeeid');
	$fixeddeductions->unset_remove();
	$fixeddeductions->order_by('id','desc');
	$fixeddeductions->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
	$fixeddeductions->relation('name','fixed_deduction_codecategory','id',array('name','code'));
	$fixeddeductions->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
	$fixeddeductions->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
	$fixeddeductions->change_type('status','select','pending','pending,completed,cancelled');
	$fixeddeductions->before_insert('fixed_deductions');
	$fixeddeductions->before_update('fixed_deductions');
	$fixeddeductions->set_attr('type',array('id'=>'type'));
	$fixeddeductions->set_attr('allow_upto_75_percent',array('id'=>'allow'));
	$fixeddeductions->relation('department','department','departmentid','departmentname');

	$ebusiness1 = $xcrud->nested_table('Pay Runs/Paysip','employeeid','payrun_details','employeeid');
	$ebusiness1->relation('employeeid','employeemaster','employeeid',array('first_name','middle_name','last_name','employeeid'));
	$ebusiness1->button('PaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Print Payslip','glyphicon glyphicon-download','payslip');
	$ebusiness1->button('EmailPaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Email Payslip','glyphicon glyphicon-envelope','payslipemail');
	$ebusiness1->sum('normal_pay,premium,stay_away,normal_hours,timehalf_hours,double_hours,timehalf_amount,double_amount,stay_away,leave_allowances,other_allowances_fnpf,other_allowances_nonfnpf,meal_allowance,employee_fnpf,fnpf_employer,fixed_deductions,net_pay');
	$ebusiness1->relation('department','department','departmentid','departmentname');
	$ebusiness1->unset_remove();

    echo $xcrud->render();
}
// ═══════════════════════════════════════════
// PAYROLL + TAX USER — clorissa (no management, has tax/fnpf)
// ═══════════════════════════════════════════
elseif ($userid == 'clorissa') { 
    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
	$xcrud->table('employeemaster');
	$xcrud->table_name('Employee Master Details');
	Xcrud_config::$editor_url = dirname($_SERVER["SCRIPT_NAME"]).'/editors/ckeditor/ckeditor.js'; 
	$xcrud->where('management=',0);
	$xcrud->disabled('log');
	$xcrud->columns('employeeid,first_name,middle_name,last_name,tin,fnpf,department,job_role,email_address,status,log');
	$xcrud->unset_remove();
    $xcrud->fields('employeeid,management,tin,fnpfmember,fnpf_member,fnpf,jointcard,security_licence,union_member,first_name,middle_name,last_name,fnpf_firstname,fnpf_othernames,photo,date_of_birth,gender,department,status,log', false, 'Basic Profile');
	$xcrud->fields('fathers_name,height,weight,marital,spouse,children,spouse_occupation,transport_mode', false, 'Personal Details');
	$xcrud->fields('mob,ph,street,suburb,postal,email_address', false, 'Contact & Address');
	$xcrud->fields('emergency_contact,emergency_number', false, 'Emergency Contact Details');
    $xcrud->fields('start_date,years_service,employment_type,contract,job_role,system_role,job_type,agreement,previous_employer,previous_employers_tin', false, 'Employement details');
    $xcrud->fields('qualifications,certifications,otherskills,tertiary,high_school', false, 'Education');
    $xcrud->fields('smoker,health_report', false, 'Health');
    $xcrud->fields('sick_leave_available,annual_leave_available,bereavement_leave_available,familycare_leave_available,paternity_leave_available,maternity_leave_available,ytd_sick_leave,ytd_annual_leave,ytd_bereavement_leave,ytd_familycare_leave,ytd_paternity_leave,ytd_maternity_leave', false, 'Leave Status');
	$xcrud->fields('max_hours_to_work,salary_type,paycycle,cyclevalue, annualsalary,base_wage_rate,ytd_gross,payment_method,bank_code,bank_name,bank_branch,account_number,account_name,second_bankname,second_accountname,second_accountnumber', false, 'Payment Details');
	$xcrud->fields('cv,hobbies,remarks', false, 'Miscellaneous');
	$xcrud->fields('non_resident,completed_pay_period,annual_income_plus_bonus,ytd_income_tax_withheld,ytd_srt_tax_withheld,ytd_ecal_tax_withheld',false,'Tax Details');
	$xcrud->fields('fnpf_deducted_till_date',false,'FNPF Details');
	$xcrud->fields('current_sites,other_approved_sites,termination_date,incremental_date', false, 'Patrol Location Data');
	$xcrud->relation('department','department','departmentid','departmentname');
	$xcrud->change_type('photo', 'image', '', array('thumbs' => 
    array(
        array('width' => '200', 'height' => '200', 'marker' => '_th'),
        array('width' => 50, 'height' => 50, 'crop' => true, 'folder' => 'thumbs')
    )));
	$xcrud->change_type('agreement', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('cv', 'file', '', array('not_rename'=>true));
	$xcrud->change_type('status','select','Active','Active,On Leave,trainee,attachee,Final Warning,Terminated,InActive');
	$xcrud->change_type('marital','select','Married','Married,Separated,Partner,Single,Divorcee,Widower,Widow');
	$xcrud->change_type('transport_mode','select','Public Transportation','Public Transportation,Own Transport,Walk,Bicycle');
	$xcrud->change_type('suburb','select','Suva','Nausori,Suva,Lami,Navua,Pacific Harbour,Sigatoka, Nadroga,Nadi,Lautoka,Ba,Tavua,Rakiraki,Tailevu,Labasa,Savusavu,Levuka');
	$xcrud->change_type('employment_type','select','Primary','Primary,Secondary');
	$xcrud->validation_pattern('email_address', 'email');
	$xcrud->change_type('salary_type','select','Fixed','Fixed,Varies');
	$xcrud->change_type('job_type','select','Full-Time','Full-time,Part-Time,Casual');
	$xcrud->change_type('gender','select','Male','Male,Female, Others');
	$xcrud->change_type('payment_method','select','Transfer to Bank','Transfer to Bank,Cash,cheque');
	$xcrud->change_type('bank_name','select','No Bank Yet','No Bank Yet,Westpac,BRED,ANZ,HFC,BOB, BSP');
	$xcrud->relation('paycycle','paycycle','paycycleid','name');
	$xcrud->relation('cyclevalue','paycycle','paycycleid','frequency','','','',' ','','paycycleid','paycycle');
	$xcrud->label('last_name','Surname');
	$xcrud->column_pattern('employeeid', '<a href="#" class="xcrud-action" data-task="edit" data-primary="{employeeid}">{value}</a>');
	$xcrud->limit_list('20,50,100,1000');
    $xcrud->benchmark();
	$xcrud->label('fnpf_deducted_till_date','YTD FNPF');

	$timenow = date('Y-m-d H:i:s');
	$log = "Entered by: ".$userid." Date : ".$timenow;
	$xcrud->pass_default('log',$log);
	$xcrud->pass_var('log',$log);
	$xcrud->before_update('update_log');
	$xcrud->disabled('log');

	$leavebreak = $xcrud->nested_table('Leave Breakdown','employeeid','absent','employeeid');
    $leavebreak->relation('departmentid','department','departmentid',array('departmentid','departmentname'));
	$leavebreak->label('id','calender_id');
	$fixeddeductions = $xcrud->nested_table('Fixed Deductions','employeeid','fixeddeductions','employeeid');
	$fixeddeductions->unset_remove();
	$fixeddeductions->order_by('id','desc');
	$fixeddeductions->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
	$fixeddeductions->relation('name','fixed_deduction_codecategory','id',array('name','code'));
	$fixeddeductions->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
	$fixeddeductions->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
	$fixeddeductions->change_type('status','select','pending','pending,completed,cancelled');
	$fixeddeductions->before_insert('fixed_deductions');
	$fixeddeductions->before_update('fixed_deductions');
	$fixeddeductions->set_attr('type',array('id'=>'type'));
	$fixeddeductions->set_attr('allow_upto_75_percent',array('id'=>'allow'));
	$fixeddeductions->relation('department','department','departmentid','departmentname');

	$ebusiness1 = $xcrud->nested_table('Pay Runs/Paysip','employeeid','payrun_details','employeeid');
	$ebusiness1->relation('employeeid','employeemaster','employeeid',array('first_name','middle_name','last_name','employeeid'));
	$ebusiness1->button('PaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Print Payslip','glyphicon glyphicon-download','payslip');
	$ebusiness1->button('EmailPaySlipsIndividual.php?payid={payid}&employeeid={employeeid}', 'Email Payslip','glyphicon glyphicon-envelope','payslipemail');
	$ebusiness1->sum('normal_pay,premium,stay_away,normal_hours,timehalf_hours,double_hours,timehalf_amount,double_amount,stay_away,leave_allowances,other_allowances_fnpf,other_allowances_nonfnpf,meal_allowance,employee_fnpf,fnpf_employer,fixed_deductions,net_pay');
	$ebusiness1->relation('department','department','departmentid','departmentname');
	$ebusiness1->unset_remove();

    echo $xcrud->render();
}
// ═══════════════════════════════════════════
// NO ACCESS — all other users
// ═══════════════════════════════════════════
else {
	echo '<div style="text-align:center;padding:60px 20px;font-family:Poppins,sans-serif;">
		<div style="font-size:48px;margin-bottom:16px;">&#128274;</div>
		<h3 style="color:#1F2937;margin-bottom:8px;">Access Restricted</h3>
		<p style="color:#6B7280;font-size:14px;">You do not have permission to view Employee Master Details.<br/>Contact your system administrator for access.</p>
		<a href="index.php" style="display:inline-block;margin-top:20px;padding:10px 24px;background:#2AABB3;color:#fff;border-radius:8px;text-decoration:none;font-weight:600;font-size:13px;">&#8592; Return to Dashboard</a>
	</div>';
}

echo '</div>';
echo '</div>';
echo '</div>';
?>
</div>

<!-- Status Badge Enhancement + Tab Icon Script -->
<script>
jQuery(document).on("ready xcrudafterrequest", function(){
    // Status badges with Ant Design colors
    var sc = {
        'Active':{bg:'#F6FFED',c:'#52C41A',b:'#B7EB8F'},
        'On Leave':{bg:'#FFF7E6',c:'#FAAD14',b:'#FFE58F'},
        'trainee':{bg:'#E6F7FF',c:'#1890FF',b:'#91D5FF'},
        'attachee':{bg:'#F0F5FF',c:'#2F54EB',b:'#ADC6FF'},
        'Final Warning':{bg:'#FFF2F0',c:'#FF4D4F',b:'#FFCCC7'},
        'Terminated':{bg:'#FFF1F0',c:'#CF1322',b:'#FFA39E'},
        'InActive':{bg:'#F5F5F5',c:'#8C8C8C',b:'#D9D9D9'}
    };
    jQuery('table.xcrud-list tbody td').each(function(){
        var t = jQuery(this).text().trim();
        if(sc[t]){
            var s=sc[t];
            jQuery(this).html('<span style="display:inline-block;padding:3px 12px;border-radius:12px;font-size:11.5px;font-weight:600;font-family:Poppins,sans-serif;background:'+s.bg+';color:'+s.c+';border:1px solid '+s.b+';">'+t+'</span>');
        }
    });

    // Add tab icons
    var tabIcons = {
        'Basic Profile':'fas fa-user-circle',
        'Personal Details':'fas fa-id-card',
        'Contact & Address':'fas fa-map-marker-alt',
        'Emergency Contact':'fas fa-phone-alt',
        'Employement details':'fas fa-briefcase',
        'Education':'fas fa-graduation-cap',
        'Health':'fas fa-heartbeat',
        'Leave Status':'fas fa-calendar-check',
        'Payment Details':'fas fa-credit-card',
        'Miscellaneous':'fas fa-folder-open',
        'Tax Details':'fas fa-file-invoice-dollar',
        'FNPF Details':'fas fa-piggy-bank',
        'Patrol Location':'fas fa-map-pin',
        'Leave Breakdown':'fas fa-calendar-minus',
        'Fixed Deductions':'fas fa-minus-circle',
        'Pay Runs':'fas fa-money-check-alt',
        'Training':'fas fa-chalkboard-teacher',
        'Productivity':'fas fa-chart-line',
        'Industrial Relations':'fas fa-balance-scale',
        'Certifications':'fas fa-certificate',
        'Uniform':'fas fa-tshirt',
        'vaccination':'fas fa-syringe'
    };
    jQuery('.xcrud-nav a, .xcrud-tab a').each(function(){
        var txt = jQuery(this).text().trim();
        var el = jQuery(this);
        if(el.find('i.fa,i.fas').length === 0){
            jQuery.each(tabIcons, function(key, icon){
                if(txt.indexOf(key) !== -1 || key.indexOf(txt) !== -1){
                    el.prepend('<i class="'+icon+'" style="opacity:0.6;font-size:12px;margin-right:4px;"></i> ');
                    return false;
                }
            });
        }
    });
});
</script>

<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>

<?php
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p></td></tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p></td></tr>
		</table>';
	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){
	$_SESSION['Module'] = $_GET['Application'];
}
?>
