<?php
require_once __DIR__ . '/includes/settings_helpers.php';
require_once __DIR__ . '/includes/tax_forms_module.php';

settings_require_auth();
settings_ensure_tables($conn);
$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$orgName = $_SESSION['org_name'] ?? 'demo';
$templateCode = 'standard';
$saveMessage = '';
$errorMessage = '';
$template = settings_get_salary_template($conn, $orgId, $templateCode);
settings_ensure_audit_tables($conn);
settings_ensure_employee_organization_column($conn, $orgId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $previousTemplate = $template;
    $status = (float) ($_POST['annual_ctc'] ?? 0) > 0 ? 'Active' : 'Draft';
    $template = [
        'template_code' => $templateCode,
        'template_name' => trim((string) ($_POST['template_name'] ?? 'Standard Salary Template')),
        'annual_ctc' => max(0, (float) ($_POST['annual_ctc'] ?? 0)),
        'basic_percent' => max(0, min(100, (float) ($_POST['basic_percent'] ?? 50))),
        'hra_enabled' => (int) (!empty($_POST['hra_enabled'])),
        'hra_percent' => max(0, (float) ($_POST['hra_percent'] ?? 50)),
        'conveyance_enabled' => (int) (!empty($_POST['conveyance_enabled'])),
        'conveyance_monthly' => max(0, (float) ($_POST['conveyance_monthly'] ?? 0)),
        'is_default' => 1,
        'status' => $status,
    ];

    if (settings_upsert_salary_template($conn, $orgId, $template)) {
        $saveMessage = 'Salary template saved successfully.';
        $template = settings_get_salary_template($conn, $orgId, $templateCode);
        settings_set_setup_step_state($conn, $orgId, 'salary_components', (float) ($template['annual_ctc'] ?? 0) > 0);
        settings_log_salary_template_history(
            $conn,
            $orgId,
            $templateCode,
            !empty($previousTemplate['id']) ? 'updated' : 'created',
            (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
            $previousTemplate,
            $template
        );
    } else {
        $errorMessage = 'Unable to save the salary template right now.';
    }
}

$templateName = (string) ($template['template_name'] ?? 'Standard Salary Template');
$annualCtc = number_format((float) ($template['annual_ctc'] ?? 0), 2, '.', '');
$basicPercent = number_format((float) ($template['basic_percent'] ?? 50), 2, '.', '');
$hraEnabled = !empty($template['hra_enabled']);
$hraPercent = number_format((float) ($template['hra_percent'] ?? 50), 2, '.', '');
$conveyanceEnabled = !empty($template['conveyance_enabled']);
$conveyanceMonthly = number_format((float) ($template['conveyance_monthly'] ?? 0), 2, '.', '');
$annualCtcValue = (float) ($template['annual_ctc'] ?? 0);
$basicAnnualValue = $annualCtcValue * ((float) ($template['basic_percent'] ?? 50) / 100);
$hraAnnualValue = $hraEnabled ? ($basicAnnualValue * ((float) ($template['hra_percent'] ?? 50) / 100)) : 0;
$conveyanceAnnualValue = $conveyanceEnabled ? ((float) ($template['conveyance_monthly'] ?? 0) * 12) : 0;
$fixedAnnualValue = max(0, $annualCtcValue - $basicAnnualValue - $hraAnnualValue - $conveyanceAnnualValue);
$templateReady = $annualCtcValue > 0;

$taxDetails = tax_details_get($conn, (string) ($org['id'] ?? ($_SESSION['org_id'] ?? '')));
$paySchedule = settings_get_pay_schedule($conn, $orgId);
$epfSettings = settings_get_statutory_component($conn, $orgId, 'epf');
$esiSettings = settings_get_statutory_component($conn, $orgId, 'esi');
$lwfSettings = settings_get_statutory_component($conn, $orgId, 'lwf');

$employeeCount = 0;
$employeeCountStmt = $conn->prepare("SELECT COUNT(*) AS total FROM employees WHERE organization_id = ? AND COALESCE(is_deleted, 0) = 0");
if ($employeeCountStmt) {
    $employeeCountStmt->bind_param('i', $orgId);
    $employeeCountStmt->execute();
    $employeeCountResult = $employeeCountStmt->get_result();
    if ($employeeCountResult && ($employeeCountRow = $employeeCountResult->fetch_assoc())) {
        $employeeCount = (int) ($employeeCountRow['total'] ?? 0);
    }
    $employeeCountStmt->close();
}

$payrunCount = 0;
$payrunCountStmt = $conn->prepare("SELECT COUNT(*) AS total FROM payruns WHERE org_id = ?");
if ($payrunCountStmt) {
    $payrunCountStmt->bind_param('s', $orgName);
    $payrunCountStmt->execute();
    $payrunCountResult = $payrunCountStmt->get_result();
    if ($payrunCountResult && ($payrunCountRow = $payrunCountResult->fetch_assoc())) {
        $payrunCount = (int) ($payrunCountRow['total'] ?? 0);
    }
    $payrunCountStmt->close();
}

$profileComplete = trim((string) ($org['organisation_name'] ?? '')) !== '' && trim((string) ($org['address_line1'] ?? '')) !== '' && trim((string) ($org['state'] ?? '')) !== '';
$taxComplete = trim((string) ($taxDetails['pan'] ?? '')) !== '' && trim((string) ($taxDetails['deductor_name'] ?? '')) !== '';
$payScheduleComplete = !empty($paySchedule['pay_frequency']) && !empty($paySchedule['first_pay_date']);
$statutorySubitems = [
    ['label' => "Employees' Provident Fund", 'href' => 'statutory_components.php?component=epf', 'complete' => !empty($epfSettings['enabled'])],
    ['label' => "Employees' State Insurance", 'href' => 'statutory_components.php?component=esi', 'complete' => !empty($esiSettings['enabled'])],
    ['label' => 'Labour Welfare Fund', 'href' => 'statutory_components.php?component=lwf', 'complete' => !empty($lwfSettings['enabled'])],
    ['label' => 'Professional Tax', 'href' => 'tax_details.php', 'complete' => $taxComplete, 'note' => 'Configured based on Work Location'],
];
$statutoryComplete = count(array_filter($statutorySubitems, static function (array $item): bool {
    return !empty($item['complete']);
})) === count($statutorySubitems);
$statutoryManualComplete = settings_get_setup_step_state($conn, $orgId, 'statutory_components');
$statutoryComplete = $statutoryComplete || $statutoryManualComplete;
$salaryManualComplete = settings_get_setup_step_state($conn, $orgId, 'salary_components');
$salaryComplete = (float) ($template['annual_ctc'] ?? 0) > 0 || $salaryManualComplete;
$employeesComplete = $employeeCount > 0;
$priorPayrollComplete = $payrunCount > 0;
$zohoBooksComplete = true;

$setupSteps = [
    ['label' => '1. Add Organisation Details', 'completed' => $profileComplete],
    ['label' => '2. Provide your Tax Details', 'completed' => $taxComplete],
    ['label' => '3. Configure your Pay Schedule', 'completed' => $payScheduleComplete],
    ['label' => '4. Set up Statutory Components', 'completed' => $statutoryComplete],
    ['label' => '5. Set up Salary Components', 'completed' => $salaryComplete],
    ['label' => '6. Add Employees', 'completed' => $employeesComplete],
    ['label' => '7. Configure Prior Payroll', 'completed' => $priorPayrollComplete],
    ['label' => '8. Connect with Zoho Books', 'completed' => $zohoBooksComplete],
];
$completedSetupSteps = count(array_filter($setupSteps, static function (array $step): bool {
    return !empty($step['completed']);
}));
$setupStepCount = count($setupSteps);
$setupCompletionPercent = $setupStepCount > 0 ? (int) round(($completedSetupSteps / $setupStepCount) * 100) : 0;
$allSetupComplete = $setupStepCount > 0 && $completedSetupSteps === $setupStepCount;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $allSetupComplete) {
    header('Location: getting_started.php');
    exit();
}
?>
<!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 Templates | 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>
    .profile-main{gap:14px;}
    .profile-head{align-items:flex-start;gap:16px;}
    .profile-head h1{font-size:24px;}
    .profile-head p{margin:6px 0 0;color:#64748b;line-height:1.6;max-width:900px;}
    .template-intro{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;padding:18px 20px;border:1px solid #dbe6ff;border-radius:16px;background:linear-gradient(135deg,#f7fbff 0%,#eef5ff 100%);}
    .template-intro-copy{display:flex;gap:14px;align-items:flex-start;}
    .template-intro-icon{width:48px;height:48px;border-radius:14px;background:#dbeafe;color:#2563eb;display:flex;align-items:center;justify-content:center;font-size:20px;flex:0 0 auto;}
    .template-intro h2{margin:0 0 6px;font-size:18px;}
    .template-intro p{margin:0;color:#5b6474;line-height:1.6;}
    .template-badge{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:#fff;border:1px solid #dbe6ff;font-size:13px;font-weight:700;color:#2563eb;white-space:nowrap;}
    .template-grid{display:grid;grid-template-columns:280px minmax(0,1fr);gap:16px;}
    .template-nav,.template-panel{background:#fff;border:1px solid var(--border);border-radius:14px;box-shadow:var(--shadow);}
    .template-nav{padding:18px;}
    .template-nav h3{margin:0 0 14px;font-size:16px;}
    .template-nav-group{margin-top:18px;}
    .template-nav-label{font-size:11px;font-weight:800;letter-spacing:.4px;text-transform:uppercase;color:#94a3b8;margin-bottom:10px;}
    .template-link{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;border-radius:10px;color:#334155;text-decoration:none;font-weight:600;}
    .template-link:hover{background:#f8fafc;}
    .template-link.active{background:#eff6ff;color:#2563eb;}
    .template-link small{font-weight:700;color:#94a3b8;}
    .template-panel{padding:22px;}
    .panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:18px;}
    .panel-head h2{margin:0;font-size:22px;}
    .panel-head p{margin:6px 0 0;color:#6b7280;line-height:1.6;}
    .panel-chip{padding:8px 12px;border-radius:999px;background:#f8fafc;border:1px solid #e5e7eb;font-size:12px;font-weight:700;color:#475569;}
    .benefits-card{margin-top:16px;border:1px solid #e5e7eb;border-radius:16px;padding:22px;background:#fbfdff;}
    .benefits-card h3{margin:0 0 8px;font-size:16px;color:#111827;}
    .benefits-card p{margin:0;color:#64748b;}
    .template-shell{display:grid;grid-template-columns:minmax(260px,320px) minmax(0,1fr);gap:16px;align-items:start;}
    .template-rail,.template-panel,.setup-summary,.preview-card{background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow);}
    .template-rail{padding:18px;position:sticky;top:82px;align-self:start;}
    .template-rail h3{margin:0;font-size:16px;}
    .template-rail p{margin:8px 0 0;color:#64748b;line-height:1.55;font-size:13px;}
    .rail-badge{display:inline-flex;align-items:center;gap:8px;padding:7px 11px;border-radius:999px;background:#eff6ff;color:#2563eb;font-size:12px;font-weight:700;margin-top:14px;}
    .rail-list{display:grid;gap:10px;margin-top:16px;}
    .rail-stat{display:flex;justify-content:space-between;gap:14px;align-items:center;padding:12px 14px;border:1px solid #edf2f7;border-radius:12px;background:#f8fbff;}
    .rail-stat strong{font-size:13px;color:#1f2937;}
    .rail-stat span{font-size:12px;color:#64748b;text-align:right;}
    .rail-divider{height:1px;background:#edf2f7;margin:16px 0;}
    .checklist{display:grid;gap:10px;margin-top:14px;}
    .check-item{display:grid;grid-template-columns:20px minmax(0,1fr);gap:10px;align-items:flex-start;padding:10px 0;border-bottom:1px solid #f1f5f9;}
    .check-item:last-child{border-bottom:none;padding-bottom:0;}
    .check-dot{width:20px;height:20px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;background:#e2e8f0;color:#94a3b8;font-size:11px;flex:0 0 auto;margin-top:1px;}
    .check-item.done .check-dot{background:#22c55e;color:#fff;}
    .check-copy{font-size:13px;color:#334155;line-height:1.45;}
    .check-copy small{display:block;margin-top:3px;color:#64748b;font-size:12px;}
    .template-panel{padding:20px;}
    .template-panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:18px;}
    .template-panel-head h2{margin:0;font-size:20px;}
    .template-panel-head p{margin:6px 0 0;color:#64748b;line-height:1.55;}
    .status-chip{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:#f8fafc;border:1px solid #e2e8f0;color:#475569;font-size:12px;font-weight:700;white-space:nowrap;}
    .status-chip.ready{background:#ecfdf5;border-color:#bbf7d0;color:#047857;}
    .setup-summary{padding:16px 18px;margin-bottom:16px;background:linear-gradient(135deg,#eff6ff 0%,#ffffff 100%);}
    .setup-summary-top{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;}
    .setup-summary h3{margin:0;font-size:17px;color:#1d4ed8;}
    .setup-summary p{margin:6px 0 0;color:#64748b;line-height:1.55;}
    .setup-count{font-size:13px;font-weight:700;color:#1d4ed8;white-space:nowrap;}
    .progress-bar{margin-top:12px;height:8px;border-radius:999px;background:#dbeafe;overflow:hidden;}
    .progress-bar > span{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,#3b82f6 0%,#2563eb 100%);}
    .summary-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-top:16px;}
    .summary-tile{padding:14px;border:1px solid #edf2f7;border-radius:14px;background:#fff;}
    .summary-tile small{display:block;font-size:12px;color:#64748b;text-transform:uppercase;letter-spacing:.3px;font-weight:700;}
    .summary-tile strong{display:block;margin-top:6px;font-size:18px;color:#111827;}
    .summary-tile span{display:block;margin-top:5px;color:#64748b;font-size:12px;}
    .alert-ok,.alert-err{margin:0 0 16px;padding:13px 15px;border-radius:12px;font-size:14px;font-weight:600;}
    .alert-ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857;}
    .alert-err{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;}
    .salary-card{border:1px solid #e5e7eb;border-radius:16px;overflow:hidden;background:#fff;padding:24px;}
    .salary-card > h3{margin:0;font-size:16px;}
    .salary-card-head{padding:20px 22px;border-bottom:1px solid #edf2f7;background:linear-gradient(180deg,#ffffff 0%,#fbfdff 100%);}
    .salary-card-head h3{margin:0;font-size:16px;}
    .salary-card-sub{margin:6px 0 0;color:#64748b;line-height:1.6;}
    .salary-form-body{padding:20px 22px 22px;}
    .salary-ctc-row{display:flex;align-items:center;gap:18px;margin-bottom:18px;}
    .salary-label{font-weight:700;color:#334155;min-width:120px;}
    .salary-ctc-input{display:flex;align-items:center;gap:0;max-width:360px;width:100%;}
    .salary-ctc-input .currency,.salary-ctc-input .per-year{height:40px;display:flex;align-items:center;padding:0 14px;border:1px solid #d7deea;background:#fff;color:#64748b;}
    .salary-ctc-input .currency{border-right:none;border-radius:10px 0 0 10px;}
    .salary-ctc-input input{border-radius:0;border-left:none;border-right:none;box-shadow:none;}
    .salary-ctc-input .per-year{border-left:none;border-radius:0 10px 10px 0;white-space:nowrap;}
    .salary-table{border:1px solid #e6edf7;border-radius:14px;overflow:hidden;background:#fff;}
    .salary-head,.salary-row{display:grid;grid-template-columns:2fr 1.6fr 1.2fr 1.2fr;gap:12px;align-items:center;padding:14px 16px;}
    .salary-head{background:#f8fbff;color:#64748b;font-size:12px;font-weight:800;letter-spacing:.35px;text-transform:uppercase;}
    .salary-row{border-top:1px solid #edf2f7;}
    .salary-section{padding:14px 16px 8px;font-size:14px;font-weight:800;color:#1f2937;border-top:1px solid #edf2f7;background:#fff;}
    .salary-row.hidden{display:none;}
    .salary-title{font-weight:700;color:#1f2937;}
    .salary-title-sub{display:block;margin-top:4px;font-size:12px;color:#6b7280;font-weight:500;line-height:1.45;}
    .salary-calc{display:flex;align-items:center;gap:0;max-width:250px;}
    .salary-calc input{border-radius:10px 0 0 10px;border-right:none;}
    .salary-calc .calc-suffix{height:40px;display:flex;align-items:center;padding:0 14px;border:1px solid #d7deea;border-radius:0 10px 10px 0;background:#fff;color:#64748b;font-size:13px;white-space:nowrap;}
    .salary-input{width:100%;height:40px;border:1px solid #d7deea;border-radius:10px;padding:0 12px;font-size:14px;background:#fff;color:#1f2937;}
    .salary-input[readonly]{background:#f9fbff;color:#334155;}
    .salary-amount-action{display:flex;align-items:center;gap:10px;}
    .salary-remove{border:none;background:transparent;color:#f87171;font-size:26px;line-height:1;cursor:pointer;padding:0 2px;}
    .salary-actions{position:relative;padding:14px 16px;border-top:1px solid #edf2f7;background:#fff;}
    .salary-add-btn{border:none;background:transparent;color:#2563eb;font-size:15px;font-weight:700;cursor:pointer;padding:0;}
    .salary-add-menu{position:absolute;left:16px;top:46px;min-width:250px;border:1px solid #dbe6ff;border-radius:12px;background:#fff;box-shadow:0 16px 36px rgba(15,23,42,.12);overflow:hidden;z-index:20;}
    .salary-add-menu button{display:block;width:100%;border:none;background:#fff;padding:12px 14px;text-align:left;font-weight:600;color:#334155;cursor:pointer;}
    .salary-add-menu button:hover{background:#eff6ff;color:#2563eb;}
    .total-row{background:#eef6ff;font-weight:800;}
    .total-row div{font-size:15px;}
    .template-actions{display:flex;align-items:center;gap:12px;margin-top:18px;}
    .primary-btn,.secondary-btn{display:inline-flex;align-items:center;justify-content:center;height:42px;padding:0 16px;border-radius:10px;font-weight:700;text-decoration:none;cursor:pointer;}
    .primary-btn{background:#2563eb;border:1px solid #2563eb;color:#fff;}
    .secondary-btn{background:#fff;border:1px solid #d7deea;color:#475569;}
    .preview-card{margin-top:16px;padding:18px 20px;background:linear-gradient(180deg,#ffffff 0%,#f8fbff 100%);}
    .preview-card h3{margin:0 0 6px;font-size:15px;}
    .preview-card p{margin:0;color:#64748b;line-height:1.6;font-size:13px;}
    .preview-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:14px;}
    .preview-tile{padding:14px;border:1px solid #edf2f7;border-radius:14px;background:#fff;}
    .preview-tile small{display:block;font-size:12px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;}
    .preview-tile strong{display:block;margin-top:6px;font-size:18px;color:#111827;}
    .preview-tile span{display:block;margin-top:5px;color:#64748b;font-size:12px;line-height:1.45;}
    @media (max-width: 1180px){
      .template-shell{grid-template-columns:1fr;}
      .template-rail{position:static;}
      .summary-grid,.preview-grid{grid-template-columns:repeat(2,minmax(0,1fr));}
    }
    @media (max-width: 760px){
      .profile-head,.template-panel-head,.salary-ctc-row,.template-actions,.setup-summary-top{flex-direction:column;align-items:flex-start;}
      .salary-head,.salary-row{grid-template-columns:1fr;}
      .salary-calc,.salary-ctc-input{max-width:none;}
      .summary-grid,.preview-grid{grid-template-columns:1fr;}
      .salary-add-menu{right:16px;left:auto;}
    }
  </style>
</head>
<body class="orgprofile-page salary-template-page">
  <?php settings_render_header($orgName, 'dashboard.php', 'fa-wallet'); ?>
  <main class="profile-layout">
    <?php settings_render_sidebar('salary_templates'); ?>
    <section class="profile-main">
      <div class="profile-head">
        <div>
          <h1>Salary Templates</h1>
          <p>Create a reusable salary breakup for onboarding. This keeps employee pay structures consistent and mirrors the polished settings flow from Zoho Payroll.</p>
        </div>
        <div class="org-id"><?php echo htmlspecialchars($orgName); ?></div>
      </div>

      <div class="setup-summary">
        <div class="setup-summary-top">
          <div>
            <h3>Get started with a reusable salary template</h3>
            <p>Complete the structure below to keep onboarding, salary calculations, and payslips aligned.</p>
          </div>
          <div class="setup-count"><?php echo (int) $completedSetupSteps; ?>/<?php echo (int) $setupStepCount; ?> Completed</div>
        </div>
        <div class="progress-bar" aria-hidden="true">
          <span style="width: <?php echo (int) $setupCompletionPercent; ?>%;"></span>
        </div>
        <div class="summary-grid">
          <div class="summary-tile">
            <small>Template</small>
            <strong><?php echo htmlspecialchars($templateName); ?></strong>
            <span>Default salary structure</span>
          </div>
          <div class="summary-tile">
            <small>Annual CTC</small>
            <strong>&#8377;<?php echo htmlspecialchars(number_format($annualCtcValue, 2)); ?></strong>
            <span>Basis for monthly breakup</span>
          </div>
          <div class="summary-tile">
            <small>Monthly CTC</small>
            <strong>&#8377;<?php echo htmlspecialchars(number_format($annualCtcValue / 12, 2)); ?></strong>
            <span>Auto calculated preview</span>
          </div>
          <div class="summary-tile">
            <small>Status</small>
            <strong><?php echo htmlspecialchars((string) ($template['status'] ?? 'Draft')); ?></strong>
            <span><?php echo $templateReady ? 'Ready for payroll use' : 'Add CTC to activate'; ?></span>
          </div>
        </div>
      </div>

      <div class="template-shell">
        <div class="template-intro">
          <div class="template-intro-copy">
            <div class="template-intro-icon"><i class="fa-regular fa-file-lines"></i></div>
            <div>
              <h2>Build reusable salary structures</h2>
              <p>Create salary templates with the same earning breakup your team uses during employee onboarding, then apply them consistently across employees.</p>
            </div>
          </div>
          <div class="template-badge"><i class="fa-solid fa-layer-group"></i> Standard Template</div>
        </div>

        <div class="template-grid">
          <aside class="template-nav">
            <h3>Templates</h3>
            <a class="template-link active" href="#">
              <span>Standard Salary Template</span>
              <small>Default</small>
            </a>
            <div class="template-nav-group">
              <div class="template-nav-label">Available Components</div>
              <a class="template-link" href="#"><span>Basic</span><small>50% of CTC</small></a>
              <a class="template-link" href="#"><span>Fixed Allowance</span><small>Auto balance</small></a>
              <a class="template-link" href="#"><span>House Rent Allowance</span><small>Optional</small></a>
              <a class="template-link" href="#"><span>Conveyance Allowance</span><small>Optional</small></a>
            </div>
          </aside>

          <div class="template-panel">
            <div class="panel-head">
              <div>
                <h2><?php echo htmlspecialchars($templateName); ?></h2>
                <p>Set how the employee's salary is divided for accurate pay calculation. This template mirrors the salary structure editor and can be reused for new employees.</p>
              </div>
              <div class="panel-chip">Template Status: <?php echo htmlspecialchars((string) ($template['status'] ?? 'Draft')); ?></div>
            </div>

            <form class="salary-card" method="post">
              <?php if ($saveMessage !== '') { ?>
                <div class="alert-ok"><?php echo htmlspecialchars($saveMessage); ?></div>
              <?php } ?>
              <?php if ($errorMessage !== '') { ?>
                <div class="alert-err"><?php echo htmlspecialchars($errorMessage); ?></div>
              <?php } ?>
              <input type="hidden" name="template_name" value="<?php echo htmlspecialchars($templateName); ?>">
              <h3>Salary Structure</h3>
              <div class="salary-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">&#8377;</span>
                  <input class="salary-input" type="number" name="annual_ctc" value="<?php echo htmlspecialchars($annualCtc); ?>" min="0" step="0.01" 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>

                <div class="salary-section">Earnings</div>

                <input type="hidden" name="hra_enabled" value="<?php echo $hraEnabled ? '1' : '0'; ?>" data-hra-enabled>
                <input type="hidden" name="conveyance_enabled" value="<?php echo $conveyanceEnabled ? '1' : '0'; ?>" data-conveyance-enabled>

                <div class="salary-row">
                  <div class="salary-title">Basic</div>
                  <div class="salary-calc">
                    <input class="salary-input" 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="salary-input" type="number" value="0.00" readonly data-basic-monthly></div>
                  <div><input class="salary-input" type="number" value="0.00" readonly data-basic-annual></div>
                </div>

                <div class="salary-row">
                  <div class="salary-title">
                    Fixed Allowance
                    <span class="salary-title-sub">Monthly CTC - Sum of all other components</span>
                  </div>
                  <div class="salary-calc">
                    <span class="calc-suffix">Fixed amount</span>
                  </div>
                  <div><input class="salary-input" type="number" value="0.00" readonly data-fixed-monthly></div>
                  <div><input class="salary-input" type="number" value="0.00" 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="salary-input" type="number" name="hra_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="salary-input" type="number" value="0.00" readonly data-hra-monthly></div>
                  <div class="salary-amount-action">
                    <input class="salary-input" type="number" value="0.00" readonly data-hra-annual>
                    <button class="salary-remove" type="button" data-remove-row="hra" aria-label="Remove House Rent Allowance">&times;</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="salary-input" type="number" name="conveyance_monthly" value="<?php echo htmlspecialchars($conveyanceMonthly); ?>" min="0" step="0.01" data-conveyance-monthly></div>
                  <div class="salary-amount-action">
                    <input class="salary-input" type="number" value="0.00" readonly data-conveyance-annual>
                    <button class="salary-remove" type="button" data-remove-row="conveyance" aria-label="Remove Conveyance Allowance">&times;</button>
                  </div>
                </div>

                <div class="salary-actions">
                  <button class="salary-add-btn" type="button" data-toggle-menu>+ Add Earning</button>
                  <div class="salary-add-menu" data-add-menu hidden>
                    <button type="button" data-add-row="hra">House Rent Allowance</button>
                    <button type="button" data-add-row="conveyance">Conveyance Allowance</button>
                  </div>
                </div>

                <div class="salary-row total-row">
                  <div class="salary-title">Cost to Company</div>
                  <div></div>
                  <div>&#8377;<span data-ctc-monthly>0.00</span></div>
                  <div>&#8377;<span data-ctc-annual>0.00</span></div>
                </div>
              </div>

              <div class="template-actions">
                <button class="primary-btn" type="submit">Save Template</button>
                <a class="secondary-btn" href="settings.php">Cancel</a>
              </div>
            </form>

            <div class="benefits-card">
              <h3>Other Benefits</h3>
              <p>Optional Add-ons to Employee Salary Structure</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script>
    (function () {
      const ctcInput = document.querySelector('[data-ctc]');
      const basicPercent = document.querySelector('[data-basic-percent]');
      const basicMonthly = document.querySelector('[data-basic-monthly]');
      const basicAnnual = document.querySelector('[data-basic-annual]');
      const fixedMonthly = document.querySelector('[data-fixed-monthly]');
      const fixedAnnual = document.querySelector('[data-fixed-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 ctcMonthly = document.querySelector('[data-ctc-monthly]');
      const ctcAnnual = document.querySelector('[data-ctc-annual]');
      const hraEnabled = document.querySelector('[data-hra-enabled]');
      const conveyanceEnabled = document.querySelector('[data-conveyance-enabled]');
      const addMenu = document.querySelector('[data-add-menu]');
      const toggleMenu = document.querySelector('[data-toggle-menu]');

      if (!ctcInput || !basicPercent) return;

      const toNum = (value) => {
        const number = parseFloat(value);
        return Number.isFinite(number) ? number : 0;
      };

      const fmt = (value) => (Math.round(value * 100) / 100).toFixed(2);

      const isVisible = (key) => {
        const row = document.querySelector(`[data-salary-row="${key}"]`);
        return !!row && !row.classList.contains('hidden');
      };

      const setVisible = (key, visible) => {
        const row = document.querySelector(`[data-salary-row="${key}"]`);
        if (!row) return;
        row.classList.toggle('hidden', !visible);

        if (key === 'hra' && hraEnabled) hraEnabled.value = visible ? '1' : '0';
        if (key === 'conveyance' && conveyanceEnabled) conveyanceEnabled.value = visible ? '1' : '0';

        if (!visible) {
          row.querySelectorAll('input').forEach((input) => {
            if (input.hasAttribute('data-hra-percent')) {
              input.value = '50.00';
            } else {
              input.value = '0.00';
            }
          });
        }
      };

      const syncMenu = () => {
        if (!addMenu) return;
        addMenu.querySelectorAll('[data-add-row]').forEach((button) => {
          button.hidden = isVisible(button.getAttribute('data-add-row'));
        });
      };

      const recalc = () => {
        const annualCtc = toNum(ctcInput.value);
        const basicPct = toNum(basicPercent.value);
        const basicYear = annualCtc * basicPct / 100;
        const basicMonth = basicYear / 12;
        const hraYear = isVisible('hra') ? (basicYear * toNum(hraPercent.value) / 100) : 0;
        const hraMonth = hraYear / 12;
        const conveyYear = isVisible('conveyance') ? (toNum(conveyanceMonthly.value) * 12) : 0;
        const fixedYear = annualCtc - basicYear - hraYear - conveyYear;
        const fixedMonth = fixedYear / 12;

        basicAnnual.value = fmt(basicYear);
        basicMonthly.value = fmt(basicMonth);
        hraAnnual.value = fmt(hraYear);
        hraMonthly.value = fmt(hraMonth);
        conveyanceAnnual.value = fmt(conveyYear);
        fixedAnnual.value = fmt(fixedYear);
        fixedMonthly.value = fmt(fixedMonth);
        ctcAnnual.textContent = fmt(annualCtc);
        ctcMonthly.textContent = fmt(annualCtc / 12);
        syncMenu();
      };

      ctcInput.addEventListener('input', recalc);
      basicPercent.addEventListener('input', recalc);
      hraPercent.addEventListener('input', recalc);
      conveyanceMonthly.addEventListener('input', recalc);

      document.querySelectorAll('[data-add-row]').forEach((button) => {
        button.addEventListener('click', function () {
          setVisible(button.getAttribute('data-add-row'), true);
          if (addMenu) addMenu.hidden = true;
          recalc();
        });
      });

      document.querySelectorAll('[data-remove-row]').forEach((button) => {
        button.addEventListener('click', function () {
          setVisible(button.getAttribute('data-remove-row'), false);
          recalc();
        });
      });

      if (toggleMenu && addMenu) {
        toggleMenu.addEventListener('click', function () {
          syncMenu();
          addMenu.hidden = !addMenu.hidden;
        });

        document.addEventListener('click', function (event) {
          if (!addMenu.contains(event.target) && !toggleMenu.contains(event.target)) {
            addMenu.hidden = true;
          }
        });
      }

      recalc();
    })();
  </script>
</body>
</html>

