<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db      = Database::getInstance();
$isEdit  = isset($_GET['id']) || isset($_POST['employee_db_id']);
$empDbId = cleanInt($_GET['id'] ?? $_POST['employee_db_id'] ?? 0);
$page    = $isEdit ? 'Edit Employee' : 'Add Employee';
$emp     = [];

if ($isEdit && $empDbId) {
    $emp = $db->fetchOne("SELECT * FROM employees WHERE id = ?", [$empDbId]);
    // FIX (07 Jul 2026): don't allow editing an employee that belongs to
    // a different organization just by changing ?id= in the URL.
    if ($emp && !in_array($emp['company_id'], orgCompanyIds($db))) { $emp = null; }
    if (!$emp) { setFlash('error','Employee not found'); header('Location: list.php'); exit; }
}

// Masters
// FIX: companies has no `is_active` column, and this must only offer
// companies that belong to the current user's own organization.
$companies    = $db->fetchAll("SELECT id,name FROM companies WHERE organization_id=? ORDER BY name", [organizationId()]);
$departments  = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");
$designations = $db->fetchAll("SELECT id,name FROM designations WHERE is_active=1 ORDER BY name");
$grades       = $db->fetchAll("SELECT id,name FROM grades WHERE is_active=1 ORDER BY name");
$categories   = $db->fetchAll("SELECT id,name FROM categories WHERE is_active=1 ORDER BY name");
$locations    = $db->fetchAll("SELECT id,name FROM locations WHERE is_active=1 ORDER BY name");
$branches     = $db->fetchAll("SELECT id,name FROM branches WHERE is_active=1 ORDER BY name");
$shifts       = $db->fetchAll("SELECT id,name FROM shifts WHERE is_active=1 ORDER BY name");
$musterTypes  = $db->fetchAll("SELECT id,name FROM muster_types WHERE is_active=1 ORDER BY name");
$offTemplates = $db->fetchAll("SELECT id,name FROM off_day_templates WHERE is_active=1 ORDER BY name");
// FIX: manager picker must only list this organization's own employees.
[$mgrClause, $mgrParams] = orgScopeClause($db, 'company_id');
$managers     = $db->fetchAll("SELECT id,employee_id,first_name,last_name FROM employees WHERE status='active' AND $mgrClause ORDER BY first_name", $mgrParams);

