<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once __DIR__ . '/includes/settings_helpers.php';

session_start();
if (empty($_SESSION['authenticated'])) {
    header("Location: signin.php");
    exit();
}
require_once __DIR__ . '/db.php';

$success = false;
$errorMessage = '';
$errorList = [];
$flashMessage = '';
if (isset($_SESSION['flash_ok'])) {
    $flashMessage = $_SESSION['flash_ok'];
    unset($_SESSION['flash_ok']);
}
$flashError = '';
if (isset($_SESSION['flash_err'])) {
    $flashError = $_SESSION['flash_err'];
    unset($_SESSION['flash_err']);
}

$result = $conn->query("SELECT * FROM organizations ORDER BY id DESC LIMIT 1");
$row = $result ? $result->fetch_assoc() : null;
$orgName = $_SESSION['org_name'] ?? ($row['organisation_name'] ?? 'demo');
$displayName = $_SESSION['username'] ?? $orgName;
$orgId   = $_SESSION['org_id'] ?? ($row['organisation_id'] ?? ($row['id'] ?? '60066881652'));
$orgIdInt = (int) ($row['id'] ?? (ctype_digit((string) $orgId) ? $orgId : 0));
settings_ensure_employee_organization_column($conn, $orgIdInt);
settings_ensure_audit_tables($conn);
$states = settings_get_states_for_country($conn, $row['business_location'] ?? 'India');
$trialStatus = strtoupper($_SESSION['org_status'] ?? ($row['status'] ?? 'TRIAL'));
$userEmail = $_SESSION['user'] ?? 'user@example.com';
date_default_timezone_set('Asia/Kolkata');
$bodyClasses = 'dash-page';
$employeeName = $_GET['emp'] ?? 'balachandar5';
$step = $_GET['step'] ?? 'list';
$validSteps = ['list', 'basic', 'salary', 'personal', 'payment'];
if (!in_array($step, $validSteps, true)) {
    $step = 'list';
}

function pick_field($row, $candidates) {
    foreach ($candidates as $field) {
        if (array_key_exists($field, $row) && $row[$field] !== null && $row[$field] !== '') {
            return $row[$field];
        }
    }
    return null;
}

function employees_has_organization_id(mysqli $conn): bool {
    static $hasColumn = null;
    if ($hasColumn !== null) {
        return $hasColumn;
    }

    $result = $conn->query("SHOW COLUMNS FROM employees LIKE 'organization_id'");
    $hasColumn = (bool) ($result && $result->num_rows > 0);
    return $hasColumn;
}

function employees_ensure_salary_columns(mysqli $conn): void {
    static $ensured = false;
    if ($ensured) {
        return;
    }

    $existing = [];
    $result = $conn->query("SHOW COLUMNS FROM employees");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $existing[] = $row['Field'];
        }
    }

    $needed = [
        'house_rent_allowance_enabled' => "ALTER TABLE employees ADD COLUMN house_rent_allowance_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER fixed_allowance_annual",
        'house_rent_allowance_percent' => "ALTER TABLE employees ADD COLUMN house_rent_allowance_percent DECIMAL(10,2) DEFAULT 50.00 AFTER house_rent_allowance_enabled",
        'house_rent_allowance_monthly' => "ALTER TABLE employees ADD COLUMN house_rent_allowance_monthly DECIMAL(12,2) DEFAULT NULL AFTER house_rent_allowance_percent",
        'house_rent_allowance_annual' => "ALTER TABLE employees ADD COLUMN house_rent_allowance_annual DECIMAL(12,2) DEFAULT NULL AFTER house_rent_allowance_monthly",
        'conveyance_allowance_enabled' => "ALTER TABLE employees ADD COLUMN conveyance_allowance_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER house_rent_allowance_annual",
        'conveyance_allowance_monthly' => "ALTER TABLE employees ADD COLUMN conveyance_allowance_monthly DECIMAL(12,2) DEFAULT NULL AFTER conveyance_allowance_enabled",
        'conveyance_allowance_annual' => "ALTER TABLE employees ADD COLUMN conveyance_allowance_annual DECIMAL(12,2) DEFAULT NULL AFTER conveyance_allowance_monthly",
    ];

    foreach ($needed as $column => $sql) {
        if (!in_array($column, $existing, true)) {
            $conn->query($sql);
        }
    }

    $ensured = true;
}

function employees_ensure_payment_columns(mysqli $conn): void {
    static $ensured = false;
    if ($ensured) {
        return;
    }

    $existing = [];
    $result = $conn->query("SHOW COLUMNS FROM employees");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $existing[] = $row['Field'];
        }
    }

    $needed = [
        'account_holder_name' => "ALTER TABLE employees ADD COLUMN account_holder_name VARCHAR(190) DEFAULT NULL AFTER payment_method",
        'bank_name' => "ALTER TABLE employees ADD COLUMN bank_name VARCHAR(190) DEFAULT NULL AFTER account_holder_name",
        'account_number' => "ALTER TABLE employees ADD COLUMN account_number VARCHAR(80) DEFAULT NULL AFTER bank_name",
        'ifsc_code' => "ALTER TABLE employees ADD COLUMN ifsc_code VARCHAR(30) DEFAULT NULL AFTER account_number",
        'bank_account_type' => "ALTER TABLE employees ADD COLUMN bank_account_type VARCHAR(30) DEFAULT NULL AFTER ifsc_code",
    ];

    foreach ($needed as $column => $sql) {
        if (!in_array($column, $existing, true)) {
            $conn->query($sql);
        }
    }

    $ensured = true;
}

function build_full_name($row) {
    $full = pick_field($row, ['full_name']);
    if ($full) {
        return $full;
    }
    $first = pick_field($row, ['first_name', 'firstname']);
    $middle = pick_field($row, ['middle_name', 'middlename']);
    $last = pick_field($row, ['last_name', 'lastname']);
    $parts = array_filter([$first, $middle, $last]);
    return $parts ? implode(' ', $parts) : null;
}

function build_emp_code($row) {
    return pick_field($row, ['employee_code', 'employee_id', 'emp_code']);
}

function build_work_email($row) {
    return pick_field($row, ['work_email', 'email', 'office_email']);
}

function build_department($row) {
    return pick_field($row, ['department', 'dept_name']);
}

function build_designation($row) {
    return pick_field($row, ['designation', 'job_title']);
}

function employees_fetch_row(mysqli $conn, int $employeeId, int $organizationId): ?array {
    $hasOrg = employees_has_organization_id($conn);
    $sql = $hasOrg
        ? "SELECT * FROM employees WHERE id = ? AND organization_id = ? LIMIT 1"
        : "SELECT * FROM employees WHERE id = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return null;
    }

    if ($hasOrg) {
        $stmt->bind_param('ii', $employeeId, $organizationId);
    } else {
        $stmt->bind_param('i', $employeeId);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return $row ?: null;
}

function employees_fetch_salary_hold_entries(mysqli $conn, int $organizationId, int $employeeId): array {
    $rows = [];
    $stmt = $conn->prepare(
        "SELECT * FROM employee_salary_holds
         WHERE organization_id = ? AND employee_id = ?
         ORDER BY created_at DESC, id DESC"
    );
    if (!$stmt) {
        return $rows;
    }

    $stmt->bind_param('ii', $organizationId, $employeeId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($result && ($row = $result->fetch_assoc())) {
        $rows[] = $row;
    }
    $stmt->close();

    return $rows;
}

function load_dropdown_values(mysqli $conn, string $sql, $orgId, string $type = 'i'): array {
    $values = [];
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param($type, $orgId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($result && ($row = $result->fetch_assoc())) {
            $value = trim((string) ($row['value'] ?? ''));
            if ($value !== '') {
                $values[] = $value;
            }
        }
        $stmt->close();
    }

    $values = array_values(array_unique($values));
    sort($values, SORT_NATURAL | SORT_FLAG_CASE);
    return $values;
}

function render_employee_combo_field(
    string $name,
    string $label,
    string $value,
    array $options,
    string $manageHref,
    string $manageLabel,
    string $placeholder = 'Select'
): void {
    $comboId = 'combo_' . preg_replace('/[^a-z0-9_]+/i', '_', $name);
    $displayValue = $value !== '' ? $value : $placeholder;
    ?>
    <div class="combo-select" data-combo-root="<?php echo htmlspecialchars($comboId); ?>">
        <input type="hidden" name="<?php echo htmlspecialchars($name); ?>" value="<?php echo htmlspecialchars($value); ?>" data-combo-value>
        <button type="button" class="combo-trigger" data-combo-trigger aria-haspopup="listbox" aria-expanded="false">
            <span class="combo-trigger__text" data-combo-label><?php echo htmlspecialchars($displayValue); ?></span>
            <span class="combo-trigger__actions">
                <span class="combo-clear" data-combo-clear role="button" tabindex="0" aria-label="Clear selection" title="Clear selection">×</span>
                <span class="combo-arrow" aria-hidden="true"><i class="fa-solid fa-chevron-down"></i></span>
            </span>
        </button>
        <div class="combo-panel" data-combo-panel hidden>
            <div class="combo-search">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" placeholder="Search" data-combo-search aria-label="<?php echo htmlspecialchars($label); ?> search">
            </div>
            <div class="combo-options" role="listbox">
                <?php if ($options): ?>
                    <?php foreach ($options as $option): ?>
                        <button type="button" class="combo-option<?php echo $value === $option ? ' is-selected' : ''; ?>" data-combo-option data-value="<?php echo htmlspecialchars($option); ?>">
                            <span><?php echo htmlspecialchars($option); ?></span>
                            <i class="fa-solid fa-check"></i>
                        </button>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="combo-empty">No options available</div>
                <?php endif; ?>
            </div>
            <button type="button" class="combo-add" data-open-master-modal="<?php echo htmlspecialchars($comboId); ?>">
                <i class="fa-solid fa-circle-plus"></i>
                <?php echo htmlspecialchars($manageLabel); ?>
            </button>
        </div>
    </div>
    <?php
}

function is_profile_incomplete($row) {
    $required = [
        build_full_name($row),
        build_emp_code($row),
        build_work_email($row),
        build_department($row),
        pick_field($row, ['designation']),
        pick_field($row, ['work_location']),
        pick_field($row, ['date_of_joining', 'join_date'])
    ];
    foreach ($required as $value) {
        if ($value === null || $value === '') {
            return true;
        }
    }
    return false;
}

function pick_first($row, $candidates) {
    foreach ($candidates as $field) {
        if (array_key_exists($field, $row)) {
            return $row[$field];
        }
    }
    return null;
}

function merge_employee_form_values(array $employee, array $post): array {
    $map = [
        'first_name' => ['first_name'],
        'middle_name' => ['middle_name'],
        'last_name' => ['last_name'],
        'employee_id' => ['employee_code'],
        'designation' => ['designation'],
        'department' => ['department'],
        'work_location' => ['work_location'],
        'join_date' => ['date_of_joining'],
        'date_of_leaving' => ['date_of_leaving'],
        'employment_type' => ['employment_type'],
        'email' => ['work_email', 'email'],
        'personal_email' => ['personal_email'],
        'mobile' => ['mobile_number', 'mobile'],
        'gender' => ['gender'],
        'dob' => ['dob', 'date_of_birth'],
        'age' => ['age'],
        'father_name' => ['father_name'],
        'pan' => ['pan', 'pan_number'],
        'abled_type' => ['abled_type'],
        'addr1' => ['addr1', 'address_line1'],
        'addr2' => ['addr2', 'address_line2'],
        'city' => ['city'],
        'state' => ['state'],
        'pin' => ['pin', 'pincode'],
        'annual_ctc' => ['annual_ctc'],
        'basic_percent' => ['basic_percent'],
        'basic_monthly' => ['basic_monthly'],
        'basic_annual' => ['basic_annual'],
        'fixed_allowance_monthly' => ['fixed_allowance_monthly'],
        'fixed_allowance_annual' => ['fixed_allowance_annual'],
        'house_rent_allowance_enabled' => ['house_rent_allowance_enabled'],
        'house_rent_allowance_percent' => ['house_rent_allowance_percent'],
        'house_rent_allowance_monthly' => ['house_rent_allowance_monthly'],
        'house_rent_allowance_annual' => ['house_rent_allowance_annual'],
        'conveyance_allowance_enabled' => ['conveyance_allowance_enabled'],
        'conveyance_allowance_monthly' => ['conveyance_allowance_monthly'],
        'conveyance_allowance_annual' => ['conveyance_allowance_annual'],
        'pay_method' => ['pay_method', 'payment_method'],
    ];

    foreach ($map as $postKey => $targets) {
        if (!array_key_exists($postKey, $post)) {
            continue;
        }

        $value = $post[$postKey];
        foreach ($targets as $target) {
            $employee[$target] = $value;
        }
    }

    if (array_key_exists('professional_tax', $post)) {
        $employee['professional_tax'] = $post['professional_tax'];
    }

    $fullName = trim(implode(' ', array_filter([
        trim((string) ($employee['first_name'] ?? '')),
        trim((string) ($employee['middle_name'] ?? '')),
        trim((string) ($employee['last_name'] ?? '')),
    ])));
    if ($fullName !== '') {
        $employee['full_name'] = $fullName;
    }

    return $employee;
}

employees_ensure_salary_columns($conn);
employees_ensure_payment_columns($conn);
settings_ensure_salary_hold_tables($conn);

if ($step === 'list') {
    $employees = [];
    if (employees_has_organization_id($conn)) {
        $stmt = $conn->prepare("SELECT * FROM employees WHERE organization_id = ? AND COALESCE(is_deleted, 0) = 0 ORDER BY id DESC");
        if ($stmt) {
            $stmt->bind_param('i', $orgIdInt);
            $stmt->execute();
            $empResult = $stmt->get_result();
            while ($empResult && ($empRow = $empResult->fetch_assoc())) {
                $employees[] = $empRow;
            }
            $stmt->close();
        }
    } else {
        $empResult = $conn->query("SELECT * FROM employees WHERE COALESCE(is_deleted, 0) = 0 ORDER BY id DESC");
        if ($empResult) {
            while ($empRow = $empResult->fetch_assoc()) {
                $employees[] = $empRow;
            }
        }
    }
}

$employee = null;
$currentEmployeeId = 0;
$employeeBenefits = [];
$salaryMode = 'edit';
if ($step !== 'list') {
    $employeeId = isset($_GET['emp_id']) ? (int)$_GET['emp_id'] : 0;
    $employeeKey = trim((string)($_GET['emp'] ?? ''));
    if ($employeeId > 0) {
        $sql = employees_has_organization_id($conn)
            ? "SELECT * FROM employees WHERE id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0"
            : "SELECT * FROM employees WHERE id = ? AND COALESCE(is_deleted, 0) = 0";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            if (employees_has_organization_id($conn)) {
                $stmt->bind_param('ii', $employeeId, $orgIdInt);
            } else {
                $stmt->bind_param('i', $employeeId);
            }
            $stmt->execute();
            $employee = $stmt->get_result()->fetch_assoc();
            $stmt->close();
        }
    } elseif ($employeeKey !== '') {
        $sql = employees_has_organization_id($conn)
            ? "SELECT * FROM employees WHERE organization_id = ? AND COALESCE(is_deleted, 0) = 0 AND (full_name = ? OR employee_code = ? OR employee_id = ?) LIMIT 1"
            : "SELECT * FROM employees WHERE COALESCE(is_deleted, 0) = 0 AND (full_name = ? OR employee_code = ? OR employee_id = ?) LIMIT 1";
        $stmt = $conn->prepare($sql);
        if ($stmt) {
            if (employees_has_organization_id($conn)) {
                $stmt->bind_param('isss', $orgIdInt, $employeeKey, $employeeKey, $employeeKey);
            } else {
                $stmt->bind_param('sss', $employeeKey, $employeeKey, $employeeKey);
            }
            $stmt->execute();
            $employee = $stmt->get_result()->fetch_assoc();
            $stmt->close();
        }
    }
}
if (!empty($employee) && !empty($employee['id'])) {
    $currentEmployeeId = (int)$employee['id'];
}
if (!$currentEmployeeId && isset($_POST['employee_db_id'])) {
    $currentEmployeeId = (int)$_POST['employee_db_id'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $employee = merge_employee_form_values($employee ?? [], $_POST);
}
if ($currentEmployeeId && $step === 'salary') {
    $benefitResult = $conn->query("SELECT * FROM employee_benefits WHERE employee_id = " . (int)$currentEmployeeId . " ORDER BY id DESC");
    if ($benefitResult) {
        while ($row = $benefitResult->fetch_assoc()) {
            $employeeBenefits[] = $row;
        }
    }
}
if ($step === 'salary') {
    $hasSalaryData = !empty(pick_field($employee ?? [], [
        'annual_ctc',
        'basic_percent',
        'basic_annual',
        'basic_monthly',
        'fixed_allowance_annual',
        'fixed_allowance_monthly',
        'house_rent_allowance_annual',
        'house_rent_allowance_monthly',
        'conveyance_allowance_annual',
        'conveyance_allowance_monthly'
    ]));
    $modeParam = $_GET['mode'] ?? '';
    $salaryMode = ($modeParam === 'edit' || !$hasSalaryData) ? 'edit' : 'summary';
}

$salaryHoldEntries = [];
if ($currentEmployeeId && $step === 'salary') {
    $salaryHoldEntries = employees_fetch_salary_hold_entries($conn, $orgIdInt, $currentEmployeeId);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['master_action'])) {
    $masterAction = (string) $_POST['master_action'];
    $returnStep = trim((string) ($_POST['return_step'] ?? 'basic'));
    $returnEmpId = (int) ($_POST['return_emp_id'] ?? 0);
    $returnUrl = 'employees.php?step=' . rawurlencode($returnStep ?: 'basic');
    if ($returnEmpId > 0) {
        $returnUrl .= '&emp_id=' . $returnEmpId;
    }

    if ($masterAction === 'create_designation') {
        $name = trim((string) ($_POST['designation_name'] ?? ''));
        if ($name === '') {
            $_SESSION['flash_err'] = 'Designation name is required.';
        } else {
            $stmt = $conn->prepare("INSERT INTO designations (organization_id, name) VALUES (?, ?)");
            if ($stmt) {
                $stmt->bind_param('is', $orgIdInt, $name);
                if ($stmt->execute()) {
                    $_SESSION['flash_ok'] = 'Designation saved successfully.';
                } else {
                    $_SESSION['flash_err'] = 'Unable to save designation. It may already exist.';
                }
                $stmt->close();
            } else {
                $_SESSION['flash_err'] = 'Unable to prepare designation save.';
            }
        }
    } elseif ($masterAction === 'create_department') {
        $name = trim((string) ($_POST['department_name'] ?? ''));
        $code = trim((string) ($_POST['department_code'] ?? ''));
        $desc = trim((string) ($_POST['department_desc'] ?? ''));
        if ($name === '') {
            $_SESSION['flash_err'] = 'Department name is required.';
        } else {
            $stmt = $conn->prepare("INSERT INTO departments (org_id, name, code, description) VALUES (?, ?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param('ssss', $orgId, $name, $code, $desc);
                if ($stmt->execute()) {
                    $_SESSION['flash_ok'] = 'Department saved successfully.';
                } else {
                    $_SESSION['flash_err'] = 'Unable to save department. It may already exist.';
                }
                $stmt->close();
            } else {
                $_SESSION['flash_err'] = 'Unable to prepare department save.';
            }
        }
    } elseif ($masterAction === 'create_work_location') {
        $locationName = trim((string) ($_POST['location_name'] ?? ''));
        $addressLine1 = trim((string) ($_POST['address_line1'] ?? ''));
        $addressLine2 = trim((string) ($_POST['address_line2'] ?? ''));
        $state = trim((string) ($_POST['state'] ?? ''));
        $city = trim((string) ($_POST['city'] ?? ''));
        $pincode = trim((string) ($_POST['pincode'] ?? ''));
        $isFilingAddress = isset($_POST['is_filing_address']) ? 1 : 0;

        if ($locationName === '') {
            $_SESSION['flash_err'] = 'Work location name is required.';
        } elseif ($addressLine1 === '') {
            $_SESSION['flash_err'] = 'Address line 1 is required.';
        } elseif ($state === '') {
            $_SESSION['flash_err'] = 'State is required.';
        } else {
            if ($isFilingAddress) {
                $reset = $conn->prepare("UPDATE work_locations SET is_filing_address = 0 WHERE organization_id = ?");
                if ($reset) {
                    $reset->bind_param('i', $orgIdInt);
                    $reset->execute();
                    $reset->close();
                }
            }
            $stmt = $conn->prepare(
                "INSERT INTO work_locations
                 (organization_id, location_name, address_line1, address_line2, state, city, pincode, is_filing_address)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
            );
            if ($stmt) {
                $stmt->bind_param('issssssi', $orgIdInt, $locationName, $addressLine1, $addressLine2, $state, $city, $pincode, $isFilingAddress);
                if ($stmt->execute()) {
                    $_SESSION['flash_ok'] = 'Work location saved successfully.';
                } else {
                    $_SESSION['flash_err'] = 'Unable to save work location. It may already exist.';
                }
                $stmt->close();
            } else {
                $_SESSION['flash_err'] = 'Unable to prepare work location save.';
            }
        }
    }

    header('Location: ' . $returnUrl);
    exit();
}

