<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);
settings_get_current_org($conn);

$tab = trim((string) ($_GET['tab'] ?? 'earnings'));
$mode = trim((string) ($_GET['mode'] ?? 'list'));
$type = trim((string) ($_GET['type'] ?? $tab));
$componentId = (int) ($_GET['component_id'] ?? ($_POST['component_id'] ?? 0));

$tabs = [
    'earnings' => 'Earnings',
    'deductions' => 'Deductions',
    'benefits' => 'Benefits',
    'reimbursements' => 'Reimbursements',
];

if (!isset($tabs[$tab])) {
    $tab = 'earnings';
}

$lists = [
    'earnings' => [
        ['Basic', 'Basic', 'Fixed; 50% of CTC', 'Yes', 'Yes', 'Active'],
        ['House Rent Allowance', 'House Rent Allowance', 'Fixed; 50% of Basic', 'No', 'Yes', 'Active'],
        ['Conveyance Allowance', 'Conveyance Allowance', 'Fixed; Flat Amount', 'Yes (if PF Wage < 15k)', 'No', 'Active'],
        ['Children Education Allowance', 'Children Education Allowance', 'Fixed; Flat Amount', 'Yes (if PF Wage < 15k)', 'Yes', 'Inactive'],
        ['Transport Allowance', 'Transport Allowance', 'Fixed; Flat amount of 1600', 'Yes (if PF Wage < 15k)', 'Yes', 'Inactive'],
        ['Travelling Allowance', 'Travelling Allowance', 'Fixed; Flat Amount', 'Yes (if PF Wage < 15k)', 'No', 'Inactive'],
        ['Fixed Allowance', 'Fixed Allowance', 'Fixed; Flat Amount', 'Yes (if PF Wage < 15k)', 'Yes', 'Active'],
        ['Overtime Allowance', 'Overtime Allowance', 'Variable; Flat Amount', 'No', 'Yes', 'Inactive'],
        ['Gratuity', 'Gratuity', 'Variable; Flat Amount', 'No', 'No', 'Active'],
        ['Bonus', 'Bonus', 'Variable; Flat Amount', 'No', 'No', 'Active'],
        ['Commission', 'Commission', 'Variable; Flat Amount', 'No', 'Yes', 'Active'],
        ['Leave Encashment', 'Leave Encashment', 'Variable; Flat Amount', 'No', 'No', 'Active'],
        ['Notice Pay', 'Notice Pay', 'Variable; Flat Amount', 'No', 'No', 'Active'],
        ['Hold Salary', 'Hold Salary (Non Taxable)', 'Variable; Flat Amount', 'No', 'No', 'Active'],
    ],
    'deductions' => [
        ['Withheld Salary', 'Withheld Salary', 'One Time', 'Active'],
        ['Notice Pay Deduction', 'Notice Pay Deduction', 'One Time', 'Active'],
    ],
    'benefits' => [
        ['Voluntary Provident Fund', 'Voluntary Provident Fund', 'Recurring', 'Inactive'],
    ],
    'reimbursements' => [
        ['Fuel Reimbursement', 'Fuel Reimbursement', '0', 'Inactive'],
        ['Driver Reimbursement', 'Driver Reimbursement', '0', 'Inactive'],
        ['Vehicle Maintenance Reimbursement', 'Vehicle Maintenance Reimbursement', '0', 'Inactive'],
        ['Telephone Reimbursement', 'Telephone Reimbursement', '0', 'Inactive'],
        ['Leave Travel Allowance', 'Leave Travel Allowance', '0', 'Inactive'],
    ],
];

$accountExpenses = [
    'Office Supplies',
    'Advertising And Marketing',
    'Bank Fees and Charges',
    'Credit Card Charges',
    'Travel Expense',
    'Transportation Expense',
    'Raw Materials And Consumables',
    'Merchandise',
    'Depreciation And Amortisation',
    'Contract Assets',
];

$accountLiabilities = [
    'Tax Payable',
    'Employee Reimbursements',
    'Opening Balance Adjustments',
    'Unearned Revenue',
    'TDS Payable',
    'Salary Payable',
    'PF Payable',
    'ESI Payable',
];

$benefitPlans = [
    'National Pension Scheme',
    'Other Non-Taxable Deduction',
];

$correctionComponents = [
    'Basic',
    'House Rent Allowance',
    'Conveyance Allowance',
    'Fixed Allowance',
    'Bonus',
    'Leave Encashment',
];

$deductionFrequencies = [
    'One-time deduction',
    'Recurring deduction for subsequent Payrolls',
];

$reimbursementTypes = [
    'Fuel Reimbursement',
    'Driver Reimbursement',
    'Vehicle Maintenance Reimbursement',
    'Telephone Reimbursement',
    'Leave Travel Allowance',
];

$reimbursementHandling = [
    'Carry forward and encash at the end of the fiscal year',
    'Do not carry forward and encash monthly',
];

$investments = [
    '80C',
    'Life Insurance Premium',
    'Public Provident Fund',
    'Unit-linked insurance plan',
    'ELSS Tax Saving Mutual Fund',
    'Medi Claim Policy for self, spouse, children - 80D',
    'Medi Claim Policy for self, spouse, children for senior citizen - 80D',
    'Medi Claim Policy for parents - 80D',
    'Medi Claim Policy for parents for senior citizen - 80D',
    'Medical expenditure for self or dependent for senior citizen - 80DDB',
    'Medical expenditure for self or dependent for very senior citizen - 80DDB',
    '80GGC',
    'Donation for political party',
];