// POST handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $data = [
        'first_name'          => post('first_name'),
        'last_name'           => post('last_name'),
        'date_of_birth'       => post('date_of_birth') ?: null,
        'gender'              => post('gender'),
        'blood_group'         => post('blood_group'),
        'marital_status'      => post('marital_status'),
        'nationality'         => post('nationality') ?: 'Indian',
        'aadhaar_number'      => post('aadhaar_number'),
        'pan_number'          => strtoupper(post('pan_number')),
        'passport_number'     => post('passport_number'),
        'driving_licence'     => post('driving_licence'),
        'date_of_joining'     => post('date_of_joining'),
        'company_id'          => postInt('company_id') ?: ($companies[0]['id'] ?? 0),
        'department_id'       => postInt('department_id') ?: null,
        'designation_id'      => postInt('designation_id') ?: null,
        'grade_id'            => postInt('grade_id') ?: null,
        'category_id'         => postInt('category_id') ?: null,
        'location_id'         => postInt('location_id') ?: null,
        'branch_id'           => postInt('branch_id') ?: null,
        'shift_id'            => postInt('shift_id') ?: null,
        'muster_type_id'      => postInt('muster_type_id') ?: null,
        'off_day_template_id' => postInt('off_day_template_id') ?: null,
        'reporting_manager_id'=> postInt('reporting_manager_id') ?: null,
        'work_type'           => post('work_type') ?: 'full_time',
        'employment_type'     => post('employment_type') ?: 'permanent',
        'probation_months'    => postInt('probation_months'),
        'confirmation_date'   => post('confirmation_date') ?: null,
        'personal_email'      => post('personal_email'),
        'official_email'      => post('official_email'),
        'mobile'              => post('mobile'),
        'alternate_phone'     => post('alternate_phone'),
        'residential_address' => post('residential_address'),
        'residential_city'    => post('residential_city'),
        'residential_state'   => post('residential_state'),
        'residential_pincode' => post('residential_pincode'),
        'permanent_address'   => post('permanent_address'),
        'permanent_city'      => post('permanent_city'),
        'permanent_state'     => post('permanent_state'),
        'permanent_pincode'   => post('permanent_pincode'),
        'emergency_name'      => post('emergency_name'),
        'emergency_relation'  => post('emergency_relation'),
        'emergency_phone'     => post('emergency_phone'),
        'uan_number'          => post('uan_number'),
        'pf_number'           => post('pf_number'),
        'esi_number'          => post('esi_number'),
        'tax_regime'          => post('tax_regime') ?: 'new',
        'pf_applicable'       => isset($_POST['pf_applicable'])  ? 1 : 0,
        'esi_applicable'      => isset($_POST['esi_applicable']) ? 1 : 0,
        'pt_applicable'       => isset($_POST['pt_applicable'])  ? 1 : 0,
        'tds_applicable'      => isset($_POST['tds_applicable']) ? 1 : 0,
        'bonus_eligible'      => isset($_POST['bonus_eligible']) ? 1 : 0,
        'gratuity_eligible'   => isset($_POST['gratuity_eligible']) ? 1 : 0,
        'lta_eligible'        => isset($_POST['lta_eligible'])   ? 1 : 0,
        'status'              => post('status') ?: 'active',
    ];

    // FIX (09 Jul 2026): Employee ID can now be entered manually (falls
    // back to auto-generated if left blank), and is editable afterward.
    // employee_id is globally UNIQUE across the whole table (not just
    // within one org), so it's checked here with a friendly error instead
    // of letting a raw duplicate-key database error through.
    $manualEmpId = trim(post('employee_id'));
    if ($manualEmpId) {
        $dupCode = $db->fetchOne("SELECT id FROM employees WHERE employee_id=?" . ($isEdit ? " AND id != ?" : ""), $isEdit ? [$manualEmpId, $empDbId] : [$manualEmpId]);
        if ($dupCode) {
            setFlash('error', "Employee ID '$manualEmpId' is already in use by another employee — IDs must be unique across the whole system. Please choose a different one.");
            header('Location: create.php' . ($isEdit ? "?id=$empDbId" : '')); exit;
        }
        $data['employee_id'] = strtoupper($manualEmpId);
    }

    // FIX (07 Jul 2026): don't trust the submitted company_id blindly —
    // someone could tamper with the form and assign an employee to a
    // company belonging to a DIFFERENT organization entirely.
    if (!in_array($data['company_id'], orgCompanyIds($db))) {
        setFlash('error', 'Invalid company selected.');
        header('Location: create.php' . ($isEdit ? "?id=$empDbId" : '')); exit;
    }

    // NOTE (07 Jul 2026): removed a license-seat check that used to sit
    // here — it referenced columns that don't exist (companies.license_seats/
    // is_active) AND it was checking the wrong thing anyway. Creating an
    // employee HR record does not create an app login; the license (sold
    // per organization, across all its companies) is only consumed when
    // someone creates an ACTIVE user login for them in User Management,
    // and that's already enforced correctly there. An organization should
    // be free to keep more employee records than purchased app seats
    // (e.g. staff who don't need app access at all).

    // Photo upload
    if (!empty($_FILES['photo']['name'])) {
        $path = uploadFile($_FILES['photo'], 'photos', ALLOWED_IMAGE_TYPES);
        if ($path) $data['photo'] = $path;
    }

    $db->beginTransaction();
    try {
        if ($isEdit) {
            $db->updateRow('employees', $data, $empDbId);
            $newId = $empDbId;
            auditLog('UPDATE','employees',$newId,[],$data);
        } else {
            // FIX: only auto-generate if the form didn't already set one above.
            if (empty($data['employee_id'])) {
                $data['employee_id'] = employeeCode();
            }
            $newId = $db->insertRow('employees', $data);
            auditLog('INSERT','employees',$newId,[],$data);
        }

        // Salary info
        $gross = cleanFloat($_POST['gross_monthly'] ?? 0);
        $ctc   = cleanFloat($_POST['ctc_annual']   ?? 0);
        if ($gross > 0) {
            $existing = $db->fetchValue("SELECT id FROM employee_salary WHERE employee_id=?", [$newId]);
            if ($existing) {
                $db->execute("UPDATE employee_salary SET gross_monthly=?,ctc_annual=?,effective_date=? WHERE employee_id=?",
                    [$gross, $ctc, date('Y-m-d'), $newId]);
            } else {
                $db->insertRow('employee_salary', [
                    'employee_id'   => $newId,
                    'gross_monthly' => $gross,
                    'ctc_annual'    => $ctc,
                    'effective_date'=> date('Y-m-d'),
                ]);
            }
        }

        // Bank account
        $accNo = post('account_number');
        if ($accNo) {
            $db->execute("DELETE FROM employee_bank_accounts WHERE employee_id=?", [$newId]);
            $db->insertRow('employee_bank_accounts', [
                'employee_id'         => $newId,
                'bank_id'             => postInt('bank_id') ?: null,
                'account_holder_name' => post('account_holder_name'),
                'account_number'      => $accNo,
                'ifsc_code'           => strtoupper(post('ifsc_code')),
                'branch_name'         => post('bank_branch'),
                'account_type'        => post('account_type') ?: 'savings',
                'upi_id'              => post('upi_id'),
                'payment_mode'        => post('payment_mode') ?: 'bank_transfer',
                'is_primary'          => 1,
            ]);
        }

        $db->commit();
        setFlash('success', $isEdit ? 'Employee updated successfully.' : 'Employee added successfully.');
        header('Location: view.php?id=' . $newId); exit;
    } catch (Exception $e) {
        $db->rollback();
        setFlash('error', 'Error: ' . $e->getMessage());
    }
}

