<?php
$page_title = 'Employee Master Management';
$admin_page = 'employees';
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_id'])) { redirect(SITE_URL . '/admin/login.php'); }
require_once __DIR__ . '/header.php';

$db = getDB();

// Fetch Dashboard Metrics
$metrics = $db->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN employment_type = 'Contract' THEN 1 ELSE 0 END) as contract,
        SUM(CASE WHEN verification_status != 'Verified' THEN 1 ELSE 0 END) as pending_docs
    FROM employees
")->fetch(PDO::FETCH_ASSOC);

// Fetch Branches & Departments for filters
$branches = $db->query("SELECT id, branch_name FROM branches")->fetchAll(PDO::FETCH_ASSOC);
$departments = $db->query("SELECT DISTINCT department FROM employees WHERE department IS NOT NULL")->fetchAll(PDO::FETCH_ASSOC);

// Fetch Employee List
$stmt = $db->query("
    SELECT e.*, b.branch_name,
    (SELECT COUNT(*) FROM employee_documents WHERE employee_id = e.id) as doc_count
    FROM employees e
    LEFT JOIN branches b ON e.branch_id = b.id
    ORDER BY e.id DESC
");
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:24px;">
    <div>
        <h2 style="font-family:'Outfit',sans-serif; font-size:1.8rem; color:#0f172a; margin:0;">Employee Master</h2>
        <p style="color:#64748b; font-size:0.95rem; margin-top:5px;">Manage comprehensive employee lifecycle and profiles.</p>
    </div>
    <div style="display:flex; gap:10px;">
        <button style="background:#f8fafc; color:#0f172a; border:1px solid #cbd5e1; padding:8px 16px; border-radius:6px; cursor:pointer; font-weight:600;"><i class="fas fa-file-export"></i> Export</button>
        <button onclick="openEmployeeModal()" style="background:#2563eb; color:#fff; border:none; padding:8px 16px; border-radius:6px; cursor:pointer; font-weight:600;"><i class="fas fa-user-plus"></i> Add New Employee</button>
    </div>
</div>

<!-- KPI Dashboard Cards -->
<div class="grid-4" style="margin-bottom:24px;">
    <div class="card" style="padding:20px; border-left:4px solid #3b82f6; display:flex; align-items:center; justify-content:space-between;">
        <div>
            <div style="color:#64748b; font-size:0.8rem; font-weight:700; text-transform:uppercase;">Total Employees</div>
            <div style="font-size:1.8rem; font-weight:800; color:#0f172a;"><?= $metrics['total'] ?? 0 ?></div>
        </div>
        <div style="width:50px; height:50px; border-radius:12px; background:#eff6ff; color:#3b82f6; display:flex; align-items:center; justify-content:center; font-size:1.5rem;"><i class="fas fa-users"></i></div>
    </div>
    <div class="card" style="padding:20px; border-left:4px solid #10b981; display:flex; align-items:center; justify-content:space-between;">
        <div>
            <div style="color:#64748b; font-size:0.8rem; font-weight:700; text-transform:uppercase;">Active Staff</div>
            <div style="font-size:1.8rem; font-weight:800; color:#0f172a;"><?= $metrics['active'] ?? 0 ?></div>
        </div>
        <div style="width:50px; height:50px; border-radius:12px; background:#dcfce7; color:#10b981; display:flex; align-items:center; justify-content:center; font-size:1.5rem;"><i class="fas fa-user-check"></i></div>
    </div>
    <div class="card" style="padding:20px; border-left:4px solid #f59e0b; display:flex; align-items:center; justify-content:space-between;">
        <div>
            <div style="color:#64748b; font-size:0.8rem; font-weight:700; text-transform:uppercase;">Contract Base</div>
            <div style="font-size:1.8rem; font-weight:800; color:#0f172a;"><?= $metrics['contract'] ?? 0 ?></div>
        </div>
        <div style="width:50px; height:50px; border-radius:12px; background:#fef3c7; color:#f59e0b; display:flex; align-items:center; justify-content:center; font-size:1.5rem;"><i class="fas fa-file-contract"></i></div>
    </div>
    <div class="card" style="padding:20px; border-left:4px solid #ef4444; display:flex; align-items:center; justify-content:space-between;">
        <div>
            <div style="color:#64748b; font-size:0.8rem; font-weight:700; text-transform:uppercase;">Pending Verification</div>
            <div style="font-size:1.8rem; font-weight:800; color:#ef4444;"><?= $metrics['pending_docs'] ?? 0 ?></div>
        </div>
        <div style="width:50px; height:50px; border-radius:12px; background:#fee2e2; color:#ef4444; display:flex; align-items:center; justify-content:center; font-size:1.5rem;"><i class="fas fa-exclamation-triangle"></i></div>
    </div>
</div>

<!-- Advanced Filters -->
<div class="card" style="margin-bottom:24px; padding:15px 20px; display:flex; gap:15px; align-items:center; flex-wrap:wrap;">
    <div style="font-weight:600; color:#475569;"><i class="fas fa-filter"></i> Filters:</div>
    <input type="text" id="searchEmp" placeholder="Search ID, Name, Phone..." style="padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none; min-width:200px;">
    
    <select style="padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none; background:#f8fafc;">
        <option value="">All Branches</option>
        <?php foreach($branches as $b): ?><option value="<?= $b['id'] ?>"><?= h($b['branch_name']) ?></option><?php endforeach; ?>
    </select>
    
    <select style="padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none; background:#f8fafc;">
        <option value="">All Departments</option>
        <?php foreach($departments as $d): ?><option value="<?= $d['department'] ?>"><?= h($d['department']) ?></option><?php endforeach; ?>
    </select>
    
    <select style="padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none; background:#f8fafc;">
        <option value="">Status: All</option>
        <option value="active">Active</option>
        <option value="suspended">Suspended</option>
        <option value="terminated">Terminated</option>
    </select>
</div>

<!-- Employee Data Table -->
<div class="card" style="padding:0; overflow:hidden;">
    <div style="overflow-x:auto;">
        <table style="width:100%; border-collapse:collapse; min-width:1200px; font-size:0.85rem;" id="empTable">
            <thead>
                <tr style="background:#f1f5f9; color:#475569; text-align:left; border-bottom:2px solid #e2e8f0;">
                    <th style="padding:12px 15px;">Profile</th>
                    <th style="padding:12px 15px;">Employee ID</th>
                    <th style="padding:12px 15px;">Full Name</th>
                    <th style="padding:12px 15px;">Department / Shift</th>
                    <th style="padding:12px 15px;">Branch</th>
                    <th style="padding:12px 15px;">Contact</th>
                    <th style="padding:12px 15px;">Status</th>
                    <th style="padding:12px 15px; text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($employees as $e): 
                    $emp_code = $e['emp_code'] ?? 'EMP-'.str_pad($e['id'],4,'0',STR_PAD_LEFT);
                    $status_badge = $e['status'] === 'active' ? '<span style="background:#dcfce7; color:#166534; padding:2px 6px; border-radius:4px; font-weight:600;">Active</span>' : '<span style="background:#fee2e2; color:#991b1b; padding:2px 6px; border-radius:4px; font-weight:600;">In-Active</span>';
                ?>
                <tr style="border-bottom:1px solid #f1f5f9; transition:background 0.2s;" class="emp-row">
                    <td style="padding:12px 15px;">
                        <div style="width:35px; height:35px; border-radius:50%; background:#2563eb; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:bold;">
                            <?= strtoupper(substr($e['name'],0,1)) ?>
                        </div>
                    </td>
                    <td style="padding:12px 15px; font-weight:700; color:#0f172a;"><?= $emp_code ?></td>
                    <td style="padding:12px 15px;">
                        <div style="font-weight:600; color:#1e293b;"><?= h($e['name']) ?></div>
                        <div style="font-size:0.75rem; color:#64748b;"><?= h($e['designation'] ?? 'Staff') ?></div>
                    </td>
                    <td style="padding:12px 15px;">
                        <div><?= h($e['department'] ?? 'Office') ?></div>
                        <div style="font-size:0.75rem; color:#64748b;">Shift: <?= h($e['shift'] ?? 'General') ?></div>
                    </td>
                    <td style="padding:12px 15px; color:#475569;"><i class="fas fa-building" style="color:#cbd5e1;"></i> <?= h($e['branch_name'] ?? 'HO') ?></td>
                    <td style="padding:12px 15px;">
                        <div style="color:#3b82f6;"><i class="fas fa-phone-alt" style="font-size:0.75rem;"></i> <?= h($e['mobile'] ?? 'N/A') ?></div>
                        <div style="font-size:0.75rem; color:#64748b;"><?= h($e['email'] ?? 'N/A') ?></div>
                    </td>
                    <td style="padding:12px 15px;"><?= $status_badge ?></td>
                    <td style="padding:12px 15px; text-align:center;">
                        <button onclick="viewEmployeeProfile(<?= $e['id'] ?>)" title="View Profile" style="background:none; border:none; color:#3b82f6; cursor:pointer; margin:0 5px;"><i class="fas fa-eye"></i></button>
                        <button title="Edit" style="background:none; border:none; color:#f59e0b; cursor:pointer; margin:0 5px;" onclick="editEmployee(<?= $e['id'] ?>)"><i class="fas fa-edit"></i></button>
                        <button title="Action Menu" style="background:none; border:none; color:#64748b; cursor:pointer; margin:0 5px;"><i class="fas fa-ellipsis-v"></i></button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div style="padding:15px; border-top:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; font-size:0.85rem; color:#64748b;">
        <div>Showing 1 to <?= count($employees) ?> of <?= count($employees) ?> entries</div>
        <div style="display:flex; gap:5px;">
            <button style="padding:5px 10px; border:1px solid #cbd5e1; background:#fff; border-radius:4px; cursor:pointer;">Previous</button>
            <button style="padding:5px 10px; border:1px solid #2563eb; background:#2563eb; color:#fff; border-radius:4px; cursor:pointer;">1</button>
            <button style="padding:5px 10px; border:1px solid #cbd5e1; background:#fff; border-radius:4px; cursor:pointer;">Next</button>
        </div>
    </div>
</div>

<!-- Add/Edit Employee Modal (Complex Form) -->
<div id="empModal" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.6); z-index:1000; align-items:center; justify-content:center; backdrop-filter:blur(4px);">
    <div style="background:#fff; width:100%; max-width:850px; border-radius:12px; max-height:90vh; display:flex; flex-direction:column; box-shadow:0 20px 25px -5px rgba(0,0,0,0.1);">
        
        <div style="padding:20px; border-bottom:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; background:#f8fafc; border-radius:12px 12px 0 0;">
            <h3 id="empModalTitle" style="margin:0; font-size:1.25rem; color:#0f172a;"><i class="fas fa-user-plus" style="color:#2563eb; margin-right:10px;"></i>Add New Employee</h3>
            <button onclick="closeEmployeeModal()" style="background:none; border:none; font-size:1.25rem; color:#64748b; cursor:pointer;"><i class="fas fa-times"></i></button>
        </div>
        
        <div style="padding:20px; overflow-y:auto; flex:1;">
            <form id="empForm" onsubmit="saveEmployee(event)">
                <input type="hidden" id="emp_id" name="emp_id">
                
                <h4 style="margin:0 0 15px; font-size:1rem; color:#3b82f6; border-bottom:1px solid #bfdbfe; padding-bottom:5px;">Personal Details</h4>
                <div class="grid-3" style="gap:15px; margin-bottom:25px;">
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Full Name *</label>
                        <input type="text" name="name" id="emp_name" required style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Email Address *</label>
                        <input type="email" name="email" id="emp_email" required style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Mobile Number</label>
                        <input type="text" name="mobile" id="emp_mobile" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Gender</label>
                        <select name="gender" id="emp_gender" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Date of Birth</label>
                        <input type="date" name="dob" id="emp_dob" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Blood Group</label>
                        <input type="text" name="blood_group" id="emp_blood" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;" placeholder="e.g. O+">
                    </div>
                </div>

                <h4 style="margin:0 0 15px; font-size:1rem; color:#3b82f6; border-bottom:1px solid #bfdbfe; padding-bottom:5px;">Corporate Allocation</h4>
                <div class="grid-3" style="gap:15px; margin-bottom:25px;">
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Branch / Plant *</label>
                        <select name="branch_id" id="emp_branch" required style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                            <option value="">Select Branch</option>
                            <?php foreach($branches as $b): ?><option value="<?= $b['id'] ?>"><?= h($b['branch_name']) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Department</label>
                        <input type="text" name="department" id="emp_dept" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Designation</label>
                        <input type="text" name="designation" id="emp_desig" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Employment Type</label>
                        <select name="employment_type" id="emp_type" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                            <option value="Permanent">Permanent</option>
                            <option value="Contract">Contract</option>
                            <option value="Probation">Probation</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">System Role</label>
                        <select name="role" id="emp_role" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                            <option value="employee">Employee</option>
                            <option value="hr">HR Manager</option>
                            <option value="admin">System Admin</option>
                        </select>
                    </div>
                    <div>
                        <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px;">Initial Password *</label>
                        <input type="text" name="password" id="emp_pass" placeholder="Leave blank to keep existing" style="width:100%; padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
                    </div>
                </div>
            </form>
        </div>
        
        <div style="padding:20px; border-top:1px solid #e2e8f0; display:flex; justify-content:flex-end; gap:10px; background:#f8fafc; border-radius:0 0 12px 12px;">
            <button type="button" onclick="closeEmployeeModal()" style="padding:10px 20px; background:#fff; border:1px solid #cbd5e1; color:#475569; border-radius:6px; cursor:pointer; font-weight:600;">Cancel</button>
            <button type="submit" form="empForm" id="saveEmpBtn" style="padding:10px 20px; background:#2563eb; color:#fff; border:none; border-radius:6px; cursor:pointer; font-weight:600;"><i class="fas fa-save"></i> Save Employee</button>
        </div>

    </div>