$designationOptions = load_dropdown_values(
    $conn,
    "SELECT name AS value FROM designations WHERE organization_id = ? ORDER BY name ASC",
    $orgIdInt,
    'i'
);
$departmentOptions = load_dropdown_values(
    $conn,
    "SELECT name AS value FROM departments WHERE org_id = ? ORDER BY name ASC",
    $orgId,
    's'
);
$workLocationOptions = load_dropdown_values(
    $conn,
    "SELECT location_name AS value FROM work_locations WHERE organization_id = ? ORDER BY is_filing_address DESC, location_name ASC",
    $orgIdInt,
    'i'
);

if (!empty($employee['designation']) && !in_array($employee['designation'], $designationOptions, true)) {
    $designationOptions[] = $employee['designation'];
}
if (!empty($employee['department']) && !in_array($employee['department'], $departmentOptions, true)) {
    $departmentOptions[] = $employee['department'];
}
if (!empty($employee['work_location']) && !in_array($employee['work_location'], $workLocationOptions, true)) {
    $workLocationOptions[] = $employee['work_location'];
}

sort($designationOptions, SORT_NATURAL | SORT_FLAG_CASE);
sort($departmentOptions, SORT_NATURAL | SORT_FLAG_CASE);
sort($workLocationOptions, SORT_NATURAL | SORT_FLAG_CASE);

if ($step !== 'basic' && $step !== 'list' && $currentEmployeeId === 0) {
    $_SESSION['flash_err'] = 'Please complete Basic Details first.';
    header("Location: employees.php?step=basic");
    exit();
}