$banks = $db->fetchAll("SELECT id,name FROM banks WHERE is_active=1 ORDER BY name");
$bank  = $empDbId ? $db->fetchOne("SELECT * FROM employee_bank_accounts WHERE employee_id=?",[$empDbId]) : null;
$sal   = $empDbId ? $db->fetchOne("SELECT * FROM employee_salary WHERE employee_id=?",[$empDbId]) : null;

$headerActions = '<button form="empForm" type="submit" class="btn btn-pc btn-sm"><i class="ti ti-check me-1"></i>'.($isEdit?'Update':'Save').' Employee</button>
<a href="list.php" class="btn btn-sm btn-outline-secondary">Cancel</a>';
include __DIR__ . '/../../includes/header.php';

function sel(array $options, string $field, $current, string $valKey='id', string $lblKey='name'): string {
    $out = '';
    foreach ($options as $o) {
        $sel = ($o[$valKey] == $current) ? 'selected' : '';
        $out .= "<option value='{$o[$valKey]}' $sel>".htmlspecialchars($o[$lblKey])."</option>";
    }
    return $out;
}
?>

<form method="POST" enctype="multipart/form-data" id="empForm">
<?= csrfField() ?>
<?php if ($isEdit): ?><input type="hidden" name="employee_db_id" value="<?= $empDbId ?>"><?php endif; ?>