</div>

<!-- Employee Deep Profile View Modal -->
<div id="profileModal" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.6); z-index:1000; align-items:center; justify-content:center; backdrop-filter:blur(4px);">
    <div style="background:#fff; width:100%; max-width:1000px; border-radius:12px; height:90vh; display:flex; flex-direction:column; box-shadow:0 20px 25px -5px rgba(0,0,0,0.1); overflow:hidden;">
        
        <!-- Header -->
        <div style="padding:20px; border-bottom:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; background:#0f172a; color:#fff;">
            <div style="display:flex; align-items:center; gap:15px;">
                <div id="profAvatar" style="width:50px; height:50px; border-radius:50%; background:#3b82f6; display:flex; align-items:center; justify-content:center; font-size:1.5rem; font-weight:bold; border:2px solid #fff;">A</div>
                <div>
                    <h3 id="profName" style="margin:0; font-size:1.4rem;">Loading...</h3>
                    <div style="font-size:0.85rem; color:#94a3b8;"><span id="profDesig"></span> · <span id="profDept"></span></div>
                </div>
            </div>
            <button onclick="closeProfileModal()" style="background:none; border:none; font-size:1.5rem; color:#cbd5e1; cursor:pointer;"><i class="fas fa-times"></i></button>
        </div>

        <!-- Body with Tabs -->
        <div style="display:flex; flex:1; overflow:hidden;">
            <!-- Tab Links (Sidebar) -->
            <div style="width:220px; background:#f8fafc; border-right:1px solid #e2e8f0; display:flex; flex-direction:column;">
                <button class="prof-tab active" onclick="switchTab('overview')" style="padding:15px 20px; text-align:left; background:#fff; border:none; border-left:3px solid #2563eb; color:#0f172a; font-weight:600; cursor:pointer;"><i class="fas fa-id-card" style="width:20px;"></i> Overview</button>
                <button class="prof-tab" onclick="switchTab('docs')" style="padding:15px 20px; text-align:left; background:transparent; border:none; border-left:3px solid transparent; color:#64748b; font-weight:600; cursor:pointer;"><i class="fas fa-folder-open" style="width:20px;"></i> Documents</button>
                <button class="prof-tab" onclick="switchTab('finance')" style="padding:15px 20px; text-align:left; background:transparent; border:none; border-left:3px solid transparent; color:#64748b; font-weight:600; cursor:pointer;"><i class="fas fa-money-check-alt" style="width:20px;"></i> Payroll & Bank</button>
                <button class="prof-tab" onclick="switchTab('logs')" style="padding:15px 20px; text-align:left; background:transparent; border:none; border-left:3px solid transparent; color:#64748b; font-weight:600; cursor:pointer;"><i class="fas fa-history" style="width:20px;"></i> Activity Logs</button>
            </div>

            <!-- Tab Content Area -->
            <div style="flex:1; padding:25px; overflow-y:auto; background:#fff;" id="profContentArea">
                <div style="text-align:center; padding:50px;"><i class="fas fa-spinner fa-spin" style="font-size:2rem; color:#3b82f6;"></i></div>
            </div>
        </div>
    </div>