function salary_components_slugify(string $value): string
{
    $value = strtolower(trim($value));
    $value = preg_replace('/[^a-z0-9]+/i', '_', $value) ?? '';
    $value = trim($value, '_');
    return $value !== '' ? $value : 'component';
}

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
settings_ensure_salary_component_tables($conn);
settings_seed_salary_components($conn, $orgId);

if (isset($_GET['mark_complete']) && (string) $_GET['mark_complete'] === '1') {
    settings_set_setup_step_state($conn, $orgId, 'salary_components', true);
    $_SESSION['flash_ok'] = 'Salary components marked as completed.';
    header('Location: salary_components.php');
    exit();
}

$saveMessage = '';
$errorMessage = '';
if (isset($_SESSION['flash_ok'])) {
    $saveMessage = (string) $_SESSION['flash_ok'];
    unset($_SESSION['flash_ok']);
}
if (isset($_SESSION['flash_err'])) {
    $errorMessage = (string) $_SESSION['flash_err'];
    unset($_SESSION['flash_err']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['component_action'])) {
    $componentAction = trim((string) $_POST['component_action']);
    $actionTab = trim((string) ($_POST['component_group'] ?? $tab));
    if (!in_array($actionTab, array_keys($tabs), true)) {
        $actionTab = 'earnings';
    }

    if ($componentId <= 0) {
        $errorMessage = 'Unable to find the selected salary component.';
    } elseif ($componentAction === 'toggle_status') {
        $targetStatus = !empty($_POST['target_status']);
        if (settings_update_salary_component_status($conn, $orgId, $componentId, $targetStatus)) {
            $_SESSION['flash_ok'] = $targetStatus ? 'Salary component marked as active.' : 'Salary component marked as inactive.';
            header('Location: salary_components.php?tab=' . urlencode($actionTab));
            exit();
        }
        $errorMessage = 'Unable to update the salary component status.';
    } elseif ($componentAction === 'delete') {
        if (settings_delete_salary_component($conn, $orgId, $componentId)) {
            $_SESSION['flash_ok'] = 'Salary component deleted successfully.';
            header('Location: salary_components.php?tab=' . urlencode($actionTab));
            exit();
        }
        $errorMessage = 'Unable to delete the salary component right now.';
    }
}