<!-- Tabs -->
<ul class="nav nav-tabs mb-0" id="empTabs" role="tablist">
  <?php $tabs = ['Personal','Professional','Contact','Salary','Bank Account','Compliance','General'];
  foreach ($tabs as $i => $t): ?>
  <li class="nav-item">
    <button class="nav-link <?= $i===0?'active':'' ?>" data-bs-toggle="tab" data-bs-target="#tab<?= $i ?>" type="button"><?= $t ?></button>
  </li>
  <?php endforeach; ?>
</ul>
<div class="tab-content pc-card" style="border-top-left-radius:0">

  <!-- TAB 0: Personal -->
  <div class="tab-pane fade show active" id="tab0">
    <div class="pc-section-divider">Personal Information</div>
    <div class="row g-3">
      <div class="col-md-3"><label class="pc-label">Employee ID</label>
        <input name="employee_id" class="form-control form-control-sm" value="<?= clean($emp['employee_id']??'') ?>" placeholder="Leave blank to auto-generate">
        <div class="form-text">Must be unique across the whole system. Leave blank on a new employee to auto-generate.</div>
      </div>
      <div class="col-md-3"><label class="pc-label">First Name *</label>
        <input name="first_name" class="form-control form-control-sm" value="<?= clean($emp['first_name']??'') ?>" required></div>
      <div class="col-md-3"><label class="pc-label">Last Name *</label>
        <input name="last_name" class="form-control form-control-sm" value="<?= clean($emp['last_name']??'') ?>" required></div>
      <div class="col-md-3"><label class="pc-label">Date of Birth</label>
        <input type="date" name="date_of_birth" class="form-control form-control-sm" value="<?= $emp['date_of_birth']??'' ?>"></div>
      <div class="col-md-3"><label class="pc-label">Gender</label>
        <select name="gender" class="form-select form-select-sm">
          <option value="">Select</option>
          <?php foreach (['male','female','other'] as $g): ?>
          <option value="<?= $g ?>" <?= ($emp['gender']??'')===$g?'selected':'' ?>><?= ucfirst($g) ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Blood Group</label>
        <select name="blood_group" class="form-select form-select-sm">
          <option value="">Select</option>
          <?php foreach (['A+','A-','B+','B-','AB+','AB-','O+','O-'] as $bg): ?>
          <option value="<?= $bg ?>" <?= ($emp['blood_group']??'')===$bg?'selected':'' ?>><?= $bg ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Marital Status</label>
        <select name="marital_status" class="form-select form-select-sm">
          <option value="">Select</option>
          <?php foreach (['single','married','divorced','widowed'] as $ms): ?>
          <option value="<?= $ms ?>" <?= ($emp['marital_status']??'')===$ms?'selected':'' ?>><?= ucfirst($ms) ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Nationality</label>
        <input name="nationality" class="form-control form-control-sm" value="<?= clean($emp['nationality']??'Indian') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Aadhaar Number</label>
        <input name="aadhaar_number" class="form-control form-control-sm" maxlength="12" value="<?= clean($emp['aadhaar_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">PAN Number</label>
        <input name="pan_number" class="form-control form-control-sm" maxlength="10" style="text-transform:uppercase" value="<?= clean($emp['pan_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Passport Number</label>
        <input name="passport_number" class="form-control form-control-sm" value="<?= clean($emp['passport_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Driving Licence</label>
        <input name="driving_licence" class="form-control form-control-sm" value="<?= clean($emp['driving_licence']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Photo</label>
        <input type="file" name="photo" class="form-control form-control-sm" accept="image/*"></div>
    </div>
    <div class="pc-section-divider mt-3">Emergency Contact</div>
    <div class="row g-3">
      <div class="col-md-3"><label class="pc-label">Contact Name</label>
        <input name="emergency_name" class="form-control form-control-sm" value="<?= clean($emp['emergency_name']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Relationship</label>
        <input name="emergency_relation" class="form-control form-control-sm" value="<?= clean($emp['emergency_relation']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Phone</label>
        <input name="emergency_phone" class="form-control form-control-sm" value="<?= clean($emp['emergency_phone']??'') ?>"></div>
    </div>
  </div>

  <!-- TAB 1: Professional -->
  <div class="tab-pane fade" id="tab1">
    <div class="pc-section-divider">Professional Details</div>
    <div class="row g-3">
      <div class="col-md-3"><label class="pc-label">Date of Joining *</label>
        <input type="date" name="date_of_joining" class="form-control form-control-sm" value="<?= $emp['date_of_joining']??'' ?>" required></div>
      <div class="col-md-3"><label class="pc-label">Company *</label>
        <select name="company_id" class="form-select form-select-sm" required>
          <option value="">Select Company</option><?= sel($companies,'company_id',$emp['company_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Department</label>
        <select name="department_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($departments,'department_id',$emp['department_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Designation</label>
        <select name="designation_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($designations,'designation_id',$emp['designation_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Grade</label>
        <select name="grade_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($grades,'grade_id',$emp['grade_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Category</label>
        <select name="category_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($categories,'category_id',$emp['category_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Location</label>
        <select name="location_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($locations,'location_id',$emp['location_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Branch</label>
        <select name="branch_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($branches,'branch_id',$emp['branch_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Shift</label>
        <select name="shift_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($shifts,'shift_id',$emp['shift_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Muster Type</label>
        <select name="muster_type_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($musterTypes,'muster_type_id',$emp['muster_type_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Week Off Template</label>
        <select name="off_day_template_id" class="form-select form-select-sm">
          <option value="">Select</option><?= sel($offTemplates,'off_day_template_id',$emp['off_day_template_id']??0) ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Reporting Manager</label>
        <select name="reporting_manager_id" class="form-select form-select-sm">
          <option value="">Select</option>
          <?php foreach ($managers as $m): ?>
          <option value="<?= $m['id'] ?>" <?= ($emp['reporting_manager_id']??0)==$m['id']?'selected':'' ?>>
            <?= clean($m['first_name'].' '.$m['last_name'].' ('.$m['employee_id'].')') ?>
          </option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Work Type</label>
        <select name="work_type" class="form-select form-select-sm">
          <?php foreach (['full_time'=>'Full Time','part_time'=>'Part Time','contract'=>'Contract'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= ($emp['work_type']??'full_time')===$v?'selected':'' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Employment Type</label>
        <select name="employment_type" class="form-select form-select-sm">
          <?php foreach (['permanent'=>'Permanent','probation'=>'Probation','contract'=>'Contract','intern'=>'Intern'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= ($emp['employment_type']??'permanent')===$v?'selected':'' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="pc-label">Probation (Months)</label>
        <input type="number" name="probation_months" class="form-control form-control-sm" value="<?= $emp['probation_months']??6 ?>"></div>
      <div class="col-md-3"><label class="pc-label">Confirmation Date</label>
        <input type="date" name="confirmation_date" class="form-control form-control-sm" value="<?= $emp['confirmation_date']??'' ?>"></div>
      <div class="col-md-3"><label class="pc-label">Status</label>
        <select name="status" class="form-select form-select-sm">
          <?php foreach (['active','probation','inactive','on_leave','resigned','terminated'] as $s): ?>
          <option value="<?= $s ?>" <?= ($emp['status']??'active')===$s?'selected':'' ?>><?= ucfirst(str_replace('_',' ',$s)) ?></option>
          <?php endforeach; ?>
        </select></div>
    </div>
  </div>

  <!-- TAB 2: Contact -->
  <div class="tab-pane fade" id="tab2">
    <div class="pc-section-divider">Contact Details</div>
    <div class="row g-3">
      <?php $contactFields = [
        ['personal_email','Personal Email'],['official_email','Official Email'],
        ['mobile','Mobile *'],['alternate_phone','Alternate Phone'],
        ['residential_address','Residential Address'],['residential_city','City'],
        ['residential_state','State'],['residential_pincode','Pincode'],
        ['permanent_address','Permanent Address'],['permanent_city','City (Perm)'],
        ['permanent_state','State (Perm)'],['permanent_pincode','Pincode (Perm)'],
      ];
      foreach ($contactFields as [$name,$label]): ?>
      <div class="col-md-3"><label class="pc-label"><?= $label ?></label>
        <input name="<?= $name ?>" class="form-control form-control-sm" value="<?= clean($emp[$name]??'') ?>" <?= $name==='mobile'?'required':'' ?>></div>
      <?php endforeach; ?>
    </div>
    <div class="mt-2">
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="copyAddress()">
        <i class="ti ti-copy me-1"></i>Same as Residential
      </button>
    </div>
  </div>

  <!-- TAB 3: Salary -->
  <div class="tab-pane fade" id="tab3">
    <div class="pc-section-divider">Salary Information</div>
    <div class="row g-3">
      <div class="col-md-3"><label class="pc-label">CTC (Annual) ₹</label>
        <input type="number" name="ctc_annual" class="form-control form-control-sm" step="0.01" value="<?= $sal['ctc_annual']??0 ?>"></div>
      <div class="col-md-3"><label class="pc-label">Gross Monthly ₹</label>
        <input type="number" name="gross_monthly" class="form-control form-control-sm" step="0.01" value="<?= $sal['gross_monthly']??0 ?>" id="grossInput" oninput="autoCalcSalary()"></div>
    </div>
    <div class="pc-section-divider mt-3">Salary Breakdown (Auto-calculated)</div>
    <div class="row g-3" id="salaryBreakdown">
      <?php $heads = [['Basic','basic',40],['HRA','hra',20],['DA','da',0],['Conveyance','conv',0],['Medical','medical',0],['Special Allow.','special',0]];
      foreach ($heads as [$lbl,$code,$pct]): ?>
      <div class="col-md-2">
        <label class="pc-label"><?= $lbl ?></label>
        <input type="number" name="sal_<?= $code ?>" class="form-control form-control-sm sal-component" data-pct="<?= $pct ?>" step="0.01">
      </div>
      <?php endforeach; ?>
    </div>
    <div class="pc-section-divider mt-3">Tax Regime</div>
    <div class="row g-3">
      <div class="col-md-3"><label class="pc-label">Tax Regime</label>
        <select name="tax_regime" class="form-select form-select-sm">
          <option value="new" <?= ($emp['tax_regime']??'new')==='new'?'selected':'' ?>>New Regime</option>
          <option value="old" <?= ($emp['tax_regime']??'new')==='old'?'selected':'' ?>>Old Regime</option>
        </select></div>
      <div class="col-md-3"><label class="pc-label">UAN Number</label>
        <input name="uan_number" class="form-control form-control-sm" value="<?= clean($emp['uan_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">PF Number</label>
        <input name="pf_number" class="form-control form-control-sm" value="<?= clean($emp['pf_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">ESI Number</label>
        <input name="esi_number" class="form-control form-control-sm" value="<?= clean($emp['esi_number']??'') ?>"></div>
    </div>
  </div>

  <!-- TAB 4: Bank -->
  <div class="tab-pane fade" id="tab4">
    <div class="pc-section-divider">Bank Account Details</div>
    <div class="row g-3">
      <div class="col-md-4"><label class="pc-label">Bank Name</label>
        <select name="bank_id" class="form-select form-select-sm">
          <option value="">Select Bank</option><?= sel($banks,'bank_id',$bank['bank_id']??0) ?>
        </select></div>
      <div class="col-md-4"><label class="pc-label">Account Holder Name</label>
        <input name="account_holder_name" class="form-control form-control-sm" value="<?= clean($bank['account_holder_name']??'') ?>"></div>
      <div class="col-md-4"><label class="pc-label">Account Number</label>
        <input name="account_number" class="form-control form-control-sm" value="<?= clean($bank['account_number']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">IFSC Code</label>
        <input name="ifsc_code" class="form-control form-control-sm" style="text-transform:uppercase" value="<?= clean($bank['ifsc_code']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Branch Name</label>
        <input name="bank_branch" class="form-control form-control-sm" value="<?= clean($bank['branch_name']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Account Type</label>
        <select name="account_type" class="form-select form-select-sm">
          <option value="savings" <?= ($bank['account_type']??'savings')==='savings'?'selected':'' ?>>Savings</option>
          <option value="current" <?= ($bank['account_type']??'')==='current'?'selected':'' ?>>Current</option>
        </select></div>
      <div class="col-md-3"><label class="pc-label">UPI ID</label>
        <input name="upi_id" class="form-control form-control-sm" value="<?= clean($bank['upi_id']??'') ?>"></div>
      <div class="col-md-3"><label class="pc-label">Payment Mode</label>
        <select name="payment_mode" class="form-select form-select-sm">
          <?php foreach (['bank_transfer'=>'Bank Transfer','cash'=>'Cash','cheque'=>'Cheque','upi'=>'UPI'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= ($bank['payment_mode']??'bank_transfer')===$v?'selected':'' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select></div>
    </div>
  </div>

  <!-- TAB 5: Compliance -->
  <div class="tab-pane fade" id="tab5">
    <div class="pc-section-divider">Compliance Flags</div>
    <div class="row g-3">
      <?php $flags = ['pf_applicable'=>'PF Applicable','esi_applicable'=>'ESI Applicable','pt_applicable'=>'Professional Tax',
                      'tds_applicable'=>'TDS Applicable','bonus_eligible'=>'Bonus Eligible','gratuity_eligible'=>'Gratuity Eligible','lta_eligible'=>'LTA Eligible'];
      foreach ($flags as $fname=>$flabel): ?>
      <div class="col-md-3">
        <div class="form-check form-switch">
          <input class="form-check-input" type="checkbox" name="<?= $fname ?>" id="<?= $fname ?>" value="1" <?= ($emp[$fname]??1)?'checked':'' ?>>
          <label class="form-check-label fw-semibold" for="<?= $fname ?>"><?= $flabel ?></label>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- TAB 6: General -->
  <div class="tab-pane fade" id="tab6">
    <div class="pc-section-divider">General Settings</div>
    <p class="small text-muted">Shift, muster type, and week-off settings are configured in the Professional tab. Additional settings below.</p>
    <div class="row g-3">
      <div class="col-md-6">
        <div class="alert alert-info small">
          <i class="ti ti-info-circle me-1"></i>
          Leave balance will be automatically allocated based on the leave policy assigned to this employee after saving.
        </div>
      </div>
    </div>
  </div>

</div><!-- /tab-content -->
</form>

<?php $extraJs = "<script>
function autoCalcSalary() {
  const gross = parseFloat(document.getElementById('grossInput').value) || 0;
  document.querySelectorAll('.sal-component').forEach(el => {
    const pct = parseFloat(el.dataset.pct) || 0;
    if (pct > 0) el.value = (gross * pct / 100).toFixed(2);
  });
}
function copyAddress() {
  ['address','city','state','pincode'].forEach(f => {
    const src = document.querySelector('[name=residential_'+f+']');
    const dst = document.querySelector('[name=permanent_'+f+']');
    if (src && dst) dst.value = src.value;
  });
}
// Tab validation highlight
document.getElementById('empForm').addEventListener('submit', function(e) {
  const required = this.querySelectorAll('[required]');
  let valid = true;
  required.forEach(el => {
    if (!el.value.trim()) {
      el.classList.add('is-invalid');
      // Switch to that tab
      const tab = el.closest('.tab-pane');
      if (tab) document.querySelector('[data-bs-target=\"#'+tab.id+'\"]')?.click();
      valid = false;
    } else el.classList.remove('is-invalid');
  });
  if (!valid) e.preventDefault();
});
autoCalcSalary();
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>