$benefitErrors = [];
$benefitSuccess = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['benefit_submit'])) {
    $benefitName = trim((string)($_POST['benefit_name'] ?? ''));
    $benefitPlan = trim((string)($_POST['benefit_plan'] ?? ''));
    $associateInvestment = trim((string)($_POST['associate_investment'] ?? ''));
    $contributionBasis = trim((string)($_POST['contribution_basis'] ?? ''));
    $employerContribution = trim((string)($_POST['employer_contribution_amount'] ?? ''));
    $contributionType = trim((string)($_POST['contribution_type'] ?? ''));
    $totalAmount = trim((string)($_POST['total_amount_to_deduct'] ?? ''));

    if ($benefitName === '') {
        $benefitErrors[] = 'Please enter a benefit name.';
    }
    if ($benefitPlan === '') {
        $benefitErrors[] = 'Please select a benefit plan.';
    }
    if ($employerContribution !== '' && !is_numeric($employerContribution)) {
        $benefitErrors[] = 'Employer contribution must be a number.';
    }
    if ($totalAmount !== '' && !is_numeric($totalAmount)) {
        $benefitErrors[] = 'Total amount to deduct must be a number.';
    }
    if (empty($benefitErrors)) {
        $includeEmployer = isset($_POST['include_employer_contribution']) ? 1 : 0;
        $isSuper = isset($_POST['is_superannuation']) ? 1 : 0;
        $stmt = $conn->prepare("INSERT INTO employee_benefits
            (employee_id, benefit_name, benefit_plan, include_employer_contribution, is_superannuation, associate_investment, contribution_basis, employer_contribution_amount, contribution_type, total_amount_to_deduct)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            $empIdForBenefit = (int)$currentEmployeeId;
            $employerContributionVal = $employerContribution === '' ? null : (float)$employerContribution;
            $totalAmountVal = $totalAmount === '' ? null : (float)$totalAmount;
            $stmt->bind_param(
                'issiiissss',
                $empIdForBenefit,
                $benefitName,
                $benefitPlan,
                $includeEmployer,
                $isSuper,
                $associateInvestment,
                $contributionBasis,
                $employerContributionVal,
                $contributionType,
                $totalAmountVal
            );
            if ($stmt->execute()) {
                $benefitSuccess = 'Benefit added successfully.';
            } else {
                $benefitErrors[] = 'Unable to save benefit. ' . $stmt->error;
            }
            $stmt->close();
        } else {
            $benefitErrors[] = 'Unable to prepare benefit save.';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_salary_hold'])) {
    $salaryEmployeeId = isset($_POST['employee_db_id']) ? (int) $_POST['employee_db_id'] : $currentEmployeeId;
    $salaryMonthFrom = trim((string) ($_POST['salary_month_from'] ?? ''));
    $salaryMonthTo = trim((string) ($_POST['salary_month_to'] ?? ''));
    $releaseMonth = trim((string) ($_POST['release_month'] ?? ''));
    $holdStatus = trim((string) ($_POST['hold_status'] ?? 'pending'));
    $approvalStatus = trim((string) ($_POST['approval_status'] ?? 'pending'));
    $holdReason = trim((string) ($_POST['hold_reason'] ?? ''));
    $notes = trim((string) ($_POST['salary_hold_notes'] ?? ''));

    if ($salaryEmployeeId <= 0) {
        $_SESSION['flash_err'] = 'Select an employee before saving salary hold details.';
        header('Location: employees.php?step=list');
        exit();
    }

    if ($salaryMonthFrom === '' || $salaryMonthTo === '') {
        $_SESSION['flash_err'] = 'Select both hold months before saving salary hold details.';
        $redirect = 'employees.php?step=salary&emp_id=' . urlencode((string) $salaryEmployeeId);
        header('Location: ' . $redirect);
        exit();
    }

    $approvedBy = null;
    $approvedAt = null;
    $releasedBy = null;
    $releasedAt = null;
    if ($approvalStatus === 'approved') {
        $approvedBy = (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system');
        $approvedAt = date('Y-m-d H:i:s');
    }
    if ($holdStatus === 'released') {
        $releasedBy = (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system');
        $releasedAt = date('Y-m-d H:i:s');
    }

    if (settings_save_salary_hold_entry(
        $conn,
        $orgIdInt,
        $salaryEmployeeId,
        $salaryMonthFrom,
        $salaryMonthTo,
        $releaseMonth !== '' ? $releaseMonth : null,
        in_array($holdStatus, ['pending', 'held', 'released', 'approved'], true) ? $holdStatus : 'pending',
        in_array($approvalStatus, ['pending', 'approved', 'rejected'], true) ? $approvalStatus : 'pending',
        $holdReason !== '' ? $holdReason : null,
        (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
        $notes !== '' ? $notes : null,
        $approvedBy,
        $releasedBy,
        $approvedAt,
        $releasedAt
    )) {
        $_SESSION['flash_ok'] = 'Salary hold saved successfully.';
    } else {
        $_SESSION['flash_err'] = 'Unable to save salary hold details.';
    }

    $redirect = 'employees.php?step=salary&emp_id=' . urlencode((string) $salaryEmployeeId);
    header('Location: ' . $redirect);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    if ($step !== 'basic') {
        $success = true;
    } else {
        $trim = function ($value) {
            return is_string($value) ? trim($value) : $value;
        };
        $firstNameInput = $trim($_POST['first_name'] ?? '');
        $employeeIdInput = $trim($_POST['employee_id'] ?? '');
        $joinDateInput = $trim($_POST['join_date'] ?? '');
        $emailInput = $trim($_POST['email'] ?? '');
        $genderInput = $trim($_POST['gender'] ?? '');
        $workLocationInput = $trim($_POST['work_location'] ?? '');
        $designationInput = $trim($_POST['designation'] ?? '');
        $departmentInput = $trim($_POST['department'] ?? '');

        $columns = [];
        $colResult = $conn->query("DESCRIBE employees");
        if ($colResult) {
            while ($col = $colResult->fetch_assoc()) {
                $columns[] = $col['Field'];
            }
        }

        if ($firstNameInput === '') {
            $errorList[] = "Enter the employee's first name.";
        }
        if ($employeeIdInput === '') {
            $errorList[] = 'Specify a unique employee ID.';
        } else {
            $idFields = [];
            foreach (['employee_code', 'employee_id', 'emp_code'] as $candidate) {
                if (in_array($candidate, $columns, true)) {
                    $idFields[] = $candidate;
                }
            }
            if (!empty($idFields)) {
                $whereParts = [];
                foreach ($idFields as $field) {
                    $whereParts[] = "`{$field}` = ?";
                }
                $whereSql = implode(' OR ', $whereParts);
                $sql = "SELECT id FROM employees WHERE ({$whereSql})";
                $params = array_fill(0, count($idFields), $employeeIdInput);
                $types = str_repeat('s', count($idFields));
                if (employees_has_organization_id($conn)) {
                    $sql .= " AND organization_id = ?";
                    $params[] = $orgIdInt;
                    $types .= 'i';
                }
                if ($currentEmployeeId > 0) {
                    $sql .= " AND id <> ?";
                    $params[] = $currentEmployeeId;
                    $types .= 'i';
                }
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $bindParams = [$types];
                    foreach ($params as $index => $value) {
                        $params[$index] = $value;
                        $bindParams[] = &$params[$index];
                    }
                    call_user_func_array([$stmt, 'bind_param'], $bindParams);
                    $stmt->execute();
                    $stmt->store_result();
                    if ($stmt->num_rows > 0) {
                        $errorList[] = 'Employee ID already exists. Please use a unique ID.';
                    }
                    $stmt->close();
                }
            }
        }
        if ($emailInput === '' || !filter_var($emailInput, FILTER_VALIDATE_EMAIL)) {
            $errorList[] = 'Enter a valid Work Email address.';
        }
        if ($genderInput === '') {
            $errorList[] = 'Select the gender of the employee.';
        }
        if ($joinDateInput === '') {
            $errorList[] = 'Enter a Date of Joining.';
        }
        if ($workLocationInput === '') {
            $errorList[] = 'Select a Work Location.';
        }
        if ($designationInput === '') {
            $errorList[] = 'Select a designation.';
        }
        if ($departmentInput === '') {
            $errorList[] = 'Select a department.';
        }

        if (!empty($errorList)) {
            $errorMessage = 'Oops! Looks like you missed something...';
        } else {
        $clean = function ($value) {
            $value = is_string($value) ? trim($value) : $value;
            return $value === '' ? null : $value;
        };

        $payload = [];
        $addIfSet = function ($column, $postKey) use (&$payload, $clean) {
            if (array_key_exists($postKey, $_POST)) {
                $payload[$column] = $clean($_POST[$postKey]);
            }
        };

        $addIfSet('first_name', 'first_name');
        $addIfSet('middle_name', 'middle_name');
        $addIfSet('last_name', 'last_name');
        $addIfSet('employee_code', 'employee_id');
        $addIfSet('designation', 'designation');
        $addIfSet('department', 'department');
        $addIfSet('work_location', 'work_location');
        $addIfSet('date_of_joining', 'join_date');
        $addIfSet('date_of_leaving', 'date_of_leaving');
        $addIfSet('employment_type', 'employment_type');
        $addIfSet('work_email', 'email');
        $addIfSet('personal_email', 'personal_email');
        $addIfSet('gender', 'gender');

        $addIfSet('date_of_birth', 'dob');
        $addIfSet('dob', 'dob');
        $addIfSet('age', 'age');
        $addIfSet('father_name', 'father_name');
        $addIfSet('pan', 'pan');
        $addIfSet('abled_type', 'abled_type');
        $addIfSet('addr1', 'addr1');
        $addIfSet('address_line1', 'addr1');
        $addIfSet('addr2', 'addr2');
        $addIfSet('address_line2', 'addr2');
        $addIfSet('city', 'city');
        $addIfSet('state', 'state');
        $addIfSet('pin', 'pin');
        $addIfSet('pincode', 'pin');
        $addIfSet('postal_code', 'pin');

        $addIfSet('annual_ctc', 'annual_ctc');
        $addIfSet('basic_percent', 'basic_percent');
        $addIfSet('basic_monthly', 'basic_monthly');
        $addIfSet('basic_annual', 'basic_annual');
        $addIfSet('fixed_allowance_monthly', 'fixed_allowance_monthly');
        $addIfSet('fixed_allowance_annual', 'fixed_allowance_annual');
        $payload['house_rent_allowance_enabled'] = (isset($_POST['house_rent_allowance_enabled']) && $_POST['house_rent_allowance_enabled'] === '1') ? 1 : 0;
        $addIfSet('house_rent_allowance_percent', 'house_rent_allowance_percent');
        $addIfSet('house_rent_allowance_monthly', 'house_rent_allowance_monthly');
        $addIfSet('house_rent_allowance_annual', 'house_rent_allowance_annual');
        $payload['conveyance_allowance_enabled'] = (isset($_POST['conveyance_allowance_enabled']) && $_POST['conveyance_allowance_enabled'] === '1') ? 1 : 0;
        $addIfSet('conveyance_allowance_monthly', 'conveyance_allowance_monthly');
        $addIfSet('conveyance_allowance_annual', 'conveyance_allowance_annual');

        $addIfSet('pay_method', 'pay_method');
        $addIfSet('payment_method', 'pay_method');
        $addIfSet('account_holder_name', 'account_holder_name');
        $addIfSet('bank_name', 'bank_name');
        $addIfSet('account_number', 'account_number');
        $addIfSet('ifsc_code', 'ifsc_code');
        $addIfSet('bank_account_type', 'bank_account_type');
        if (array_key_exists('professional_tax', $_POST)) {
            $payload['professional_tax'] = $_POST['professional_tax'] === '1' ? 1 : 0;
        }

        if (array_key_exists('first_name', $_POST) || array_key_exists('middle_name', $_POST) || array_key_exists('last_name', $_POST)) {
            $firstName = $clean($_POST['first_name'] ?? null);
            $middleName = $clean($_POST['middle_name'] ?? null);
            $lastName = $clean($_POST['last_name'] ?? null);
            $fullName = trim(implode(' ', array_filter([$firstName, $middleName, $lastName])));
            $payload['full_name'] = $fullName === '' ? null : $fullName;
        }

        $mobileValue = $clean($_POST['mobile'] ?? null);
        if ($mobileValue !== null) {
            $mobileColumn = null;
            foreach (['mobile_number', 'mobile_no', 'mobile', 'mobile_phone', 'mobile_r'] as $candidate) {
                if (in_array($candidate, $columns, true)) {
                    $mobileColumn = $candidate;
                    break;
                }
            }
            if ($mobileColumn) {
                $payload[$mobileColumn] = $mobileValue;
            }
        }

        $insertColumns = [];
        $insertValues = [];
        foreach ($payload as $column => $value) {
            if (in_array($column, $columns, true)) {
                $insertColumns[] = $column;
                $insertValues[] = $value;
            }
        }

        if (employees_has_organization_id($conn) && in_array('organization_id', $columns, true) && !in_array('organization_id', $insertColumns, true)) {
            $insertColumns[] = 'organization_id';
            $insertValues[] = $orgIdInt;
        }

        if (!$insertColumns) {
            $errorMessage = 'No matching employee columns found to save.';
        } else {
            $existingId = isset($_POST['employee_db_id']) ? (int)$_POST['employee_db_id'] : 0;
            $historyOld = $existingId > 0 ? employees_fetch_row($conn, $existingId, $orgIdInt) : null;
            $historyAction = $existingId > 0 ? 'updated' : 'created';
            if ($existingId > 0 && in_array('id', $columns, true)) {
                $setParts = [];
                foreach ($insertColumns as $column) {
                    $setParts[] = "`{$column}` = ?";
                }
                $setSql = implode(', ', $setParts);
                $sql = employees_has_organization_id($conn)
                    ? "UPDATE employees SET {$setSql} WHERE id = ? AND organization_id = ?"
                    : "UPDATE employees SET {$setSql} WHERE id = ?";
                $stmt = $conn->prepare($sql);
                if (!$stmt) {
                    $errorMessage = 'Unable to prepare employee update.';
                } else {
                    $types = str_repeat('s', count($insertValues)) . 'i';
                    if (employees_has_organization_id($conn)) {
                        $types .= 'i';
                    }
                    $bindParams = [$types];
                    foreach ($insertValues as $index => $value) {
                        $insertValues[$index] = $value;
                        $bindParams[] = &$insertValues[$index];
                    }
                    $bindParams[] = &$existingId;
                    if (employees_has_organization_id($conn)) {
                        $bindParams[] = &$orgIdInt;
                    }
                    call_user_func_array([$stmt, 'bind_param'], $bindParams);
                if ($stmt->execute()) {
                    $success = true;
                    $currentEmployeeId = $existingId;
                    $historyNew = employees_fetch_row($conn, $existingId, $orgIdInt);
                    settings_log_employee_history(
                        $conn,
                        $orgIdInt,
                        $existingId,
                        $step,
                        $historyAction,
                        (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
                        $historyOld,
                        $historyNew
                    );
                } else {
                        $errorMessage = 'Unable to update employee. ' . $stmt->error;
                    }
                    $stmt->close();
                }
            } else {
                $colSql = implode(', ', array_map(fn($c) => "`{$c}`", $insertColumns));
                $placeholders = implode(', ', array_fill(0, count($insertColumns), '?'));
                $stmt = $conn->prepare("INSERT INTO employees ({$colSql}) VALUES ({$placeholders})");
                if (!$stmt) {
                    $errorMessage = 'Unable to prepare employee save.';
                } else {
                    $types = str_repeat('s', count($insertValues));
                    $bindParams = [$types];
                    foreach ($insertValues as $index => $value) {
                        $insertValues[$index] = $value;
                        $bindParams[] = &$insertValues[$index];
                    }
                    call_user_func_array([$stmt, 'bind_param'], $bindParams);
                    if ($stmt->execute()) {
                        $success = true;
                        $currentEmployeeId = (int)$stmt->insert_id;
                        $historyNew = employees_fetch_row($conn, $currentEmployeeId, $orgIdInt);
                        settings_log_employee_history(
                            $conn,
                            $orgIdInt,
                            $currentEmployeeId,
                            $step,
                            $historyAction,
                            (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
                            null,
                            $historyNew
                        );
                    } else {
                        $errorMessage = 'Unable to save employee. ' . $stmt->error;
                    }
                    $stmt->close();
                }
            }
        }
            if ($success) {
                $_SESSION['flash_ok'] = 'Employee saved successfully.';
                $nextStep = $step;
                if ($step === 'basic') {
                    $nextStep = 'salary';
                } elseif ($step === 'salary') {
                    $nextStep = 'personal';
                } elseif ($step === 'personal') {
                    $nextStep = 'payment';
                } elseif ($step === 'payment') {
                    $nextStep = 'list';
                }
                if ($nextStep === 'list') {
                    header("Location: employees.php?step=list");
                } else {
                    $suffix = $currentEmployeeId ? ('&emp_id=' . urlencode($currentEmployeeId)) : '';
                    header("Location: employees.php?step={$nextStep}{$suffix}");
                }
                exit();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Profile</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="employees.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="<?php echo htmlspecialchars($bodyClasses); ?>">
<div class="dash-layout">
    <aside class="dash-sidebar">
        <div class="sidebar-brand">
            <img src="images/b2l_mobitech_pvt_ltd_logo.jpg" class="logo" alt="B2L Mobitech Pvt Ltd">
        </div>

        <div class="sidebar-scroll">
            <div class="sidebar-section">
                <div class="getting-started">
                    <div class="gs-top">
                        <i class="fa-solid fa-rocket-launch"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill"></div>
                    </div>
                </div>
            </div>
            <nav class="sidebar-nav">
                <a class="nav-item" href="dashboard.php"><i class="fa-solid fa-gauge-high"></i><span>Dashboard</span></a>
                <a class="nav-item active" href="employees.php"><i class="fa-solid fa-users"></i><span>Employees</span></a>
                <a class="nav-item" href="payruns.php"><i class="fa-solid fa-money-bill-wave"></i><span>Pay Runs</span></a>
                <div class="nav-group">
                    <button class="nav-item btn" type="button" data-nav-toggle><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
                    <div class="nav-sub">
                        <a class="nav-sub-item" href="reimbursements.php">Reimbursements</a>
                        <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
                        <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
                        <a class="nav-sub-item" href="salary_holds.php">Salary Holds</a>
                    </div>
                </div>
                <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="nav-item" href="loans.php"><i class="fa-solid fa-hand-holding-dollar"></i><span>Loans</span></a>
                <a class="nav-item" href="giving.php"><i class="fa-solid fa-gift"></i><span>Giving</span></a>
                <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a class="nav-item" href="reports.php"><i class="fa-solid fa-chart-pie"></i><span>Reports</span></a>
                <a class="nav-item" href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>

        <div class="sidebar-footer">
            <a class="support-link" href="#">Contact Support</a>
        </div>
        <div class="support-tile">
            <div class="support-title">Track TDS Liabilities and Generate Form 24Q</div>
            <a class="support-action" href="#">View Details</a>
        </div>
    </aside>

    <main class="dash-main">
        <header class="dash-topbar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass search-icon"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="topbar-actions">
                <span class="trial">Your trial expires in 2 day(s). <a href="dashboard.php?modal=upgrade" class="upgrade-link">Upgrade</a></span>
                <a class="pill ghost org-toggle" href="dashboard.php?drawer=org" data-tooltip="Organisation menu"><span class="pill-label"><?php echo htmlspecialchars($orgName ?: 'demo'); ?></span><i class="fa-solid fa-angle-down"></i></a>
                <a class="top-icon icon-btn" href="dashboard.php?drawer=notif" data-tooltip="Notifications"><i class="fa-regular fa-bell"></i></a>
                <a class="top-icon top-link" href="settings.php" data-tooltip="Settings"><i class="fa-solid fa-gear"></i></a>
                <a class="top-icon icon-btn app-menu" href="dashboard.php?drawer=apps" data-tooltip="Apps"><i class="fa-solid fa-table-cells-large"></i></a>
                <a class="top-icon icon-btn top-avatar" href="dashboard.php?drawer=profile" data-tooltip="Profile"><i class="fa-regular fa-circle-user"></i></a>
                <span class="avatar" data-tooltip="Profile"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
            </div>
        </header>

        <section class="dash-content">
            <?php if ($flashMessage) { ?>
                <div class="alert-ok"><i class="fa-solid fa-circle-check"></i><?php echo htmlspecialchars($flashMessage); ?></div>
            <?php } elseif ($flashError) { ?>
                <div class="alert-err"><?php echo htmlspecialchars($flashError); ?></div>
            <?php } elseif (!empty($errorList)) { ?>
                <div class="alert-err">
                    <div class="alert-err-title">
                        <?php echo htmlspecialchars($errorMessage); ?>
                        <button class="alert-close" type="button" onclick="this.parentElement.parentElement.style.display='none'">×</button>
                    </div>
                    <ul>
                        <?php foreach ($errorList as $err) { ?>
                            <li><?php echo htmlspecialchars($err); ?></li>
                        <?php } ?>
                    </ul>
                </div>
            <?php } elseif ($success) { ?>
                <div class="alert-ok"><i class="fa-solid fa-circle-check"></i>Details saved successfully.</div>
            <?php } elseif ($errorMessage) { ?>
                <div class="alert-err"><?php echo htmlspecialchars($errorMessage); ?></div>
            <?php } ?>

            <?php if ($step === 'list') { ?>
                <?php
                    $filter = $_GET['filter'] ?? '';
                    $allEmployees = $employees ?? [];
                    $incompleteCount = 0;
                    foreach ($allEmployees as $empRow) {
                        if (is_profile_incomplete($empRow)) {
                            $incompleteCount++;
                        }
                    }
                    if ($filter === 'incomplete') {
                        $employees = array_values(array_filter($allEmployees, function($row){
                            return is_profile_incomplete($row);
                        }));
                    }
                ?>
                <div class="emp-header">
                    <div class="emp-title-group">
                        <h2 class="emp-title"><?php echo $filter === 'incomplete' ? 'Incomplete Employees' : 'Active Employees'; ?></h2>
                        <button class="emp-title-btn" type="button"><i class="fa-solid fa-angle-down"></i></button>
                    </div>
                    <div class="emp-header-actions">
                        <?php if ($incompleteCount > 0) { ?>
                            <div class="banner-warn">
                                <i class="fa-solid fa-circle-exclamation"></i>
                                You have <?php echo $incompleteCount; ?> incomplete employee<?php echo $incompleteCount === 1 ? '' : 's'; ?>.
                                <a href="employees.php?step=list&filter=incomplete">View</a>
                            </div>
                        <?php } ?>
                        <?php if ($filter === 'incomplete') { ?>
                            <a class="btn-clear" href="employees.php?step=list">Clear Filter</a>
                        <?php } ?>
                        <a class="btn-add" href="employees.php?step=basic"><i class="fa-solid fa-plus"></i> Add</a>
                        <div class="more-actions">
                            <button class="btn-icon" type="button" data-open-actions onclick="(function(e){var m=document.getElementById('actionsMenu'); if(!m) return; var open=!m.classList.contains('open'); m.classList.toggle('open', open); m.style.display=open?'flex':'none'; if(e){e.stopPropagation();}})(event)"><i class="fa-solid fa-ellipsis"></i></button>
                            <div class="actions-menu" id="actionsMenu">
                                <button type="button" data-open-import onclick="(function(e){var im=document.getElementById('importModal'); var em=document.getElementById('exportModal'); var m=document.getElementById('actionsMenu'); if(em){em.classList.remove('open'); em.setAttribute('aria-hidden','true'); em.style.display='none';} if(im){im.classList.add('open'); im.setAttribute('aria-hidden','false'); im.style.display='flex';} if(m){m.classList.remove('open'); m.style.display='none';} if(e){e.stopPropagation();}})(event)"><i class="fa-solid fa-download"></i> Import Data</button>
                                <button type="button" data-open-export onclick="(function(e){var im=document.getElementById('importModal'); var em=document.getElementById('exportModal'); var m=document.getElementById('actionsMenu'); if(im){im.classList.remove('open'); im.setAttribute('aria-hidden','true'); im.style.display='none';} if(em){em.classList.add('open'); em.setAttribute('aria-hidden','false'); em.style.display='flex';} if(m){m.classList.remove('open'); m.style.display='none';} if(e){e.stopPropagation();}})(event)"><i class="fa-solid fa-upload"></i> Export Data</button>
                            </div>
                        </div>
                        <button class="btn-icon" type="button" data-open-filter><i class="fa-solid fa-filter"></i></button>
                        <button class="btn-icon btn-help" type="button" data-open-help>?</button>
                    </div>
                </div>

                <div class="emp-table-wrap">
                    <div class="bulk-toolbar is-hidden" id="bulkToolbar" aria-live="polite">
                        <div class="bulk-toolbar__left">
                            <div class="bulk-dropdown" data-bulk-dropdown>
                                <button type="button" class="bulk-btn" data-bulk-trigger>
                                    <span>Enable Portal</span>
                                    <span class="bulk-caret"><i class="fa-solid fa-chevron-down"></i></span>
                                </button>
                                <div class="bulk-menu" hidden>
                                    <button type="button" class="bulk-menu__item">Disable Portal</button>
                                </div>
                            </div>
                            <div class="bulk-dropdown" data-bulk-dropdown>
                                <button type="button" class="bulk-btn" data-bulk-trigger>
                                    <span>Release FBP Declaration</span>
                                    <span class="bulk-caret"><i class="fa-solid fa-chevron-down"></i></span>
                                </button>
                                <div class="bulk-menu" hidden>
                                    <button type="button" class="bulk-menu__item">Release FBP Declaration</button>
                                </div>
                            </div>
                            <div class="bulk-dropdown" data-bulk-dropdown>
                                <button type="button" class="bulk-btn" data-bulk-trigger>
                                    <span>Release IT Declaration</span>
                                    <span class="bulk-caret"><i class="fa-solid fa-chevron-down"></i></span>
                                </button>
                                <div class="bulk-menu" hidden>
                                    <button type="button" class="bulk-menu__item">Release IT Declaration</button>
                                </div>
                            </div>
                            <div class="bulk-dropdown" data-bulk-dropdown>
                                <button type="button" class="bulk-btn" data-bulk-trigger>
                                    <span>Release Proof Of Investments</span>
                                    <span class="bulk-caret"><i class="fa-solid fa-chevron-down"></i></span>
                                </button>
                                <div class="bulk-menu" hidden>
                                    <button type="button" class="bulk-menu__item">Release Proof Of Investments</button>
                                </div>
                            </div>
                        </div>
                        <div class="bulk-toolbar__right">
                            <span class="bulk-selected-count">
                                <span class="bulk-selected-count__num" id="selectedCount">0</span>
                                <span>Selected</span>
                            </span>
                            <span class="bulk-esc">Esc</span>
                            <button type="button" class="bulk-close" id="bulkClear">×</button>
                        </div>
                    </div>
                    <table class="emp-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" aria-label="Select all" id="selectAllEmployees"></th>
                                <th>Employee Name</th>
                                <th>Work Email</th>
                                <th>Department</th>
                                <th>Employee Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($employees)) { ?>
                                <?php foreach ($employees as $emp) { ?>
                                    <?php
                                        $empName = build_full_name($emp) ?: 'Employee';
                                        $empCode = build_emp_code($emp);
                                        $empEmail = build_work_email($emp);
                                        $empDept = build_department($emp);
                                        $empDesignation = build_designation($emp);
                                        $isIncomplete = is_profile_incomplete($emp);
                                        $empId = pick_first($emp, ['id']);
                                        $empLink = $empId ? ('employee_overview.php?emp_id=' . urlencode($empId) . '#employee-top') : ('employees.php?step=basic&emp=' . urlencode($empName));
                                    ?>
                                    <tr class="emp-row" data-emp-link="<?php echo htmlspecialchars($empLink); ?>">
                                        <td><input type="checkbox" class="emp-select" aria-label="Select row"></td>
                                        <td>
                                            <div class="emp-name-cell">
                                                <div class="emp-avatar"><?php echo strtoupper(substr($empName, 0, 1)); ?></div>
                                                <div>
                                                    <a class="emp-name-link" href="<?php echo $empLink; ?>">
                                                        <?php echo htmlspecialchars($empName); ?>
                                                        <?php if ($empCode) { ?> - <?php echo htmlspecialchars($empCode); ?><?php } ?>
                                                    </a>
                                                    <?php if ($empDesignation) { ?>
                                                        <div class="emp-code"><?php echo htmlspecialchars($empDesignation); ?></div>
                                                    <?php } ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($empEmail ?: '-'); ?></td>
                                        <td><?php echo htmlspecialchars($empDept ?: '-'); ?></td>
                                        <td>
                                            <?php if ($isIncomplete) { ?>
                                                <span class="badge badge-incomplete"><i class="fa-solid fa-circle-exclamation"></i> This employee's profile is incomplete.</span>
                                                <a class="complete-link" href="<?php echo $empLink; ?>">Complete now</a>
                                            <?php } else { ?>
                                                <span class="badge badge-active"><i class="fa-solid fa-circle-check"></i> Active</span>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                <?php } ?>
                            <?php } else { ?>
                                <tr>
                                    <td colspan="5">
                                        <div class="empty-state">
                                            <i class="fa-solid fa-user-plus"></i>
                                            <p>No employees added yet.</p>
                                            <a class="btn-add" href="employees.php?step=basic"><i class="fa-solid fa-plus"></i> Add</a>
                                        </div>
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
                <div class="help-modal" id="helpModal" aria-hidden="true">
                    <div class="help-backdrop" data-close-help></div>
                    <div class="help-dialog">
                        <div class="help-head">
                            <h3>Employees Help</h3>
                            <button class="modal-close" type="button" data-close-help>×</button>
                        </div>
                        <div class="help-body">
                            <p>Use the Add button to create employees. Click View to see only incomplete profiles. Use the filter icon to narrow the list.</p>
                        </div>
                    </div>
                </div>
                <div class="filter-drawer" id="filterDrawer" aria-hidden="true">
                    <div class="filter-panel">
                        <div class="filter-head">
                            <h3>Filter By</h3>
                            <button class="modal-close" type="button" data-close-filter>×</button>
                        </div>
                        <div class="filter-body">
                            <div class="filter-search">
                                <i class="fa-solid fa-magnifying-glass"></i>
                                <input type="text" placeholder="Search">
                            </div>
                            <div class="filter-list">
                                <label><input type="checkbox"> ID</label>
                                <label><input type="checkbox"> Work Email</label>
                                <label><input type="checkbox"> Mobile Number</label>
                                <label><input type="checkbox"> Status</label>
                                <label><input type="checkbox"> Portal Status</label>
                                <label><input type="checkbox"> Date of Joining</label>
                                <label><input type="checkbox"> Last Working Date</label>
                                <label><input type="checkbox"> Payment Mode</label>
                                <label><input type="checkbox"> Department</label>
                                <label><input type="checkbox"> Designation</label>
                                <label><input type="checkbox"> Work Location</label>
                                <label><input type="checkbox"> Investment Declaration</label>
                                <label><input type="checkbox"> Proof Of Investments</label>
                                <label><input type="checkbox"> Flexible Benefit Plan</label>
                                <label><input type="checkbox"> Reimbursement</label>
                                <label><input type="checkbox"> Reason for Exit</label>
                            </div>
                        </div>
                        <div class="filter-foot">
                            <button class="btn-primary" type="button">Apply</button>
                            <button class="btn-clear" type="button">Clear Filter</button>
                        </div>
                    </div>
                </div>
                <div class="import-modal" id="importModal" aria-hidden="true">
                    <div class="help-backdrop" data-close-import onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)"></div>
                    <div class="help-dialog">
                        <div class="help-head">
                            <h3>Import Data</h3>
                            <button class="modal-close" type="button" data-close-import onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)">x</button>
                        </div>
                        <div class="help-body">
                            <div class="fgroup">
                                <label class="flabel">Select the type of employee details to import</label>
                                <select class="finput">
                                    <option value="">Select</option>
                                    <option>Employee Basic Details</option>
                                    <option>Employee Statutory Details</option>
                                    <option>Employees Payment Information</option>
                                    <option>Employee Salary Details</option>
                                    <option>Employee Personal Details</option>
                                </select>
                            </div>
                            <div class="form-actions">
                                <button class="btn-primary" type="button">Proceed</button>
                                <button class="btn-cancel-lnk" type="button" data-close-import onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="import-modal" id="exportModal" aria-hidden="true">
                    <div class="help-backdrop" data-close-export onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)"></div>
                    <div class="help-dialog">
                        <div class="help-head">
                            <h3>Export Data</h3>
                            <button class="modal-close" type="button" data-close-export onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)">x</button>
                        </div>
                        <div class="help-body">
                            <div class="fgroup">
                                <label class="flabel">Select the type of employee details to export</label>
                                <select class="finput">
                                    <option value="">Select</option>
                                    <option>Employee Basic Details</option>
                                    <option>Employee Statutory Details</option>
                                    <option>Employees Payment Information</option>
                                    <option>Employee Salary Details</option>
                                    <option>Employee Personal Details</option>
                                </select>
                            </div>
                            <div class="fgroup">
                                <label class="flabel">Filter By</label>
                                <select class="finput">
                                    <option>All Employees</option>
                                    <option>Incomplete Employees</option>
                                </select>
                            </div>
                            <div class="fgroup">
                                <label class="flabel">Export as</label>
                                <select class="finput">
                                    <option>XLS (Microsoft Excel 1997-2004 Compatible)</option>
                                    <option>CSV</option>
                                </select>
                            </div>
                            <label class="fcheck">
                                <input type="checkbox">
                                <span>Protect this file with a password</span>
                            </label>
                            <div class="form-actions">
                                <button class="btn-primary" type="button">Export</button>
                                <button class="btn-cancel-lnk" type="button" data-close-export onclick="(function(el){var modal=el.closest('.import-modal'); if(modal){modal.classList.remove('open'); modal.setAttribute('aria-hidden','true'); modal.style.display='none';}})(this)">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php } else { ?>
                <div class="add-wrap">
                    <div class="wizard-wrap">
                        <div class="add-title">
                            <?php echo $step === 'basic' ? 'Add Employee' : htmlspecialchars($employeeName) . '\'s Profile'; ?>
                        </div>
                        <div class="step-bar">
                            <?php $stepSuffix = $currentEmployeeId ? ('&emp_id=' . urlencode($currentEmployeeId)) : ''; ?>
                            <a class="step-item <?php echo $step === 'basic' ? 'active' : 'done'; ?>" href="employees.php?step=basic<?php echo $stepSuffix; ?>">
                                <span class="step-num"><?php echo $step === 'basic' ? '1' : '<i class="fa-solid fa-check"></i>'; ?></span>Basic Details
                            </a>
                            <div class="step-line <?php echo $step !== 'basic' ? 'done' : ''; ?>"></div>
                            <a class="step-item <?php echo $step === 'salary' ? 'active' : ''; ?><?php echo $currentEmployeeId ? '' : ' disabled'; ?>" href="<?php echo $currentEmployeeId ? 'employees.php?step=salary' . $stepSuffix : 'employees.php?step=basic'; ?>">
                                <span class="step-num">2</span>Salary Details
                            </a>
                            <div class="step-line <?php echo in_array($step, ['personal', 'payment'], true) ? 'done' : ''; ?>"></div>
                            <a class="step-item <?php echo $step === 'personal' ? 'active' : ''; ?><?php echo $currentEmployeeId ? '' : ' disabled'; ?>" href="<?php echo $currentEmployeeId ? 'employees.php?step=personal' . $stepSuffix : 'employees.php?step=basic'; ?>">
                                <span class="step-num">3</span>Personal Details
                            </a>
                            <div class="step-line <?php echo $step === 'payment' ? 'done' : ''; ?>"></div>
                            <a class="step-item <?php echo $step === 'payment' ? 'active' : ''; ?><?php echo $currentEmployeeId ? '' : ' disabled'; ?>" href="<?php echo $currentEmployeeId ? 'employees.php?step=payment' . $stepSuffix : 'employees.php?step=basic'; ?>">
                                <span class="step-num">4</span>Payment Information
                            </a>
                        </div>

                        <form method="POST" novalidate data-dirty-watch>
                            <?php if (!empty($employee) && !empty($employee['id'])) { ?>
                                <input type="hidden" name="employee_db_id" value="<?php echo htmlspecialchars($employee['id']); ?>">
                            <?php } ?>
                            <?php if ($step === 'basic') { ?>
                                <div class="card z-basic">
                                    <div class="frow frow-1">
                                        <div class="fgroup">
                                            <label class="flabel">Employee Name <span class="req">*</span></label>
                                            <div class="zname-row">
                                                <input class="finput" type="text" name="first_name" placeholder="First Name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['first_name', 'firstname']) ?? ''); ?>" required>
                                                <input class="finput" type="text" name="middle_name" placeholder="Middle Name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['middle_name', 'middlename']) ?? ''); ?>">
                                                <input class="finput" type="text" name="last_name" placeholder="Last Name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['last_name', 'lastname']) ?? ''); ?>">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Employee ID <span class="req">*</span></label>
                                            <input class="finput" type="text" name="employee_id" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['employee_code', 'employee_id', 'emp_code']) ?? ''); ?>" required>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Date of Joining <span class="req">*</span></label>
                                            <input class="finput" type="date" name="join_date" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['date_of_joining', 'join_date']) ?? ''); ?>" required>
                                        </div>
                                    </div>

                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Work Email <span class="req">*</span></label>
                                            <input class="finput" type="email" name="email" placeholder="abc@xyz.com" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['work_email', 'email', 'office_email']) ?? ''); ?>" required>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Mobile Number</label>
                                            <input class="finput" type="text" name="mobile" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['mobile_number', 'mobile_no', 'mobile', 'mobile_phone', 'mobile_r']) ?? ''); ?>">
                                        </div>
                                    </div>

                                    <label class="fcheck z-director">
                                        <input type="checkbox">
                                        <span>Employee is a Director/person with substantial interest in the company.</span>
                                        <span class="z-info">i</span>
                                    </label>

                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Gender <span class="req">*</span></label>
                                            <select class="finput" name="gender" required>
                                                <?php $genderValue = pick_field($employee ?? [], ['gender']); ?>
                                                <option value="">Select</option>
                                                <option <?php echo $genderValue === 'Male' ? 'selected' : ''; ?>>Male</option>
                                                <option <?php echo $genderValue === 'Female' ? 'selected' : ''; ?>>Female</option>
                                            </select>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Work Location <span class="req">*</span></label>
                                            <?php render_employee_combo_field('work_location', 'Work Location', (string) (pick_field($employee ?? [], ['work_location']) ?? ''), $workLocationOptions, 'locations.php', '+ New Work Location'); ?>
                                        </div>
                                    </div>

                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Designation <span class="req">*</span></label>
                                            <?php render_employee_combo_field('designation', 'Designation', (string) (pick_field($employee ?? [], ['designation']) ?? ''), $designationOptions, 'designations.php', '+ New Designation'); ?>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Department <span class="req">*</span></label>
                                            <?php render_employee_combo_field('department', 'Department', (string) (pick_field($employee ?? [], ['department', 'dept_name']) ?? ''), $departmentOptions, 'departments.php', '+ New Department'); ?>
                                        </div>
                                    </div>

                                    <label class="fcheck">
                                        <input type="checkbox">
                                        <span>Enable Portal Access</span>
                                    </label>

                                    <div class="info-box">
                                        <i class="fa-regular fa-circle-info"></i>
                                        <div>Statutory components are now part of Salary Details, ensuring all salary-linked information is captured and reviewed in one place.</div>
                                    </div>
                                </div>
                            <?php } ?>

                            <?php if ($step === 'salary') { ?>
                                <div class="card">
                                    <div class="card-head">Statutory Components</div>
                                    <div class="card-sub">Enable the necessary benefits and tax applicable for this employee.</div>
                                    <label class="check-row">
                                        <?php $proTax = pick_field($employee ?? [], ['professional_tax']); ?>
                                        <input type="checkbox" name="professional_tax" value="1" <?php echo ($proTax === null || $proTax === '1' || $proTax === 1) ? 'checked' : ''; ?>>
                                        <span>Professional Tax</span>
                                    </label>
                                    <div class="form-actions">
                                        <button class="btn-primary" type="submit" name="submit">Save and Continue</button>
                                        <a class="btn-cancel-lnk" href="employees.php?step=basic&emp=<?php echo urlencode($employeeName); ?>">Cancel</a>
                                    </div>
                                </div>
                                <?php
                                    $annualCtc = (float)(pick_field($employee ?? [], ['annual_ctc']) ?? 0);
                                    $basicPercent = (float)(pick_field($employee ?? [], ['basic_percent']) ?? 50);
                                    $basicAnnual = pick_field($employee ?? [], ['basic_annual']);
                                    $basicMonthly = pick_field($employee ?? [], ['basic_monthly']);
                                    $hraEnabled = (int)(pick_field($employee ?? [], ['house_rent_allowance_enabled']) ?? 0) === 1;
                                    $hraPercent = (float)(pick_field($employee ?? [], ['house_rent_allowance_percent']) ?? 50);
                                    $hraAnnual = pick_field($employee ?? [], ['house_rent_allowance_annual']);
                                    $hraMonthly = pick_field($employee ?? [], ['house_rent_allowance_monthly']);
                                    $conveyanceEnabled = (int)(pick_field($employee ?? [], ['conveyance_allowance_enabled']) ?? 0) === 1;
                                    $conveyanceAnnual = pick_field($employee ?? [], ['conveyance_allowance_annual']);
                                    $conveyanceMonthly = pick_field($employee ?? [], ['conveyance_allowance_monthly']);
                                    $fixedMonthly = pick_field($employee ?? [], ['fixed_allowance_monthly']);
                                    $fixedAnnual = pick_field($employee ?? [], ['fixed_allowance_annual']);
                                    if ($annualCtc > 0 && ($basicAnnual === null || $basicAnnual === '')) {
                                        $basicAnnual = round($annualCtc * $basicPercent / 100, 2);
                                    }
                                    if ($basicAnnual !== null && ($basicMonthly === null || $basicMonthly === '')) {
                                        $basicMonthly = round(((float)$basicAnnual) / 12, 2);
                                    }
                                    if ($hraEnabled && $basicAnnual !== null && ($hraAnnual === null || $hraAnnual === '')) {
                                        $hraAnnual = round(((float)$basicAnnual) * $hraPercent / 100, 2);
                                    }
                                    if ($hraEnabled && $hraAnnual !== null && ($hraMonthly === null || $hraMonthly === '')) {
                                        $hraMonthly = round(((float)$hraAnnual) / 12, 2);
                                    }
                                    if ($conveyanceEnabled && $conveyanceMonthly !== null && $conveyanceMonthly !== '' && ($conveyanceAnnual === null || $conveyanceAnnual === '')) {
                                        $conveyanceAnnual = round(((float)$conveyanceMonthly) * 12, 2);
                                    }
                                    if ($conveyanceEnabled && $conveyanceAnnual !== null && $conveyanceAnnual !== '' && ($conveyanceMonthly === null || $conveyanceMonthly === '')) {
                                        $conveyanceMonthly = round(((float)$conveyanceAnnual) / 12, 2);
                                    }
                                    if ($annualCtc > 0 && ($fixedAnnual === null || $fixedAnnual === '')) {
                                        $fixedAnnual = round($annualCtc - (float)$basicAnnual - ($hraEnabled ? (float)$hraAnnual : 0) - ($conveyanceEnabled ? (float)$conveyanceAnnual : 0), 2);
                                    }
                                    if ($fixedAnnual !== null && ($fixedMonthly === null || $fixedMonthly === '')) {
                                        $fixedMonthly = round(((float)$fixedAnnual) / 12, 2);
                                    }
                                    $monthlyCtc = $annualCtc > 0 ? round($annualCtc / 12, 2) : 0;
                                ?>
                                <?php if ($salaryMode === 'summary') { ?>
                                    <div class="card">
                                        <div class="card-head head-inline">
                                            <span>Salary Structure</span>
                                            <a class="btn-edit" href="employees.php?step=salary&emp_id=<?php echo urlencode($currentEmployeeId); ?>&mode=edit">Edit</a>
                                        </div>
                                        <div class="card-sub">Set how the employee's salary is divided for accurate pay calculation.</div>
                                        <div class="salary-summary">
                                            <div class="summary-item">
                                                <div class="summary-label">Annual CTC</div>
                                                <div class="summary-value">₹<?php echo number_format((float)$annualCtc, 2); ?></div>
                                            </div>
                                            <div class="summary-item">
                                                <div class="summary-label">Monthly CTC</div>
                                                <div class="summary-value">₹<?php echo number_format((float)$monthlyCtc, 2); ?></div>
                                            </div>
                                        </div>
                                        <div class="salary-table summary-table">
                                            <div class="salary-head">
                                                <div>Salary Components</div>
                                                <div>Monthly Amount</div>
                                                <div>Annual Amount</div>
                                            </div>
                                            <div class="salary-row">
                                                <div class="salary-title">Basic (<?php echo number_format((float)$basicPercent, 2); ?> % of CTC)</div>
                                                <div>₹<?php echo number_format((float)$basicMonthly, 2); ?></div>
                                                <div>₹<?php echo number_format((float)$basicAnnual, 2); ?></div>
                                            </div>
                                            <?php if ($hraEnabled) { ?>
                                                <div class="salary-row">
                                                    <div class="salary-title">House Rent Allowance (<?php echo number_format((float)$hraPercent, 2); ?> % of Basic)</div>
                                                    <div>₹<?php echo number_format((float)$hraMonthly, 2); ?></div>
                                                    <div>₹<?php echo number_format((float)$hraAnnual, 2); ?></div>
                                                </div>
                                            <?php } ?>
                                            <?php if ($conveyanceEnabled) { ?>
                                                <div class="salary-row">
                                                    <div class="salary-title">Conveyance Allowance</div>
                                                    <div>₹<?php echo number_format((float)$conveyanceMonthly, 2); ?></div>
                                                    <div>₹<?php echo number_format((float)$conveyanceAnnual, 2); ?></div>
                                                </div>
                                            <?php } ?>
                                            <div class="salary-row">
                                                <div class="salary-title">Fixed Allowance</div>
                                                <div>₹<?php echo number_format((float)$fixedMonthly, 2); ?></div>
                                                <div>₹<?php echo number_format((float)$fixedAnnual, 2); ?></div>
                                            </div>
                                            <div class="salary-row total-row">
                                                <div class="salary-title">Cost to Company</div>
                                                <div>₹<?php echo number_format((float)$monthlyCtc, 2); ?></div>
                                                <div>₹<?php echo number_format((float)$annualCtc, 2); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                <?php } else { ?>
                                    <div class="card">
                                        <div class="card-head">Salary Structure</div>
                                        <div class="card-sub">Set how the employee's salary is divided for accurate pay calculation.</div>
                                        <div class="salary-ctc-row">
                                            <label class="salary-label">Annual CTC <span class="req">*</span></label>
                                            <div class="salary-ctc-input">
                                                <span class="currency">₹</span>
                                                <input class="finput" type="number" name="annual_ctc" value="<?php echo htmlspecialchars($annualCtc ?: ''); ?>" min="0" step="0.01" placeholder="0" data-ctc>
                                                <span class="per-year">per year</span>
                                            </div>
                                        </div>
                                        <div class="salary-table">
                                            <div class="salary-head">
                                                <div>Salary Components</div>
                                                <div>Calculation Type</div>
                                                <div>Monthly Amount</div>
                                                <div>Annual Amount</div>
                                            </div>
                                            <input type="hidden" name="house_rent_allowance_enabled" value="<?php echo $hraEnabled ? '1' : '0'; ?>" data-hra-enabled-hidden>
                                            <input type="hidden" name="conveyance_allowance_enabled" value="<?php echo $conveyanceEnabled ? '1' : '0'; ?>" data-conveyance-enabled-hidden>
                                            <div class="salary-row">
                                                <div class="salary-title">Basic</div>
                                                <div class="salary-calc">
                                                    <input class="finput small" type="number" name="basic_percent" value="<?php echo htmlspecialchars($basicPercent); ?>" min="0" max="100" step="0.01" data-basic-percent>
                                                    <span class="calc-suffix">% of CTC</span>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="basic_monthly" value="<?php echo htmlspecialchars($basicMonthly ?? ''); ?>" min="0" step="0.01" readonly data-basic-monthly>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="basic_annual" value="<?php echo htmlspecialchars($basicAnnual ?? ''); ?>" min="0" step="0.01" readonly data-basic-annual>
                                                </div>
                                            </div>
                                            <div class="salary-row">
                                                <div class="salary-title">Fixed Allowance</div>
                                                <div class="salary-calc">
                                                    <span class="calc-suffix">Fixed amount</span>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="fixed_allowance_monthly" value="<?php echo htmlspecialchars($fixedMonthly ?? ''); ?>" min="0" step="0.01" readonly data-fixed-monthly>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="fixed_allowance_annual" value="<?php echo htmlspecialchars($fixedAnnual ?? ''); ?>" min="0" step="0.01" readonly data-fixed-annual>
                                                </div>
                                            </div>
                                            <div class="salary-row<?php echo $hraEnabled ? '' : ' hidden'; ?>" data-salary-row="hra">
                                                <div class="salary-title">House Rent Allowance</div>
                                                <div class="salary-calc">
                                                    <input class="finput small" type="number" name="house_rent_allowance_percent" value="<?php echo htmlspecialchars($hraPercent); ?>" min="0" step="0.01" data-hra-percent>
                                                    <span class="calc-suffix">% of Basic</span>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="house_rent_allowance_monthly" value="<?php echo htmlspecialchars($hraMonthly ?? ''); ?>" min="0" step="0.01" readonly data-hra-monthly>
                                                </div>
                                                <div class="salary-amount-with-action">
                                                    <input class="finput small" type="number" name="house_rent_allowance_annual" value="<?php echo htmlspecialchars($hraAnnual ?? ''); ?>" min="0" step="0.01" readonly data-hra-annual>
                                                    <button class="salary-remove" type="button" data-remove-salary-row="hra" aria-label="Remove House Rent Allowance">×</button>
                                                </div>
                                            </div>
                                            <div class="salary-row<?php echo $conveyanceEnabled ? '' : ' hidden'; ?>" data-salary-row="conveyance">
                                                <div class="salary-title">Conveyance Allowance</div>
                                                <div class="salary-calc">
                                                    <span class="calc-suffix">Fixed amount</span>
                                                </div>
                                                <div>
                                                    <input class="finput small" type="number" name="conveyance_allowance_monthly" value="<?php echo htmlspecialchars($conveyanceMonthly ?? ''); ?>" min="0" step="0.01" data-conveyance-monthly>
                                                </div>
                                                <div class="salary-amount-with-action">
                                                    <input class="finput small" type="number" name="conveyance_allowance_annual" value="<?php echo htmlspecialchars($conveyanceAnnual ?? ''); ?>" min="0" step="0.01" readonly data-conveyance-annual>
                                                    <button class="salary-remove" type="button" data-remove-salary-row="conveyance" aria-label="Remove Conveyance Allowance">×</button>
                                                </div>
                                            </div>
                                            <div class="salary-actions">
                                                <button class="salary-add-btn" type="button" data-toggle-salary-menu>+ Add Earning</button>
                                                <div class="salary-add-menu" data-salary-menu hidden>
                                                    <button type="button" data-add-salary-row="hra">House Rent Allowance</button>
                                                    <button type="button" data-add-salary-row="conveyance">Conveyance Allowance</button>
                                                </div>
                                            </div>
                                            <div class="salary-row total-row">
                                                <div class="salary-title">Cost to Company</div>
                                                <div>₹<span data-ctc-monthly><?php echo number_format((float)$monthlyCtc, 2); ?></span></div>
                                                <div>₹<span data-ctc-annual><?php echo number_format((float)$annualCtc, 2); ?></span></div>
                                            </div>
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="card">
                                    <div class="card-head">Salary Hold & Release</div>
                                    <div class="card-sub">Track salary months that are held, approved, or released later.</div>
                                    <?php if ($step === 'salary' && !empty($salaryHoldEntries)) { ?>
                                        <div class="salary-hold-table">
                                            <div class="salary-hold-head">
                                                <div>Hold Period</div>
                                                <div>Release Month</div>
                                                <div>Status</div>
                                                <div>Pending Months</div>
                                            </div>
                                            <?php foreach ($salaryHoldEntries as $holdEntry) { ?>
                                                <div class="salary-hold-row">
                                                    <div>
                                                        <strong><?php echo htmlspecialchars(settings_salary_hold_month_label((string) ($holdEntry['salary_month_from'] ?? ''))); ?></strong>
                                                        <span>to <?php echo htmlspecialchars(settings_salary_hold_month_label((string) ($holdEntry['salary_month_to'] ?? ''))); ?></span>
                                                    </div>
                                                    <div><?php echo htmlspecialchars(settings_salary_hold_month_label((string) ($holdEntry['release_month'] ?? ''))); ?></div>
                                                    <div>
                                                        <span class="salary-pill status-<?php echo htmlspecialchars((string) ($holdEntry['approval_status'] ?? 'pending')); ?>">
                                                            <?php echo htmlspecialchars(ucfirst((string) ($holdEntry['approval_status'] ?? 'pending'))); ?>
                                                        </span>
                                                    </div>
                                                    <div><?php echo (int) settings_salary_hold_pending_months($holdEntry); ?> month(s)</div>
                                                </div>
                                            <?php } ?>
                                        </div>
                                    <?php } ?>
                                    <?php if ($salaryMode === 'edit') { ?>
                                        <?php
                                            $holdFromValue = '';
                                            $holdToValue = '';
                                            $releaseMonthValue = '';
                                            $holdStatusValue = 'pending';
                                            $approvalStatusValue = 'pending';
                                            $holdReasonValue = '';
                                            if (!empty($salaryHoldEntries)) {
                                                $latestHold = $salaryHoldEntries[0];
                                                $holdFromValue = (string) ($latestHold['salary_month_from'] ?? '');
                                                $holdToValue = (string) ($latestHold['salary_month_to'] ?? '');
                                                $releaseMonthValue = (string) ($latestHold['release_month'] ?? '');
                                                $holdStatusValue = (string) ($latestHold['hold_status'] ?? 'pending');
                                                $approvalStatusValue = (string) ($latestHold['approval_status'] ?? 'pending');
                                                $holdReasonValue = (string) ($latestHold['hold_reason'] ?? '');
                                            }
                                        ?>
                                        <div class="salary-hold-form">
                                            <div class="frow frow-2">
                                                <div class="fgroup">
                                                    <label class="flabel">Hold From Month</label>
                                                    <input class="finput" type="month" name="salary_month_from" value="<?php echo htmlspecialchars($holdFromValue); ?>">
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">Hold To Month</label>
                                                    <input class="finput" type="month" name="salary_month_to" value="<?php echo htmlspecialchars($holdToValue); ?>">
                                                </div>
                                            </div>
                                            <div class="frow frow-2">
                                                <div class="fgroup">
                                                    <label class="flabel">Release Month</label>
                                                    <input class="finput" type="month" name="release_month" value="<?php echo htmlspecialchars($releaseMonthValue); ?>">
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">Hold Status</label>
                                                    <select class="finput" name="hold_status">
                                                        <option value="pending" <?php echo $holdStatusValue === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                        <option value="held" <?php echo $holdStatusValue === 'held' ? 'selected' : ''; ?>>Held</option>
                                                        <option value="released" <?php echo $holdStatusValue === 'released' ? 'selected' : ''; ?>>Released</option>
                                                        <option value="approved" <?php echo $holdStatusValue === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="frow frow-1">
                                                <div class="fgroup">
                                                    <label class="flabel">Approval Status</label>
                                                    <select class="finput" name="approval_status">
                                                        <option value="pending" <?php echo $approvalStatusValue === 'pending' ? 'selected' : ''; ?>>Pending approval</option>
                                                        <option value="approved" <?php echo $approvalStatusValue === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                        <option value="rejected" <?php echo $approvalStatusValue === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="frow frow-1">
                                                <div class="fgroup">
                                                    <label class="flabel">Hold Reason</label>
                                                    <textarea class="finput salary-hold-textarea" name="hold_reason" rows="3" placeholder="For example: March and April salary held until May release."><?php echo htmlspecialchars($holdReasonValue); ?></textarea>
                                                </div>
                                            </div>
                                            <div class="frow frow-1">
                                                <div class="fgroup">
                                                    <label class="flabel">Notes</label>
                                                    <textarea class="finput salary-hold-textarea" name="salary_hold_notes" rows="2" placeholder="Optional internal notes."></textarea>
                                                </div>
                                            </div>
                                            <div class="form-actions" style="justify-content:flex-start; gap:12px;">
                                                <button class="btn-primary" type="submit" name="save_salary_hold" value="1">Save Salary Hold</button>
                                            </div>
                                        </div>
                                    <?php } ?>
                                </div>
                                <div class="card">
                                    <div class="card-head">Other Benefits</div>
                                    <div class="card-sub">Optional Add-ons to Employee Salary Structure.</div>
                                    <?php if ($benefitSuccess) { ?>
                                        <div class="alert-ok"><i class="fa-solid fa-circle-check"></i><?php echo htmlspecialchars($benefitSuccess); ?></div>
                                    <?php } ?>
                                    <?php if (!empty($benefitErrors)) { ?>
                                        <div class="alert-err">
                                            <div class="alert-err-title">
                                                Oops! Looks like you missed something...
                                                <button class="alert-close" type="button" onclick="this.parentElement.parentElement.style.display='none'">×</button>
                                            </div>
                                            <ul>
                                                <?php foreach ($benefitErrors as $err) { ?>
                                                    <li><?php echo htmlspecialchars($err); ?></li>
                                                <?php } ?>
                                            </ul>
                                        </div>
                                    <?php } ?>
                                    <div class="benefits-row">
                                        <div>
                                            <div class="benefit-title">Do you offer Benefits for this employee?</div>
                                            <div class="benefit-sub">Add Benefits and define contribution details for this employee.</div>
                                        </div>
                                        <button class="btn-secondary" type="button" data-open-benefit>+ Add Benefit</button>
                                    </div>
                                    <?php if (!empty($employeeBenefits)) { ?>
                                        <div class="benefits-list">
                                            <?php foreach ($employeeBenefits as $benefit) { ?>
                                                <div class="benefit-item">
                                                    <div>
                                                        <div class="benefit-name"><?php echo htmlspecialchars($benefit['benefit_name']); ?></div>
                                                        <div class="benefit-meta"><?php echo htmlspecialchars($benefit['benefit_plan'] ?? ''); ?></div>
                                                    </div>
                                                    <div class="benefit-amount">
                                                        <?php echo htmlspecialchars($benefit['employer_contribution_amount'] ?? ''); ?>
                                                    </div>
                                                </div>
                                            <?php } ?>
                                        </div>
                                    <?php } ?>
                                </div>
                            <?php } ?>

                            <?php if ($step === 'personal') { ?>
                                <div class="card">
                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Date of Birth <span class="req">*</span></label>
                                            <input class="finput" type="date" name="dob" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['dob', 'date_of_birth']) ?? ''); ?>" required>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Age</label>
                                            <input class="finput" type="text" name="age" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['age']) ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Father's Name <span class="req">*</span></label>
                                            <input class="finput" type="text" name="father_name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['father_name']) ?? ''); ?>" required>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">PAN</label>
                                            <input class="finput" type="text" name="pan" placeholder="AAAAA0000A" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['pan']) ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Differently Abled Type</label>
                                            <select class="finput" name="abled_type">
                                                <?php $abledValue = pick_field($employee ?? [], ['abled_type']); ?>
                                                <option <?php echo $abledValue === 'None' ? 'selected' : ''; ?>>None</option>
                                                <option <?php echo $abledValue === 'Partially Abled' ? 'selected' : ''; ?>>Partially Abled</option>
                                                <option <?php echo $abledValue === 'Fully Abled' ? 'selected' : ''; ?>>Fully Abled</option>
                                            </select>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Personal Email Address</label>
                                            <input class="finput" type="email" name="personal_email" placeholder="abc@xyz.com" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['personal_email', 'personal_email_address']) ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="frow frow-1">
                                        <div class="fgroup">
                                            <label class="flabel">Residential Address</label>
                                            <input class="finput" type="text" name="addr1" placeholder="Address Line 1" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['addr1', 'address_line1', 'address1']) ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="frow frow-1">
                                        <div class="fgroup">
                                            <input class="finput" type="text" name="addr2" placeholder="Address Line 2" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['addr2', 'address_line2', 'address2']) ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="frow frow-3">
                                        <div class="fgroup">
                                            <input class="finput" type="text" name="city" placeholder="City" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['city']) ?? ''); ?>">
                                        </div>
                                        <div class="fgroup">
                                            <select class="finput" name="state">
                                                <?php $stateValue = pick_field($employee ?? [], ['state']); ?>
                                                <option>State</option>
                                                <option <?php echo $stateValue === 'Tamil Nadu' ? 'selected' : ''; ?>>Tamil Nadu</option>
                                                <option <?php echo $stateValue === 'Karnataka' ? 'selected' : ''; ?>>Karnataka</option>
                                            </select>
                                        </div>
                                        <div class="fgroup">
                                            <input class="finput" type="text" name="pin" placeholder="PIN Code" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['pin', 'pincode', 'postal_code']) ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>

                            <?php if ($step === 'payment') { ?>
                                <div class="card">
                                    <div class="card-head">
                                        How would you like to pay this employee?<span class="req">*</span>
                                    </div>

                                    <div class="pay-methods">
                                        <?php $payMethod = pick_field($employee ?? [], ['pay_method', 'payment_method']); ?>
                                        <?php $selectedPayMethod = ($payMethod === null || $payMethod === '') ? 'bank_transfer' : $payMethod; ?>
                                        <label class="pay-opt">
                                            <input type="radio" name="pay_method" value="direct_deposit" <?php echo $payMethod === 'direct_deposit' ? 'checked' : ''; ?>>
                                            <div class="pay-ico"><i class="fa-solid fa-right-left"></i></div>
                                            <div class="pay-main">
                                                <div class="pay-title">Direct Deposit (Automated Process)</div>
                                                <div class="pay-desc">Initiate payment in B2L Mobitech once the pay run is approved</div>
                                            </div>
                                            <div class="pay-right">
                                                <a class="pay-action" href="direct_deposits.php">Configure Now</a>
                                                <div class="pay-check"><i class="fa-regular fa-circle-check"></i></div>
                                            </div>
                                        </label>

                                        <label class="pay-opt">
                                            <input type="radio" name="pay_method" value="bank_transfer" <?php echo ($payMethod === 'bank_transfer' || $payMethod === null || $payMethod === '') ? 'checked' : ''; ?>>
                                            <div class="pay-ico"><i class="fa-solid fa-building-columns"></i></div>
                                            <div class="pay-main">
                                                <div class="pay-title">Bank Transfer (Manual Process)</div>
                                                <div class="pay-desc">Download Bank Advice and process the payment through your bank's website</div>
                                            </div>
                                            <div class="pay-right">
                                                <div class="pay-check"><i class="fa-solid fa-circle-check"></i></div>
                                            </div>
                                        </label>

                                        <div class="pay-detail-card <?php echo $selectedPayMethod === 'bank_transfer' ? 'is-active' : ''; ?>" data-pay-detail="bank_transfer">
                                            <div class="pay-detail-grid">
                                                <div class="fgroup pay-detail-span">
                                                    <label class="flabel">Account Holder Name <span class="req">*</span></label>
                                                    <input class="finput" type="text" name="account_holder_name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['account_holder_name']) ?? build_full_name($employee ?? [])); ?>">
                                                </div>
                                                <div class="fgroup pay-detail-span">
                                                    <label class="flabel">Bank Name <span class="req">*</span></label>
                                                    <input class="finput" type="text" name="bank_name" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['bank_name']) ?? ''); ?>">
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">Account Number <span class="req">*</span></label>
                                                    <input class="finput" type="text" name="account_number" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['account_number']) ?? ''); ?>">
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">Re-enter Account Number <span class="req">*</span></label>
                                                    <input class="finput" type="text" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['account_number']) ?? ''); ?>" data-account-confirm>
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">IFSC <span class="req">*</span></label>
                                                    <input class="finput" type="text" name="ifsc_code" placeholder="AAAA0000000" value="<?php echo htmlspecialchars(pick_field($employee ?? [], ['ifsc_code']) ?? ''); ?>">
                                                </div>
                                                <div class="fgroup">
                                                    <label class="flabel">Account Type <span class="req">*</span></label>
                                                    <?php $bankAccountType = (string) (pick_field($employee ?? [], ['bank_account_type']) ?? 'savings'); ?>
                                                    <div class="account-type-row">
                                                        <label class="account-type-opt">
                                                            <input type="radio" name="bank_account_type" value="current" <?php echo $bankAccountType === 'current' ? 'checked' : ''; ?>>
                                                            <span>Current</span>
                                                        </label>
                                                        <label class="account-type-opt">
                                                            <input type="radio" name="bank_account_type" value="savings" <?php echo $bankAccountType !== 'current' ? 'checked' : ''; ?>>
                                                            <span>Savings</span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <label class="pay-opt">
                                            <input type="radio" name="pay_method" value="cheque" <?php echo $payMethod === 'cheque' ? 'checked' : ''; ?>>
                                            <div class="pay-ico"><i class="fa-regular fa-credit-card"></i></div>
                                            <div class="pay-main">
                                                <div class="pay-title">Cheque</div>
                                            </div>
                                            <div class="pay-right">
                                                <div class="pay-check"><i class="fa-regular fa-circle-check"></i></div>
                                            </div>
                                        </label>

                                        <label class="pay-opt">
                                            <input type="radio" name="pay_method" value="cash" <?php echo $payMethod === 'cash' ? 'checked' : ''; ?>>
                                            <div class="pay-ico"><i class="fa-regular fa-money-bill-1"></i></div>
                                            <div class="pay-main">
                                                <div class="pay-title">Cash</div>
                                            </div>
                                            <div class="pay-right">
                                                <div class="pay-check"><i class="fa-regular fa-circle-check"></i></div>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            <?php } ?>

                            <div class="form-actions">
                                <button class="btn-primary" type="submit" name="submit">Save and Continue</button>
                                <?php if ($step === 'personal') { ?>
                                    <a class="btn-cancel-lnk" href="employees.php?step=payment<?php echo $currentEmployeeId ? ('&emp_id=' . urlencode($currentEmployeeId)) : ''; ?>">Skip</a>
                                <?php } elseif ($step === 'payment') { ?>
                                    <a class="btn-cancel-lnk" href="employees.php?step=list">Skip</a>
                                <?php } else { ?>
                                    <a class="btn-cancel-lnk" href="employees.php?step=list">Cancel</a>
                                <?php } ?>
                                <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                            </div>
                        </form>
                        <div class="benefit-modal" id="benefitModal" aria-hidden="true">
                            <div class="benefit-backdrop" data-close-benefit></div>
                            <div class="benefit-dialog">
                                <div class="benefit-header">
                                    <h3>Add Benefits</h3>
                                    <button class="modal-close" type="button" data-close-benefit>×</button>
                                </div>
                                <form method="POST" class="benefit-form" novalidate>
                                    <input type="hidden" name="benefit_submit" value="1">
                                    <input type="hidden" name="employee_db_id" value="<?php echo htmlspecialchars($currentEmployeeId); ?>">
                                    <div class="fgroup">
                                        <label class="flabel">Benefit Name <span class="req">*</span></label>
                                        <input class="finput" type="text" name="benefit_name" required>
                                    </div>
                                    <div class="fgroup">
                                        <label class="flabel">Benefit Plan <span class="req">*</span></label>
                                        <select class="finput" name="benefit_plan" required>
                                            <option value="">Select a Benefit Plan</option>
                                            <option>PF</option>
                                            <option>ESI</option>
                                            <option>Gratuity</option>
                                            <option>Other</option>
                                        </select>
                                    </div>
                                    <label class="fcheck">
                                        <input type="checkbox" name="include_employer_contribution">
                                        <span>Include employer's contribution in employee’s salary structure.</span>
                                    </label>
                                    <label class="fcheck">
                                        <input type="checkbox" name="is_superannuation">
                                        <span>Consider this a superannuation fund</span>
                                    </label>
                                    <div class="fgroup">
                                        <label class="flabel">Associate this benefit with</label>
                                        <select class="finput" name="associate_investment">
                                            <option value="">Select an Investment</option>
                                            <option>Never ends</option>
                                            <option>Ends when specific amount is deducted</option>
                                            <option>Ends within fiscal year and restarts</option>
                                        </select>
                                    </div>
                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Employer's Contribution</label>
                                            <div class="benefit-inline">
                                                <select class="finput" name="contribution_basis">
                                                    <option value="fixed">Fixed amount</option>
                                                    <option value="percent">Percent of CTC</option>
                                                </select>
                                                <input class="finput" type="number" name="employer_contribution_amount" min="0" step="0.01" placeholder="0">
                                            </div>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Contribution Type</label>
                                            <select class="finput" name="contribution_type">
                                                <option>Never ends</option>
                                                <option>Ends when specific amount is deducted</option>
                                                <option>Ends within fiscal year and restarts</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="fgroup">
                                        <label class="flabel">Total Amount to Deduct</label>
                                        <input class="finput" type="number" name="total_amount_to_deduct" min="0" step="0.01" placeholder="0">
                                    </div>
                                    <div class="form-actions">
                                        <button class="btn-primary" type="submit">Save</button>
                                        <button class="btn-cancel-lnk" type="button" data-close-benefit>Cancel</button>
                                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="master-modal" id="designationCreateModal" aria-hidden="true">
                            <div class="master-backdrop" data-close-master-modal></div>
                            <div class="master-dialog master-dialog--narrow">
                                <div class="master-header">
                                    <h3>New Designation</h3>
                                    <button class="modal-close" type="button" data-close-master-modal>×</button>
                                </div>
                                <form method="POST" class="master-form" novalidate>
                                    <input type="hidden" name="master_action" value="create_designation">
                                    <input type="hidden" name="return_step" value="<?php echo htmlspecialchars($step); ?>">
                                    <input type="hidden" name="return_emp_id" value="<?php echo (int) $currentEmployeeId; ?>">
                                    <div class="fgroup">
                                        <label class="flabel">Designation Name <span class="req">*</span></label>
                                        <input class="finput" type="text" name="designation_name" required>
                                    </div>
                                    <div class="form-actions master-actions">
                                        <button class="btn-primary" type="submit">Save</button>
                                        <button class="btn-cancel-lnk" type="button" data-close-master-modal>Cancel</button>
                                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="master-modal" id="departmentCreateModal" aria-hidden="true">
                            <div class="master-backdrop" data-close-master-modal></div>
                            <div class="master-dialog">
                                <div class="master-header">
                                    <h3>New Department</h3>
                                    <button class="modal-close" type="button" data-close-master-modal>×</button>
                                </div>
                                <form method="POST" class="master-form" novalidate>
                                    <input type="hidden" name="master_action" value="create_department">
                                    <input type="hidden" name="return_step" value="<?php echo htmlspecialchars($step); ?>">
                                    <input type="hidden" name="return_emp_id" value="<?php echo (int) $currentEmployeeId; ?>">
                                    <div class="frow frow-2">
                                        <div class="fgroup">
                                            <label class="flabel">Department Name <span class="req">*</span></label>
                                            <input class="finput" type="text" name="department_name" required>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">Department Code</label>
                                            <input class="finput" type="text" name="department_code">
                                        </div>
                                    </div>
                                    <div class="fgroup">
                                        <label class="flabel">Description</label>
                                        <textarea class="finput master-textarea" name="department_desc" rows="4" placeholder="Max 250 characters"></textarea>
                                    </div>
                                    <div class="form-actions master-actions">
                                        <button class="btn-primary" type="submit">Save</button>
                                        <button class="btn-cancel-lnk" type="button" data-close-master-modal>Cancel</button>
                                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="master-modal" id="workLocationCreateModal" aria-hidden="true">
                            <div class="master-backdrop" data-close-master-modal></div>
                            <div class="master-dialog master-dialog--wide">
                                <div class="master-header">
                                    <h3>New Work Location</h3>
                                    <button class="modal-close" type="button" data-close-master-modal>×</button>
                                </div>
                                <form method="POST" class="master-form" novalidate>
                                    <input type="hidden" name="master_action" value="create_work_location">
                                    <input type="hidden" name="return_step" value="<?php echo htmlspecialchars($step); ?>">
                                    <input type="hidden" name="return_emp_id" value="<?php echo (int) $currentEmployeeId; ?>">
                                    <div class="fgroup">
                                        <label class="flabel">Work Location Name <span class="req">*</span></label>
                                        <input class="finput" type="text" name="location_name" required>
                                    </div>
                                    <div class="fgroup">
                                        <label class="flabel">Address <span class="req">*</span></label>
                                        <input class="finput" type="text" name="address_line1" placeholder="Address Line 1" required>
                                        <input class="finput" type="text" name="address_line2" placeholder="Address Line 2">
                                    </div>
                                    <div class="frow frow-3">
                                        <div class="fgroup">
                                            <label class="flabel">State <span class="req">*</span></label>
                                            <select class="finput" name="state" required>
                                                <option value="">Select a state</option>
                                                <?php foreach ($states as $stateName): ?>
                                                    <option value="<?php echo htmlspecialchars($stateName); ?>"><?php echo htmlspecialchars($stateName); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">City</label>
                                            <input class="finput" type="text" name="city">
                                        </div>
                                        <div class="fgroup">
                                            <label class="flabel">PIN Code</label>
                                            <input class="finput" type="text" name="pincode">
                                        </div>
                                    </div>
                                    <label class="fcheck">
                                        <input type="checkbox" name="is_filing_address" value="1">
                                        <span>Set as filing address</span>
                                    </label>
                                    <div class="form-actions master-actions">
                                        <button class="btn-primary" type="submit">Save</button>
                                        <button class="btn-cancel-lnk" type="button" data-close-master-modal>Cancel</button>
                                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <script>
                            (function(){
                                const form = document.querySelector('form[data-dirty-watch]');
                                if (!form) return;
                                let dirty = false;
                                const markDirty = () => { dirty = true; };
                                form.addEventListener('input', markDirty);
                                form.addEventListener('change', markDirty);
                                form.addEventListener('submit', () => { dirty = false; });
                                window.addEventListener('beforeunload', function (e) {
                                    if (!dirty) return;
                                    e.preventDefault();
                                    e.returnValue = '';
                                });
                            })();
                            (function(){
                                const modal = document.getElementById('benefitModal');
                                if (!modal) return;
                                const openBtn = document.querySelector('[data-open-benefit]');
                                const closeBtns = modal.querySelectorAll('[data-close-benefit]');
                                if (openBtn) {
                                    openBtn.addEventListener('click', function(){
                                        modal.classList.add('open');
                                        modal.setAttribute('aria-hidden', 'false');
                                    });
                                }
                                closeBtns.forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        modal.classList.remove('open');
                                        modal.setAttribute('aria-hidden', 'true');
                                    });
                                });
                            })();
                            (function(){
                                const modal = document.getElementById('helpModal');
                                if (!modal) return;
                                const openBtn = document.querySelector('[data-open-help]');
                                const closeBtns = modal.querySelectorAll('[data-close-help]');
                                if (openBtn) {
                                    openBtn.addEventListener('click', function(){
                                        modal.classList.add('open');
                                        modal.setAttribute('aria-hidden', 'false');
                                    });
                                }
                                closeBtns.forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        modal.classList.remove('open');
                                        modal.setAttribute('aria-hidden', 'true');
                                    });
                                });
                            })();
                            (function(){
                                const drawer = document.getElementById('filterDrawer');
                                if (!drawer) return;
                                const openBtn = document.querySelector('[data-open-filter]');
                                const closeBtn = drawer.querySelector('[data-close-filter]');
                                if (openBtn) {
                                    openBtn.addEventListener('click', function(){
                                        drawer.classList.add('open');
                                        drawer.setAttribute('aria-hidden', 'false');
                                    });
                                }
                                if (closeBtn) {
                                    closeBtn.addEventListener('click', function(){
                                        drawer.classList.remove('open');
                                        drawer.setAttribute('aria-hidden', 'true');
                                    });
                                }
                            })();
                            (function(){
                                const menu = document.getElementById('actionsMenu');
                                const openBtn = document.querySelector('[data-open-actions]');
                                const wrapper = openBtn ? openBtn.closest('.more-actions') : null;
                                if (!menu || !openBtn) return;
                                openBtn.addEventListener('click', function(){
                                    const willOpen = !menu.classList.contains('open');
                                    menu.classList.toggle('open', willOpen);
                                    menu.style.display = willOpen ? 'flex' : 'none';
                                    if (wrapper) {
                                        wrapper.classList.toggle('open', willOpen);
                                    }
                                });
                                document.addEventListener('click', function(e){
                                    if (!menu.contains(e.target) && !openBtn.contains(e.target)) {
                                        menu.classList.remove('open');
                                        menu.style.display = 'none';
                                        if (wrapper) {
                                            wrapper.classList.remove('open');
                                        }
                                    }
                                });
                            })();
                            (function(){
                                const importModal = document.getElementById('importModal');
                                const exportModal = document.getElementById('exportModal');
                                const menu = document.getElementById('actionsMenu');
                                const openImport = document.querySelector('[data-open-import]');
                                const openExport = document.querySelector('[data-open-export]');
                                const closeImport = document.querySelectorAll('[data-close-import]');
                                const closeExport = document.querySelectorAll('[data-close-export]');
                                const closeModal = (modal) => {
                                    if (!modal) return;
                                    modal.classList.remove('open');
                                    modal.setAttribute('aria-hidden', 'true');
                                };
                                if (openImport && importModal) {
                                    openImport.addEventListener('click', function(){
                                        if (exportModal) {
                                            exportModal.classList.remove('open');
                                            exportModal.setAttribute('aria-hidden', 'true');
                                        }
                                        importModal.classList.add('open');
                                        importModal.setAttribute('aria-hidden', 'false');
                                        if (menu) menu.classList.remove('open');
                                    });
                                }
                                if (openExport && exportModal) {
                                    openExport.addEventListener('click', function(){
                                        if (importModal) {
                                            importModal.classList.remove('open');
                                            importModal.setAttribute('aria-hidden', 'true');
                                        }
                                        exportModal.classList.add('open');
                                        exportModal.setAttribute('aria-hidden', 'false');
                                        if (menu) menu.classList.remove('open');
                                    });
                                }
                                closeImport.forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        closeModal(importModal);
                                    });
                                });
                                closeExport.forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        closeModal(exportModal);
                                    });
                                });
                                document.addEventListener('click', function(e){
                                    if (e.target.closest('[data-close-import]')) {
                                        closeModal(importModal);
                                    }
                                    if (e.target.closest('[data-close-export]')) {
                                        closeModal(exportModal);
                                    }
                                });
                            })();
                            (function(){
                                const ctcInput = document.querySelector('[data-ctc]');
                                const percentInput = document.querySelector('[data-basic-percent]');
                                const basicMonthly = document.querySelector('[data-basic-monthly]');
                                const basicAnnual = document.querySelector('[data-basic-annual]');
                                const hraPercent = document.querySelector('[data-hra-percent]');
                                const hraMonthly = document.querySelector('[data-hra-monthly]');
                                const hraAnnual = document.querySelector('[data-hra-annual]');
                                const conveyanceMonthly = document.querySelector('[data-conveyance-monthly]');
                                const conveyanceAnnual = document.querySelector('[data-conveyance-annual]');
                                const fixedMonthly = document.querySelector('[data-fixed-monthly]');
                                const fixedAnnual = document.querySelector('[data-fixed-annual]');
                                const ctcMonthly = document.querySelector('[data-ctc-monthly]');
                                const ctcAnnual = document.querySelector('[data-ctc-annual]');
                                const hraHidden = document.querySelector('[data-hra-enabled-hidden]');
                                const conveyanceHidden = document.querySelector('[data-conveyance-enabled-hidden]');
                                const salaryMenu = document.querySelector('[data-salary-menu]');
                                const menuToggle = document.querySelector('[data-toggle-salary-menu]');
                                if (!ctcInput || !percentInput) return;
                                const toNum = (val) => {
                                    const n = parseFloat(val);
                                    return Number.isFinite(n) ? n : 0;
                                };
                                const fmt = (val) => (Math.round(val * 100) / 100).toFixed(2);
                                const isShown = (key) => {
                                    const row = document.querySelector(`[data-salary-row="${key}"]`);
                                    return !!row && !row.classList.contains('hidden');
                                };
                                const setShown = (key, shown) => {
                                    const row = document.querySelector(`[data-salary-row="${key}"]`);
                                    if (!row) return;
                                    row.classList.toggle('hidden', !shown);
                                    if (key === 'hra' && hraHidden) {
                                        hraHidden.value = shown ? '1' : '0';
                                    }
                                    if (key === 'conveyance' && conveyanceHidden) {
                                        conveyanceHidden.value = shown ? '1' : '0';
                                    }
                                    if (!shown) {
                                        row.querySelectorAll('input[type="number"]').forEach(input => {
                                            if (input.hasAttribute('data-hra-percent')) {
                                                input.value = '50.00';
                                            } else {
                                                input.value = '0.00';
                                            }
                                        });
                                    }
                                };
                                const syncMenu = () => {
                                    if (!salaryMenu) return;
                                    salaryMenu.querySelectorAll('[data-add-salary-row]').forEach(btn => {
                                        btn.hidden = isShown(btn.getAttribute('data-add-salary-row'));
                                    });
                                };
                                const recalc = () => {
                                    const annual = toNum(ctcInput.value);
                                    const percent = toNum(percentInput.value);
                                    const basicAnn = annual * percent / 100;
                                    const basicMon = basicAnn / 12;
                                    const hraAnn = isShown('hra') ? (basicAnn * toNum(hraPercent ? hraPercent.value : 0) / 100) : 0;
                                    const hraMon = hraAnn / 12;
                                    const conveyAnn = isShown('conveyance') ? (toNum(conveyanceMonthly ? conveyanceMonthly.value : 0) * 12) : 0;
                                    const fixedAnn = annual - basicAnn - hraAnn - conveyAnn;
                                    const fixedMon = fixedAnn / 12;
                                    if (basicAnnual) basicAnnual.value = fmt(basicAnn);
                                    if (basicMonthly) basicMonthly.value = fmt(basicMon);
                                    if (hraAnnual) hraAnnual.value = fmt(hraAnn);
                                    if (hraMonthly) hraMonthly.value = fmt(hraMon);
                                    if (conveyanceAnnual) conveyanceAnnual.value = fmt(conveyAnn);
                                    if (fixedAnnual) fixedAnnual.value = fmt(fixedAnn);
                                    if (fixedMonthly) fixedMonthly.value = fmt(fixedMon);
                                    if (ctcMonthly) ctcMonthly.textContent = fmt(annual / 12);
                                    if (ctcAnnual) ctcAnnual.textContent = fmt(annual);
                                    syncMenu();
                                };
                                ctcInput.addEventListener('input', recalc);
                                percentInput.addEventListener('input', recalc);
                                if (hraPercent) hraPercent.addEventListener('input', recalc);
                                if (conveyanceMonthly) conveyanceMonthly.addEventListener('input', recalc);
                                document.querySelectorAll('[data-add-salary-row]').forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        setShown(btn.getAttribute('data-add-salary-row'), true);
                                        if (salaryMenu) salaryMenu.hidden = true;
                                        recalc();
                                    });
                                });
                                document.querySelectorAll('[data-remove-salary-row]').forEach(btn => {
                                    btn.addEventListener('click', function(){
                                        setShown(btn.getAttribute('data-remove-salary-row'), false);
                                        recalc();
                                    });
                                });
                                if (menuToggle && salaryMenu) {
                                    menuToggle.addEventListener('click', function(){
                                        syncMenu();
                                        salaryMenu.hidden = !salaryMenu.hidden;
                                    });
                                    document.addEventListener('click', function(e){
                                        if (!salaryMenu.contains(e.target) && !menuToggle.contains(e.target)) {
                                            salaryMenu.hidden = true;
                                        }
                                    });
                                }
                                recalc();
                            })();
                            (function(){
                                const rows = document.querySelectorAll('[data-emp-link]');
                                if (!rows.length) return;
                                const isInteractive = (el) => {
                                    return !!el.closest('a, button, input, label, select, textarea');
                                };
                                rows.forEach(row => {
                                    row.addEventListener('click', function(e){
                                        if (isInteractive(e.target)) return;
                                        const href = row.getAttribute('data-emp-link');
                                        if (!href) return;
                                        if (e.metaKey || e.ctrlKey) {
                                            window.open(href, '_blank');
                                        } else {
                                            window.location.href = href;
                                        }
                                    });
                                });
                            })();
                        </script>
                    </div>
                </div>
            <?php } ?>
        </section>
    </main>