$editingComponent = null;
if ($mode === 'edit' && $componentId > 0) {
    $editingComponent = settings_get_salary_component_by_id($conn, $orgId, $componentId);
    if (!$editingComponent) {
        $errorMessage = 'The selected salary component could not be found.';
        $mode = 'list';
    } else {
        $tab = $editingComponent['component_group'] ?? $tab;
        $type = $editingComponent['component_kind'] ?? $type;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_component'])) {
    $componentGroup = trim((string) ($_POST['component_group'] ?? $tab));
    if (!in_array($componentGroup, array_keys($tabs), true)) {
        $componentGroup = $tab;
    }

    $componentKind = trim((string) ($_POST['component_kind'] ?? 'earning'));
    $nameInPayslip = trim((string) ($_POST['name_in_payslip'] ?? ''));
    $displayLabel = trim((string) ($_POST['display_label'] ?? $nameInPayslip));
    $calculationType = trim((string) ($_POST['calculation_type'] ?? ''));
    $frequencyLabel = trim((string) ($_POST['frequency_label'] ?? ''));
    $componentKey = trim((string) ($_POST['component_key'] ?? ''));
    $isActive = !empty($_POST['is_active']);
    $considerForEpf = !empty($_POST['consider_for_epf']);
    $considerForEsi = !empty($_POST['consider_for_esi']);
    $maxAmount = trim((string) ($_POST['max_amount'] ?? ''));

    $extra = [];
    if ($componentKind === 'correction') {
        $extra['correction_for'] = trim((string) ($_POST['correction_for'] ?? ''));
        $calculationType = $calculationType !== '' ? $calculationType : 'Variable; Flat Amount';
    } elseif ($componentGroup === 'benefits') {
        $extra['benefit_plan'] = trim((string) ($_POST['benefit_plan'] ?? ''));
        $extra['associate_investment'] = trim((string) ($_POST['associate_investment'] ?? ''));
        $extra['include_employer_contribution'] = !empty($_POST['include_employer_contribution']);
        $extra['superannuation'] = !empty($_POST['superannuation']);
        $extra['pro_rata'] = !empty($_POST['pro_rata']);
        $extra['debit_account'] = trim((string) ($_POST['debit_account'] ?? ''));
        $extra['credit_account'] = trim((string) ($_POST['credit_account'] ?? ''));
        $frequencyLabel = $frequencyLabel !== '' ? $frequencyLabel : 'Recurring';
    } elseif ($componentGroup === 'deductions') {
        $extra['deduction_frequency'] = $frequencyLabel;
    } elseif ($componentGroup === 'reimbursements') {
        $extra['reimbursement_type'] = trim((string) ($_POST['reimbursement_type'] ?? ''));
        $extra['reimbursement_handling'] = trim((string) ($_POST['reimbursement_handling'] ?? ''));
        $extra['fbp_component'] = !empty($_POST['fbp_component']);
        $extra['name_in_payslip'] = $nameInPayslip;
    } else {
        $extra['pro_rata'] = !empty($_POST['pro_rata']);
    }

    if ($nameInPayslip === '') {
        $errorMessage = 'Name in Payslip is required.';
    } elseif ($componentGroup === 'earnings' && $displayLabel === '') {
        $errorMessage = 'Please choose a salary component type.';
    } elseif ($componentGroup === 'deductions' && $frequencyLabel === '') {
        $errorMessage = 'Please choose a deduction frequency.';
    } elseif ($componentGroup === 'reimbursements' && !isset($extra['reimbursement_type'])) {
        $errorMessage = 'Please choose a reimbursement type.';
    } elseif ($componentGroup === 'benefits' && !isset($extra['benefit_plan'])) {
        $errorMessage = 'Please choose a benefit plan.';
    } else {
        if ($componentKey === '') {
            $componentKey = salary_components_slugify($componentGroup . '_' . $nameInPayslip . '_' . microtime(true));
        }
        $saved = settings_save_salary_component($conn, $orgId, [
            'component_group' => $componentGroup,
            'component_kind' => $componentKind,
            'component_key' => $componentKey,
            'name_in_payslip' => $nameInPayslip,
            'display_label' => $displayLabel !== '' ? $displayLabel : $nameInPayslip,
            'calculation_type' => $calculationType,
            'frequency_label' => $frequencyLabel,
            'consider_for_epf' => $considerForEpf,
            'consider_for_esi' => $considerForEsi,
            'is_active' => $isActive,
            'max_amount' => $maxAmount,
            'extra_json' => $extra,
            'display_order' => 1000,
            'is_default' => 0,
        ]);

        if ($saved) {
            $_SESSION['flash_ok'] = 'Salary component saved successfully.';
            $redirectTab = $componentGroup === 'earnings' ? 'earnings' : $componentGroup;
            header('Location: salary_components.php?tab=' . urlencode($redirectTab));
            exit();
        }

        $errorMessage = 'Unable to save the salary component right now.';
    }
}

$components = settings_get_salary_components($conn, $orgId, $tab);
$componentCount = count($components);
$formComponent = $editingComponent ?? [];
$formExtra = $formComponent['extra'] ?? [];
$formGroup = (string) ($formComponent['component_group'] ?? $tab);
$formKind = (string) ($formComponent['component_kind'] ?? $type);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
  <title>Salary Components | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <style>
    .tabs{display:flex;gap:36px;border-bottom:1px solid var(--border);margin-bottom:2px;}
    .tab-link{padding:0 0 14px;color:#2563eb;text-decoration:none;font-size:16px;font-weight:500;}
    .tab-link.active{color:#111827;border-bottom:3px solid #3b82f6;font-weight:600;}
    .toolbar-actions{display:flex;gap:12px;align-items:center;}
    .menu-wrap{position:relative;}
    .menu-trigger{display:inline-flex;align-items:center;gap:8px;background:#3b82f6;color:#fff;text-decoration:none;padding:10px 14px;border-radius:8px;font-weight:600;border:none;cursor:pointer;font:inherit;}
    .menu-wrap:hover .menu-panel,
    .menu-wrap.open .menu-panel{display:block;}
    .menu-panel{display:none;position:absolute;right:0;top:44px;width:190px;background:#fff;border:1px solid var(--border);border-radius:14px;box-shadow:0 18px 40px rgba(15,23,42,.14);padding:10px;z-index:5;}
    .menu-panel a{display:block;padding:12px 14px;border-radius:8px;color:#374151;text-decoration:none;}
    .menu-panel a:hover,.menu-panel a.active{background:#3b82f6;color:#fff;}
    .table-shell{overflow:auto;}
    .settings-table{width:100%;border-collapse:collapse;min-width:940px;}
    .settings-table th,.settings-table td{padding:16px 0;border-top:1px solid var(--border);text-align:left;vertical-align:middle;}
    .settings-table th{font-size:13px;text-transform:uppercase;color:#111827;}
    .settings-table td{font-size:15px;}
    .name-link{color:#2563eb;text-decoration:none;}
    .status-active{color:#22c55e;font-weight:500;}
    .status-inactive{color:#b7b7b7;font-weight:500;}
    .row-menu{width:24px;height:24px;border:1px solid #d8dde6;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:#a1a1aa;}
    .row-actions{position:relative;display:inline-flex;justify-content:flex-end;min-width:40px;}
    .row-menu-btn{width:24px;height:24px;border:1px solid #d8dde6;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:#fff;color:#94a3b8;cursor:pointer;padding:0;}
    .row-menu-btn:hover{background:#f8fafc;color:#64748b;}
    .row-actions.open .row-menu-panel{display:block;}
    .row-menu-panel{display:none;position:absolute;right:0;top:30px;width:145px;background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 18px 40px rgba(15,23,42,.16);padding:8px;z-index:20;}
    .row-menu-panel a,
    .row-menu-panel button{display:block;width:100%;border:none;background:transparent;padding:11px 12px;border-radius:8px;text-align:left;font:inherit;color:#374151;text-decoration:none;cursor:pointer;}
    .row-menu-panel a:hover,
    .row-menu-panel button:hover{background:#3b82f6;color:#fff;}
    .row-menu-form{margin:0;}
    .list-foot{display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--border);padding-top:18px;margin-top:8px;font-size:16px;}
    .pager{display:flex;align-items:center;border:1px solid #d9dde7;border-radius:10px;overflow:hidden;}
    .pager span,.pager a{padding:11px 16px;text-decoration:none;color:#111827;background:#fff;}
    .pager .sel{display:flex;gap:8px;align-items:center;background:#f8fafc;border-right:1px solid #d9dde7;}
    .page-note{background:#fff8e1;border:1px solid #fde7a9;border-radius:10px;padding:14px 18px;margin:0 0 14px;display:flex;gap:12px;align-items:flex-start;font-size:15px;}
    .form-limit{max-width:1120px;}
    .form-block{max-width:560px;margin-top:22px;}
    .form-block label{display:block;font-size:16px;font-weight:600;margin-bottom:10px;}
    .form-block input,.form-block select,.form-block textarea{width:100%;height:52px;border:1px solid #d7dce7;border-radius:10px;padding:0 14px;font-size:15px;background:#fff;}
    .form-block textarea{height:76px;padding:12px 14px;resize:vertical;}
    .form-row{display:grid;grid-template-columns:1fr 1fr;gap:20px;max-width:880px;}
    .inline-help{font-size:15px;line-height:1.55;color:#374151;margin:18px 0 0;max-width:760px;}
    .field-rule{display:flex;align-items:center;gap:10px;font-size:16px;margin-top:16px;}
    .field-rule input{width:20px;height:20px;accent-color:#3b82f6;}
    .note-card{margin-top:18px;max-width:760px;background:#fff8e1;border:1px solid #fde7a9;border-radius:10px;padding:16px 18px;font-size:15px;line-height:1.6;color:#374151;}
    .page-actions{display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--border);margin-top:30px;padding-top:22px;}
    .left-actions{display:flex;gap:16px;align-items:center;}
    .save-btn{display:inline-flex;align-items:center;justify-content:center;background:#3b82f6;color:#fff;border:none;border-radius:8px;padding:11px 18px;font-weight:600;text-decoration:none;}
    .cancel-btn{display:inline-flex;align-items:center;justify-content:center;background:#fff;border:1px solid #d1d5db;color:#374151;border-radius:8px;padding:11px 18px;font-weight:600;text-decoration:none;}
    .required-copy{color:#ff2d55;font-size:15px;}
    .combo{position:relative;}
    .combo > button{width:100%;height:52px;border:1px solid #d7dce7;border-radius:10px;padding:0 14px;background:#fff;font-size:15px;text-align:left;color:#374151;display:flex;align-items:center;justify-content:space-between;}
    .combo-panel{display:block;border:1px solid #d7dce7;border-radius:12px;background:#fff;box-shadow:0 20px 40px rgba(15,23,42,.14);padding:10px;margin-top:10px;max-width:470px;}
    .combo-search{display:flex;align-items:center;gap:10px;border:1px solid #cfd6e2;border-radius:8px;padding:10px 12px;}
    .combo-search input{border:none;outline:none;height:auto;padding:0;font-size:15px;width:100%;}
    .combo-options{margin-top:10px;max-height:210px;overflow:auto;}
    .combo-options div{padding:12px 12px;border-radius:8px;font-size:15px;line-height:1.35;}
    .combo-options div.active{background:#3b82f6;color:#fff;}
    .combo-options .section{font-weight:700;color:#111827;padding-bottom:4px;}
    .muted{color:#6b7280;font-size:13px;}
    @media (max-width: 1100px){
      .form-row{grid-template-columns:1fr;}
      .page-actions{flex-direction:column;align-items:flex-start;gap:16px;}
    }
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-wallet'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('salary_components'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1>Salary Components</h1>
        <div class="toolbar-actions">
          <div class="menu-wrap">
            <button class="menu-trigger" type="button" data-menu-trigger aria-haspopup="true" aria-expanded="false">Add Component <i class="fa-solid fa-angle-down"></i></button>
            <div class="menu-panel">
              <a href="salary_components.php?tab=earnings&mode=new&type=earning">Earning</a>
              <a href="salary_components.php?tab=earnings&mode=new&type=correction">Correction</a>
              <a href="salary_components.php?tab=benefits&mode=new&type=benefit">Benefit</a>
              <a href="salary_components.php?tab=deductions&mode=new&type=deduction">Deduction</a>
              <a class="<?php echo $tab === 'reimbursements' ? 'active' : ''; ?>" href="salary_components.php?tab=reimbursements">Reimbursement</a>
            </div>
          </div>
        </div>
      </div>

      <div class="profile-card">
        <?php if ($saveMessage !== ''): ?>
          <div class="alert-ok" style="margin-bottom:18px;"><?php echo htmlspecialchars($saveMessage); ?></div>
        <?php endif; ?>
        <?php if ($errorMessage !== ''): ?>
          <div class="alert-err" style="margin-bottom:18px;"><?php echo htmlspecialchars($errorMessage); ?></div>
        <?php endif; ?>
        <?php if ($mode === 'list'): ?>
          <div class="tabs">
            <?php foreach ($tabs as $tabKey => $tabLabel): ?>
              <a class="tab-link <?php echo $tabKey === $tab ? 'active' : ''; ?>" href="salary_components.php?tab=<?php echo urlencode($tabKey); ?>"><?php echo htmlspecialchars($tabLabel); ?></a>
            <?php endforeach; ?>
          </div>

          <?php if ($tab === 'reimbursements'): ?>
            <div class="page-note">
              <span style="color:#fb923c;font-size:18px;"><i class="fa-solid fa-circle-info"></i></span>
              <div>With these reimbursement components, employees can claim reimbursements for the components which are part of the payroll and not for other expenses reimbursements.</div>
            </div>
          <?php endif; ?>

          <div class="table-shell">
            <table class="settings-table">
              <thead>
                <tr>
                  <?php if ($tab === 'earnings'): ?>
                    <th style="width:22%;">Name</th><th style="width:21%;">Earning Type</th><th style="width:21%;">Calculation Type</th><th style="width:15%;">Consider for EPF</th><th style="width:15%;">Consider for ESI</th><th>Status</th><th style="width:40px;"></th>
                  <?php elseif ($tab === 'deductions'): ?>
                    <th style="width:30%;">Name</th><th style="width:28%;">Deduction Type</th><th style="width:28%;">Deduction Frequency</th><th>Status</th><th style="width:40px;"></th>
                  <?php elseif ($tab === 'benefits'): ?>
                    <th style="width:34%;">Name</th><th style="width:32%;">Benefit Type</th><th style="width:24%;">Benefit Frequency</th><th>Status</th><th style="width:40px;"></th>
                  <?php else: ?>
                    <th style="width:32%;">Name</th><th style="width:30%;">Reimbursement Type</th><th style="width:28%;">Maximum Reimbursable Amount</th><th>Status</th><th style="width:40px;"></th>
                  <?php endif; ?>
                </tr>
              </thead>
              <tbody>
                <?php if (!$components): ?>
                  <tr>
                    <td colspan="<?php echo $tab === 'earnings' ? 7 : 5; ?>" style="padding:24px 0;color:#6b7280;">No salary components found.</td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($components as $row): ?>
                    <?php $isActive = (int) ($row['is_active'] ?? 0) === 1; ?>
                    <tr>
                      <td><a class="name-link" href="salary_components.php?tab=<?php echo urlencode($tab); ?>&mode=edit&component_id=<?php echo (int) ($row['id'] ?? 0); ?>"><?php echo htmlspecialchars((string) ($row['name_in_payslip'] ?? '')); ?></a></td>
                      <td><?php echo htmlspecialchars((string) ($row['display_label'] ?? '-')); ?></td>
                      <td><?php echo htmlspecialchars((string) ($row['calculation_type'] ?? ($row['frequency_label'] ?? '-'))); ?></td>
                      <?php if ($tab === 'earnings'): ?>
                        <td><?php echo !empty($row['consider_for_epf']) ? 'Yes' : 'No'; ?></td>
                        <td><?php echo !empty($row['consider_for_esi']) ? 'Yes' : 'No'; ?></td>
                        <td class="<?php echo $isActive ? 'status-active' : 'status-inactive'; ?>"><?php echo $isActive ? 'Active' : 'Inactive'; ?></td>
                      <?php else: ?>
                        <?php if ($tab === 'reimbursements'): ?>
                          <td><?php echo htmlspecialchars($row['max_amount'] !== null && $row['max_amount'] !== '' ? number_format((float) $row['max_amount'], 2) : '0'); ?></td>
                        <?php elseif ($tab === 'benefits'): ?>
                          <td><?php echo htmlspecialchars((string) ($row['frequency_label'] ?? 'Recurring')); ?></td>
                        <?php else: ?>
                          <td><?php echo htmlspecialchars((string) ($row['frequency_label'] ?? 'One Time')); ?></td>
                        <?php endif; ?>
                        <td class="<?php echo $isActive ? 'status-active' : 'status-inactive'; ?>"><?php echo $isActive ? 'Active' : 'Inactive'; ?></td>
                      <?php endif; ?>
                      <td>
                        <div class="row-actions">
                          <button class="row-menu-btn" type="button" data-row-menu-trigger aria-haspopup="true" aria-expanded="false" aria-label="Row actions">
                            <i class="fa-solid fa-ellipsis"></i>
                          </button>
                          <div class="row-menu-panel">
                            <a href="salary_components.php?tab=<?php echo urlencode($tab); ?>&mode=edit&component_id=<?php echo (int) ($row['id'] ?? 0); ?>">Edit</a>
                            <form class="row-menu-form" method="post">
                              <input type="hidden" name="component_action" value="toggle_status">
                              <input type="hidden" name="component_id" value="<?php echo (int) ($row['id'] ?? 0); ?>">
                              <input type="hidden" name="component_group" value="<?php echo htmlspecialchars($tab); ?>">
                              <input type="hidden" name="target_status" value="<?php echo $isActive ? '0' : '1'; ?>">
                              <button type="submit"><?php echo $isActive ? 'Mark as Inactive' : 'Mark as Active'; ?></button>
                            </form>
                            <form class="row-menu-form" method="post" onsubmit="return confirm('Delete this salary component?');">
                              <input type="hidden" name="component_action" value="delete">
                              <input type="hidden" name="component_id" value="<?php echo (int) ($row['id'] ?? 0); ?>">
                              <input type="hidden" name="component_group" value="<?php echo htmlspecialchars($tab); ?>">
                              <button type="submit">Delete</button>
                            </form>
                          </div>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="list-foot">
            <div>Total Count: <a class="name-link" href="#"><?php echo (int) $componentCount; ?></a></div>
            <div class="pager">
              <span class="sel"><i class="fa-solid fa-gear"></i> 200 per page</span>
              <span><i class="fa-solid fa-angle-left" style="color:#cbd5e1;"></i></span>
              <span><?php echo $componentCount > 0 ? '1 - ' . (int) $componentCount : '0 - 0'; ?></span>
              <span><i class="fa-solid fa-angle-right" style="color:#94a3b8;"></i></span>
            </div>
          </div>
        <?php elseif ($type === 'earning' || ($mode === 'edit' && $formKind === 'earning')): ?>
          <div class="form-limit">
            <h2 style="font-size:24px;margin:4px 0 28px;"><?php echo $mode === 'edit' && $formKind === 'earning' ? 'Edit Earning' : 'New Earning'; ?></h2>
            <form method="post">
              <input type="hidden" name="save_component" value="1">
              <input type="hidden" name="component_group" value="earnings">
              <input type="hidden" name="component_kind" value="earning">
              <input type="hidden" name="component_key" value="<?php echo htmlspecialchars((string) ($formComponent['component_key'] ?? '')); ?>">
              <div class="form-block">
                <label for="earning_name">Name in Payslip <span class="req">*</span></label>
                <input id="earning_name" name="name_in_payslip" type="text" placeholder="Basic" value="<?php echo htmlspecialchars((string) ($formComponent['name_in_payslip'] ?? '')); ?>">
              </div>
              <div class="form-row">
                <div class="form-block" style="margin-top:0;">
                  <label for="earning_type">Choose Earning Type <span class="req">*</span></label>
                  <select id="earning_type" name="display_label">
                    <?php foreach (['Basic', 'House Rent Allowance', 'Conveyance Allowance', 'Fixed Allowance', 'Bonus', 'Leave Encashment', 'Notice Pay'] as $index => $item): ?>
                      <option <?php echo (string) ($formComponent['display_label'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-block" style="margin-top:0;">
                  <label>Calculation Type</label>
                  <select name="calculation_type">
                    <?php foreach (['Fixed; 50% of CTC', 'Fixed; 50% of Basic', 'Fixed; Flat Amount', 'Fixed; Flat amount of 1600', 'Variable; Flat Amount'] as $index => $item): ?>
                      <option <?php echo (string) ($formComponent['calculation_type'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <label class="field-rule"><input type="checkbox" name="consider_for_epf" <?php echo !empty($formComponent['consider_for_epf']) ? 'checked' : ''; ?>> Consider for EPF</label>
              <label class="field-rule"><input type="checkbox" name="consider_for_esi" <?php echo !empty($formComponent['consider_for_esi']) ? 'checked' : ''; ?>> Consider for ESI</label>
              <label class="field-rule"><input type="checkbox" name="pro_rata" <?php echo !empty($formExtra['pro_rata']) ? 'checked' : ''; ?>> Calculate on pro-rata basis</label>
              <label class="field-rule"><input type="checkbox" name="is_active" <?php echo $mode === 'edit' ? (!empty($formComponent['is_active']) ? 'checked' : '') : 'checked'; ?>> Mark this as Active</label>
              <div class="note-card">Once you associate this earning with an employee, you can still update it here for future pay runs. The change will be available for new salary structures.</div>
              <div class="page-actions">
                <div class="left-actions"><button class="save-btn" type="submit">Save</button><a class="cancel-btn" href="salary_components.php?tab=earnings">Cancel</a></div>
                <div class="required-copy">* indicates mandatory fields</div>
              </div>
            </form>
          </div>
        <?php elseif ($type === 'correction' || ($mode === 'edit' && $formKind === 'correction')): ?>
          <div class="form-limit">
            <h2 style="font-size:24px;margin:4px 0 28px;"><?php echo $mode === 'edit' && $formKind === 'correction' ? 'Edit Correction Component' : 'New Correction Component'; ?></h2>
            <form method="post">
              <input type="hidden" name="save_component" value="1">
              <input type="hidden" name="component_group" value="earnings">
              <input type="hidden" name="component_kind" value="correction">
              <input type="hidden" name="calculation_type" value="Variable; Flat Amount">
              <input type="hidden" name="component_key" value="<?php echo htmlspecialchars((string) ($formComponent['component_key'] ?? '')); ?>">
              <div class="form-block">
                <label for="correction_name">Name in Payslip <span class="req">*</span></label>
                <input id="correction_name" name="name_in_payslip" type="text" placeholder="Basic Correction" value="<?php echo htmlspecialchars((string) ($formComponent['name_in_payslip'] ?? '')); ?>">
              </div>
              <div class="form-block">
                <label for="correction_for">Create Correction for <span class="req">*</span></label>
                <select id="correction_for" name="display_label">
                  <?php foreach ($correctionComponents as $index => $item): ?>
                    <option <?php echo (string) ($formComponent['display_label'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <label class="field-rule"><input type="checkbox" name="is_active" <?php echo $mode === 'edit' ? (!empty($formComponent['is_active']) ? 'checked' : '') : 'checked'; ?>> Mark this as Active</label>
              <div class="note-card">Corrections are stored against the earnings library and can be reused when salary revisions or payroll adjustments are needed.</div>
              <div class="page-actions">
                <div class="left-actions"><button class="save-btn" type="submit">Save</button><a class="cancel-btn" href="salary_components.php?tab=earnings">Cancel</a></div>
                <div class="required-copy">* indicates mandatory fields</div>
              </div>
            </form>
          </div>
        <?php elseif ($type === 'benefit' || ($mode === 'edit' && $formKind === 'benefit')): ?>
          <div class="form-limit">
            <h2 style="font-size:24px;margin:4px 0 28px;"><?php echo $mode === 'edit' && $formKind === 'benefit' ? 'Edit Benefit' : 'New Benefit'; ?></h2>
            <form method="post">
              <input type="hidden" name="save_component" value="1">
              <input type="hidden" name="component_group" value="benefits">
              <input type="hidden" name="component_kind" value="benefit">
              <input type="hidden" name="frequency_label" value="Recurring">
              <input type="hidden" name="component_key" value="<?php echo htmlspecialchars((string) ($formComponent['component_key'] ?? '')); ?>">
              <div class="form-row">
                <div class="form-block" style="margin-top:0;">
                  <label for="benefit_plan">Benefit Plan</label>
                  <select id="benefit_plan" name="benefit_plan">
                    <?php foreach ($benefitPlans as $index => $item): ?>
                      <option <?php echo (string) ($formExtra['benefit_plan'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-block" style="margin-top:0;">
                  <label for="associate_investment">Associate this benefit with</label>
                  <select id="associate_investment" name="associate_investment">
                    <?php foreach ($investments as $index => $item): ?>
                      <option <?php echo (string) ($formExtra['associate_investment'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="form-block"><label for="benefit_name">Name in Payslip <span class="req">*</span></label><input id="benefit_name" name="name_in_payslip" type="text" placeholder="Voluntary Provident Fund" value="<?php echo htmlspecialchars((string) ($formComponent['name_in_payslip'] ?? '')); ?>"></div>
              <div class="form-row">
                <div class="form-block" style="margin-top:0;">
                  <label for="debit_account">Debit Account</label>
                  <select id="debit_account" name="debit_account">
                    <?php foreach ($accountExpenses as $index => $item): ?>
                      <option <?php echo (string) ($formExtra['debit_account'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-block" style="margin-top:0;">
                  <label for="credit_account">Credit Account</label>
                  <select id="credit_account" name="credit_account">
                    <?php foreach ($accountLiabilities as $index => $item): ?>
                      <option <?php echo (string) ($formExtra['credit_account'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <label class="field-rule"><input type="checkbox" name="include_employer_contribution" <?php echo !empty($formExtra['include_employer_contribution']) ? 'checked' : ''; ?>> Include employer's contribution in employee's salary structure.</label>
              <label class="field-rule"><input type="checkbox" name="superannuation" <?php echo !empty($formExtra['superannuation']) ? 'checked' : ''; ?>> Consider this a superannuation fund</label>
              <label class="field-rule"><input type="checkbox" name="pro_rata" <?php echo !empty($formExtra['pro_rata']) ? 'checked' : ''; ?>> Calculate on pro-rata basis</label>
              <div class="muted" style="margin-left:30px;">Pay will be adjusted based on employee working days.</div>
              <label class="field-rule"><input type="checkbox" name="is_active" <?php echo $mode === 'edit' ? (!empty($formComponent['is_active']) ? 'checked' : '') : 'checked'; ?>> Mark this as Active</label>
              <div class="note-card">Note: Once you associate this benefit with an employee, you will only be able to edit the Name in Payslip. The change will be reflected in both new and existing employees.</div>
              <div class="page-actions">
                <div class="left-actions"><button class="save-btn" type="submit">Save</button><a class="cancel-btn" href="salary_components.php?tab=benefits">Cancel</a></div>
                <div class="required-copy">* indicates mandatory fields</div>
              </div>
            </form>
          </div>
        <?php elseif ($type === 'deduction' || ($mode === 'edit' && $formKind === 'deduction')): ?>
          <div class="form-limit">
            <h2 style="font-size:24px;margin:4px 0 28px;"><?php echo $mode === 'edit' && $formKind === 'deduction' ? 'Edit Deduction' : 'New Deduction'; ?></h2>
            <form method="post">
              <input type="hidden" name="save_component" value="1">
              <input type="hidden" name="component_group" value="deductions">
              <input type="hidden" name="component_kind" value="deduction">
              <input type="hidden" name="component_key" value="<?php echo htmlspecialchars((string) ($formComponent['component_key'] ?? '')); ?>">
              <div class="form-block">
                <label for="deduction_name">Name in Payslip <span class="req">*</span></label>
                <input id="deduction_name" name="name_in_payslip" type="text" placeholder="Withheld Salary" value="<?php echo htmlspecialchars((string) ($formComponent['name_in_payslip'] ?? '')); ?>">
              </div>
              <div class="form-block">
                <label>Select the deduction frequency <span class="req">*</span></label>
                <div class="checkbox-stack" style="gap:8px;">
                  <?php foreach ($deductionFrequencies as $index => $item): ?>
                    <label class="check-item<?php echo $index === 0 ? '' : ' child'; ?>"><input type="radio" name="frequency_label" value="<?php echo htmlspecialchars($item); ?>" <?php echo (string) ($formComponent['frequency_label'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'checked' : ''; ?>><span><?php echo htmlspecialchars($item); ?></span></label>
                  <?php endforeach; ?>
                </div>
              </div>
              <label class="field-rule"><input type="checkbox" name="is_active" <?php echo $mode === 'edit' ? (!empty($formComponent['is_active']) ? 'checked' : '') : 'checked'; ?>> Mark this as Active</label>
              <div class="note-card">Note: Once you associate this deduction with an employee, you will only be able to edit the Name in Payslip. The change will be reflected in both new and existing employees.</div>
              <div class="page-actions">
                <div class="left-actions"><button class="save-btn" type="submit">Save</button><a class="cancel-btn" href="salary_components.php?tab=deductions">Cancel</a></div>
                <div class="required-copy">* indicates mandatory fields</div>
              </div>
            </form>
          </div>
        <?php elseif ($type === 'reimbursement' || ($mode === 'edit' && $formKind === 'reimbursement')): ?>
          <div class="form-limit">
            <h2 style="font-size:24px;margin:4px 0 28px;"><?php echo $mode === 'edit' && $formKind === 'reimbursement' ? 'Edit Reimbursement' : 'New Reimbursement'; ?></h2>
            <form method="post">
              <input type="hidden" name="save_component" value="1">
              <input type="hidden" name="component_group" value="reimbursements">
              <input type="hidden" name="component_kind" value="reimbursement">
              <input type="hidden" name="component_key" value="<?php echo htmlspecialchars((string) ($formComponent['component_key'] ?? '')); ?>">
              <div class="form-block">
                <label for="reimbursement_type">Reimbursement Type <span class="req">*</span></label>
                <select id="reimbursement_type" name="reimbursement_type">
                  <?php foreach ($reimbursementTypes as $index => $item): ?>
                    <option <?php echo (string) ($formExtra['reimbursement_type'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'selected' : ''; ?>><?php echo htmlspecialchars($item); ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="form-block"><label for="reimbursement_name">Name in Payslip <span class="req">*</span></label><input id="reimbursement_name" name="name_in_payslip" type="text" placeholder="Fuel Reimbursement" value="<?php echo htmlspecialchars((string) ($formComponent['name_in_payslip'] ?? '')); ?>"></div>
              <label class="field-rule"><input type="checkbox" name="fbp_component" <?php echo !empty($formExtra['fbp_component']) ? 'checked' : ''; ?>> Include this as a Flexible Benefit Plan component</label>
              <div class="muted" style="margin-left:30px;">FBP allows your employees to personalise their salary structure by choosing how much they want to receive under each FBP component.</div>
              <div class="form-block">
                <label>How do you want to handle unclaimed reimbursement?</label>
                <div class="checkbox-stack" style="gap:8px;">
                  <?php foreach ($reimbursementHandling as $index => $item): ?>
                    <label class="check-item"><input type="radio" name="reimbursement_handling" value="<?php echo htmlspecialchars($item); ?>" <?php echo (string) ($formExtra['reimbursement_handling'] ?? '') === $item || ($mode !== 'edit' && $index === 0) ? 'checked' : ''; ?>><span><?php echo htmlspecialchars($item); ?></span></label>
                  <?php endforeach; ?>
                </div>
              </div>
              <div class="form-block">
                <label for="reimbursement_amount">Enter Amount <span class="req">*</span></label>
                <div style="display:flex;align-items:center;gap:10px;max-width:320px;">
                  <span style="color:#6b7280;font-size:18px;">â‚¹</span>
                  <input id="reimbursement_amount" name="max_amount" type="number" min="0" step="0.01" value="<?php echo htmlspecialchars((string) ($formComponent['max_amount'] ?? '0')); ?>" style="flex:1;">
                  <span style="color:#374151;">per month</span>
                </div>
              </div>
              <label class="field-rule"><input type="checkbox" name="is_active" <?php echo $mode === 'edit' ? (!empty($formComponent['is_active']) ? 'checked' : '') : 'checked'; ?>> Mark this as Active</label>
              <div class="note-card">Note: Once you associate this component with an employee, you will only be able to edit the Name in Payslip and Amount. The changes you make to Amount will apply only to new employees.</div>
              <div class="page-actions">
                <div class="left-actions"><button class="save-btn" type="submit">Save</button><a class="cancel-btn" href="salary_components.php?tab=reimbursements">Cancel</a></div>
                <div class="required-copy">* indicates mandatory fields</div>
              </div>
            </form>
          </div>
        <?php endif; ?>
      </div>
    </section>
  </main>
  <script>
    (function(){
      const wrap = document.querySelector('.menu-wrap');
      const trigger = document.querySelector('[data-menu-trigger]');
      const rowMenus = Array.from(document.querySelectorAll('.row-actions'));

      if (wrap && trigger) {
        trigger.addEventListener('click', function (event) {
          event.preventDefault();
          const open = wrap.classList.toggle('open');
          trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
        });

        document.addEventListener('click', function (event) {
          if (!wrap.contains(event.target)) {
            wrap.classList.remove('open');
            trigger.setAttribute('aria-expanded', 'false');
          }
        });
      }

      rowMenus.forEach(function (menu) {
        const button = menu.querySelector('[data-row-menu-trigger]');
        if (!button) {
          return;
        }

        button.addEventListener('click', function (event) {
          event.preventDefault();
          event.stopPropagation();

          rowMenus.forEach(function (other) {
            if (other !== menu) {
              other.classList.remove('open');
              const otherButton = other.querySelector('[data-row-menu-trigger]');
              if (otherButton) {
                otherButton.setAttribute('aria-expanded', 'false');
              }
            }
          });

          const open = menu.classList.toggle('open');
          button.setAttribute('aria-expanded', open ? 'true' : 'false');
        });
      });

      document.addEventListener('click', function (event) {
        rowMenus.forEach(function (menu) {
          if (!menu.contains(event.target)) {
            menu.classList.remove('open');
            const button = menu.querySelector('[data-row-menu-trigger]');
            if (button) {
              button.setAttribute('aria-expanded', 'false');
            }
          }
        });
      });
    })();
  </script>
</body>
</html>