</div>

<script>
// --- Existing JS ---
document.getElementById('searchEmp').addEventListener('input', function(e) {
    let filter = e.target.value.toLowerCase();
    let rows = document.querySelectorAll('.emp-row');
    rows.forEach(row => {
        let text = row.innerText.toLowerCase();
        row.style.display = text.includes(filter) ? '' : 'none';
    });
});

function openEmployeeModal() {
    document.getElementById('empForm').reset();
    document.getElementById('emp_id').value = '';
    document.getElementById('empModalTitle').innerHTML = '<i class="fas fa-user-plus" style="color:#2563eb; margin-right:10px;"></i>Add New Employee';
    document.getElementById('emp_pass').required = true;
    document.getElementById('empModal').style.display = 'flex';
}

function closeEmployeeModal() { document.getElementById('empModal').style.display = 'none'; }

function editEmployee(id) {
    document.getElementById('empForm').reset();
    document.getElementById('emp_id').value = id;
    document.getElementById('empModalTitle').innerHTML = '<i class="fas fa-user-edit" style="color:#f59e0b; margin-right:10px;"></i>Edit Employee';
    document.getElementById('emp_pass').required = false;
    document.getElementById('empModal').style.display = 'flex';
    alert('Edit mode triggered. Connect this to the profile fetch API.');
}