</div>
<script>
  (function(){
    const toggles = document.querySelectorAll('[data-nav-toggle]');
    toggles.forEach(btn => {
      btn.addEventListener('click', () => {
        const group = btn.closest('.nav-group');
        if (!group) return;
        group.classList.toggle('open');
      });
    });
  })();
  (function(){
    const toolbar = document.getElementById('bulkToolbar');
    const selectedCount = document.getElementById('selectedCount');
    const clearBtn = document.getElementById('bulkClear');
    const selectAll = document.getElementById('selectAllEmployees');
    const rowChecks = Array.from(document.querySelectorAll('.emp-select'));
    if (!toolbar || !selectedCount || !selectAll || !rowChecks.length) return;

    const dropdowns = Array.from(toolbar.querySelectorAll('[data-bulk-dropdown]'));
    const syncToolbar = () => {
      const count = rowChecks.filter(cb => cb.checked).length;
      selectedCount.textContent = String(count);
      selectAll.checked = count > 0 && count === rowChecks.length;
      selectAll.indeterminate = count > 0 && count < rowChecks.length;
      toolbar.classList.toggle('is-hidden', count === 0);
    };

    const clearSelection = () => {
      rowChecks.forEach(cb => {
        cb.checked = false;
      });
      selectAll.checked = false;
      selectAll.indeterminate = false;
      closeDropdowns();
      syncToolbar();
    };

    const closeDropdowns = () => {
      dropdowns.forEach(dd => {
        dd.classList.remove('open');
        const menu = dd.querySelector('.bulk-menu');
        if (menu) menu.hidden = true;
        const trigger = dd.querySelector('[data-bulk-trigger]');
        if (trigger) trigger.setAttribute('aria-expanded', 'false');
      });
    };

    const toggleDropdown = (dd) => {
      const willOpen = !dd.classList.contains('open');
      closeDropdowns();
      dd.classList.toggle('open', willOpen);
      const menu = dd.querySelector('.bulk-menu');
      const trigger = dd.querySelector('[data-bulk-trigger]');
      if (menu) menu.hidden = !willOpen;
      if (trigger) trigger.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
    };

    rowChecks.forEach(cb => cb.addEventListener('change', syncToolbar));
    selectAll.addEventListener('change', function(){
      rowChecks.forEach(cb => {
        cb.checked = selectAll.checked;
      });
      syncToolbar();
    });
    if (clearBtn) {
      clearBtn.addEventListener('click', function(){
        clearSelection();
      });
    }

    dropdowns.forEach(dd => {
      const trigger = dd.querySelector('[data-bulk-trigger]');
      const menu = dd.querySelector('.bulk-menu');
      const items = dd.querySelectorAll('.bulk-menu__item');
      if (trigger && menu) {
        trigger.addEventListener('click', function(event){
          event.stopPropagation();
          toggleDropdown(dd);
        });
      }
      items.forEach(item => {
        item.addEventListener('click', function(){
          closeDropdowns();
          const count = rowChecks.filter(cb => cb.checked).length;
          if (count === 0) {
            alert('Select at least one employee first.');
            return;
          }
          alert(item.textContent.trim() + ' for ' + count + ' selected employee(s).');
        });
      });
    });

    document.addEventListener('click', function(event){
      if (event.target.closest('.bulk-dropdown')) return;
      closeDropdowns();
    });
    document.addEventListener('keydown', function(event){
      if (event.key === 'Escape') {
        closeDropdowns();
        clearSelection();
      }
    });

    syncToolbar();
  })();
  (function(){
    const payOptions = document.querySelectorAll('.pay-opt input[name="pay_method"]');
    const payDetails = document.querySelectorAll('[data-pay-detail]');
    const accountInput = document.querySelector('input[name="account_number"]');
    const accountConfirm = document.querySelector('[data-account-confirm]');
    const syncPayDetails = () => {
      const checked = document.querySelector('.pay-opt input[name="pay_method"]:checked');
      const value = checked ? checked.value : '';
      payDetails.forEach(panel => {
        panel.classList.toggle('is-active', panel.getAttribute('data-pay-detail') === value);
      });
    };
    payOptions.forEach(input => input.addEventListener('change', syncPayDetails));
    if (accountInput && accountConfirm) {
      accountConfirm.addEventListener('input', function(){
        if (accountConfirm.value !== '' && accountInput.value !== accountConfirm.value) {
          accountConfirm.setCustomValidity('Account numbers do not match.');
        } else {
          accountConfirm.setCustomValidity('');
        }
      });
      accountInput.addEventListener('input', function(){
        if (accountConfirm.value !== '' && accountInput.value !== accountConfirm.value) {
          accountConfirm.setCustomValidity('Account numbers do not match.');
        } else {
          accountConfirm.setCustomValidity('');
        }
      });
    }
    syncPayDetails();
  })();
  (function(){
    const combos = document.querySelectorAll('.combo-select');
    if (!combos.length) return;

    const closeAll = (except) => {
      combos.forEach(combo => {
        if (combo === except) return;
        combo.classList.remove('is-open');
        const panel = combo.querySelector('[data-combo-panel]');
        const trigger = combo.querySelector('[data-combo-trigger]');
        if (panel) panel.hidden = true;
        if (trigger) trigger.setAttribute('aria-expanded', 'false');
      });
    };

    const updateCombo = (combo, value) => {
      const input = combo.querySelector('[data-combo-value]');
      const label = combo.querySelector('[data-combo-label]');
      const trigger = combo.querySelector('[data-combo-trigger]');
      const options = combo.querySelectorAll('[data-combo-option]');
      if (input) input.value = value;
      if (label) label.textContent = value || 'Select';
      combo.classList.toggle('has-value', value !== '');
      combo.classList.toggle('is-empty', value === '');
      options.forEach(option => {
        option.classList.toggle('is-selected', option.dataset.value === value);
      });
      if (trigger) trigger.setAttribute('aria-expanded', combo.classList.contains('is-open') ? 'true' : 'false');
    };

    combos.forEach(combo => {
      const trigger = combo.querySelector('[data-combo-trigger]');
      const panel = combo.querySelector('[data-combo-panel]');
      const search = combo.querySelector('[data-combo-search]');
      const clear = combo.querySelector('[data-combo-clear]');
      const options = combo.querySelectorAll('[data-combo-option]');
      const input = combo.querySelector('[data-combo-value]');

      updateCombo(combo, input ? input.value : '');

      if (trigger && panel) {
        trigger.addEventListener('click', function(){
          const willOpen = !combo.classList.contains('is-open');
          closeAll(combo);
          combo.classList.toggle('is-open', willOpen);
          panel.hidden = !willOpen;
          trigger.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
          if (willOpen && search) {
            search.value = '';
            search.focus();
            options.forEach(option => { option.hidden = false; });
          }
        });
      }

      if (search) {
        search.addEventListener('input', function(){
          const query = search.value.trim().toLowerCase();
          options.forEach(option => {
            const text = (option.dataset.value || option.textContent || '').toLowerCase();
            option.hidden = query !== '' && !text.includes(query);
          });
        });
      }

      options.forEach(option => {
        option.addEventListener('click', function(){
          const value = option.dataset.value || '';
          updateCombo(combo, value);
          combo.classList.remove('is-open');
          if (panel) panel.hidden = true;
        });
      });

      if (clear) {
        const clearSelection = function(event){
          if (event) event.preventDefault();
          if (event) event.stopPropagation();
          updateCombo(combo, '');
        };
        clear.addEventListener('click', clearSelection);
        clear.addEventListener('keydown', function(event){
          if (event.key === 'Enter' || event.key === ' ') {
            clearSelection(event);
          }
        });
      }
    });

    document.addEventListener('click', function(event){
      if (event.target.closest('.combo-select')) return;
      closeAll(null);
    });

    document.addEventListener('keydown', function(event){
      if (event.key === 'Escape') {
        closeAll(null);
      }
    });

    const masterModals = {
      combo_work_location: document.getElementById('workLocationCreateModal'),
      combo_designation: document.getElementById('designationCreateModal'),
      combo_department: document.getElementById('departmentCreateModal'),
    };
    const openMasterModal = (key) => {
      const modal = masterModals[key];
      if (!modal) return;
      closeAll(null);
      document.querySelectorAll('.master-modal.open').forEach(closeMasterModal);
      modal.classList.add('open');
      modal.setAttribute('aria-hidden', 'false');
      const firstField = modal.querySelector('input:not([type="hidden"]), select, textarea');
      if (firstField) {
        setTimeout(() => firstField.focus(), 0);
      }
    };
    const closeMasterModal = (modal) => {
      if (!modal) return;
      modal.classList.remove('open');
      modal.setAttribute('aria-hidden', 'true');
    };

    document.querySelectorAll('[data-open-master-modal]').forEach(btn => {
      btn.addEventListener('click', function(){
        openMasterModal(btn.dataset.openMasterModal || '');
      });
    });
    document.querySelectorAll('[data-close-master-modal]').forEach(btn => {
      btn.addEventListener('click', function(){
        closeMasterModal(btn.closest('.master-modal'));
      });
    });
    document.querySelectorAll('.master-modal').forEach(modal => {
      modal.addEventListener('click', function(event){
        if (event.target === modal || event.target.classList.contains('master-backdrop')) {
          closeMasterModal(modal);
        }
      });
    });
    document.addEventListener('keydown', function(event){
      if (event.key === 'Escape') {
        document.querySelectorAll('.master-modal.open').forEach(closeMasterModal);
      }
    });
  })();
</script>
</body>
</html>