async function saveEmployee(e) {
    e.preventDefault();
    const btn = document.getElementById('saveEmpBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
    btn.disabled = true;

    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());

    try {
        const response = await fetch('../api/employee-actions.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
        const result = await response.json();
        
        if (result.success) { alert('Employee saved successfully!'); location.reload(); }
        else { alert('Error: ' + result.message); btn.innerHTML = '<i class="fas fa-save"></i> Save Employee'; btn.disabled = false; }
    } catch (err) { alert('Network Error.'); btn.innerHTML = '<i class="fas fa-save"></i> Save Employee'; btn.disabled = false; }
}

// --- New Profile Modal JS ---
let currentProfileData = null;

async function viewEmployeeProfile(id) {
    document.getElementById('profileModal').style.display = 'flex';
    document.getElementById('profContentArea').innerHTML = '<div style="text-align:center; padding:50px;"><i class="fas fa-spinner fa-spin" style="font-size:2rem; color:#3b82f6;"></i> Fetching ERP Data...</div>';
    
    try {
        const res = await fetch(`../api/get-employee-profile.php?id=${id}`);
        const data = await res.json();
        if (!data.success) {
            document.getElementById('profContentArea').innerHTML = `<div style="color:red; padding:20px;">${data.message}</div>`;
            return;
        }
        
        currentProfileData = data.profile;
        let c = currentProfileData.core;
        
        // Update Header
        document.getElementById('profName').innerText = c.name;
        document.getElementById('profAvatar').innerText = c.name.charAt(0).toUpperCase();
        document.getElementById('profDesig').innerText = c.designation || 'Staff';
        document.getElementById('profDept').innerText = c.department || 'Office';
        
        // Render Default Tab
        switchTab('overview');
        
    } catch (err) {
        document.getElementById('profContentArea').innerHTML = `<div style="color:red; padding:20px;">Network Error loading profile.</div>`;
    }
}

function closeProfileModal() { document.getElementById('profileModal').style.display = 'none'; }

function switchTab(tabName) {
    // UI Tab Switch
    document.querySelectorAll('.prof-tab').forEach(t => {
        t.style.background = 'transparent'; t.style.borderLeftColor = 'transparent'; t.style.color = '#64748b'; t.style.background = 'transparent';
    });
    event.currentTarget.style.background = '#fff';
    event.currentTarget.style.borderLeftColor = '#2563eb';
    event.currentTarget.style.color = '#0f172a';

    const p = currentProfileData;
    const c = p.core;
    let html = '';

    if (tabName === 'overview') {
        html = `
            <h4 style="margin:0 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Personal Overview</h4>
            <div class="grid-3" style="gap:20px; font-size:0.9rem;">
                <div><span style="color:#64748b; font-size:0.8rem;">Employee ID</span><br><strong>${c.emp_code}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Email</span><br><strong>${c.email || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Mobile</span><br><strong>${c.mobile || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Date of Birth</span><br><strong>${c.dob || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Gender</span><br><strong>${c.gender || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Blood Group</span><br><strong>${c.blood_group || 'N/A'}</strong></div>
            </div>
            
            <h4 style="margin:25px 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Corporate Allocation</h4>
            <div class="grid-3" style="gap:20px; font-size:0.9rem;">
                <div><span style="color:#64748b; font-size:0.8rem;">Branch</span><br><strong>${c.branch_name || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Department</span><br><strong>${c.department || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Shift</span><br><strong>${c.shift || 'General'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Employment Type</span><br><strong>${c.employment_type || 'Permanent'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Status</span><br><strong style="color:#10b981;">${c.status || 'Active'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Verification</span><br><strong>${c.verification_status || 'Pending'}</strong></div>
            </div>
        `;
    } 
    else if (tabName === 'docs') {
        html = `<h4 style="margin:0 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Uploaded Documents</h4>`;
        if(p.documents.length === 0) html += `<div style="padding:20px; color:#64748b;">No documents uploaded yet.</div>`;
        p.documents.forEach(d => {
            html += `
                <div style="padding:15px; border:1px solid #e2e8f0; border-radius:8px; margin-bottom:10px; display:flex; justify-content:space-between; align-items:center;">
                    <div>
                        <div style="font-weight:600; color:#0f172a;">${d.document_type}</div>
                        <div style="font-size:0.8rem; color:#64748b;">Uploaded: ${d.uploaded_at}</div>
                    </div>
                    <span style="padding:4px 8px; background:#f1f5f9; border-radius:4px; font-size:0.8rem; font-weight:600; color:#475569;">${d.status}</span>
                </div>
            `;
        });
    }
    else if (tabName === 'finance') {
        const b = p.bank;
        const s = p.salary;
        html = `
            <h4 style="margin:0 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Bank & Statutory Details</h4>
            <div class="grid-2" style="gap:20px; font-size:0.9rem; margin-bottom:25px;">
                <div><span style="color:#64748b; font-size:0.8rem;">Bank Name</span><br><strong>${b.bank_name || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">Account Number</span><br><strong>${b.account_number || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">IFSC Code</span><br><strong>${b.ifsc_code || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">PAN Number</span><br><strong>${b.pan_number || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">UAN Number</span><br><strong>${b.uan_number || 'N/A'}</strong></div>
                <div><span style="color:#64748b; font-size:0.8rem;">ESIC Number</span><br><strong>${b.esic_number || 'N/A'}</strong></div>
            </div>

            <h4 style="margin:0 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Salary Structure</h4>
            <div style="padding:20px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; font-size:0.9rem;">
                <div style="display:flex; justify-content:space-between; margin-bottom:10px;"><span>Basic Salary:</span> <strong>₹${s.basic_salary || '0.00'}</strong></div>
                <div style="display:flex; justify-content:space-between; margin-bottom:10px;"><span>HRA:</span> <strong>₹${s.hra || '0.00'}</strong></div>
                <div style="display:flex; justify-content:space-between; margin-bottom:10px;"><span>Special Allowance:</span> <strong>₹${s.special_allowance || '0.00'}</strong></div>
                <hr style="border:0; border-top:1px solid #cbd5e1; margin:10px 0;">
                <div style="display:flex; justify-content:space-between; font-size:1.1rem; color:#10b981;"><span>Net Payable:</span> <strong>₹${s.net_salary || '0.00'}</strong></div>
            </div>
        `;
    }
    else if (tabName === 'logs') {
        html = `<h4 style="margin:0 0 15px; color:#3b82f6; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">Recent Activity Logs</h4>`;
        if(p.logs.length === 0) html += `<div style="padding:20px; color:#64748b;">No recent activity found.</div>`;
        
        let timeline = '<div style="border-left:2px solid #e2e8f0; margin-left:10px; padding-left:20px;">';
        p.logs.forEach(l => {
            timeline += `
                <div style="position:relative; margin-bottom:20px;">
                    <div style="position:absolute; left:-27px; top:3px; width:12px; height:12px; border-radius:50%; background:#2563eb; border:2px solid #fff;"></div>
                    <div style="font-weight:600; color:#0f172a; font-size:0.9rem;">${l.action}</div>
                    <div style="font-size:0.75rem; color:#64748b;">${l.created_at} · IP: ${l.ip_address}</div>
                </div>
            `;
        });
        timeline += '</div>';
        html += timeline;
    }

    document.getElementById('profContentArea').innerHTML = html;
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>
