<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db  = Database::getInstance();
$id  = cleanInt($_GET['id'] ?? 0);
$emp = $id ? $db->fetchOne("SELECT e.*,
    d.name AS dept, des.name AS designation, g.name AS grade,
    l.name AS location, b.name AS branch, s.name AS shift,
    CONCAT(m.first_name,' ',m.last_name) AS manager
    FROM employees e
    LEFT JOIN departments d ON d.id=e.department_id
    LEFT JOIN designations des ON des.id=e.designation_id
    LEFT JOIN grades g ON g.id=e.grade_id
    LEFT JOIN locations l ON l.id=e.location_id
    LEFT JOIN branches b ON b.id=e.branch_id
    LEFT JOIN shifts s ON s.id=e.shift_id
    LEFT JOIN employees m ON m.id=e.reporting_manager_id
    WHERE e.id=?", [$id]) : null;
// FIX (07 Jul 2026): anyone logged in could view ANY employee by id,
// including ones belonging to a different organization, just by
// changing the ?id= in the URL. Now it's treated as not-found for
// anything outside the current org — same message either way, so this
// doesn't even reveal whether that id belongs to someone else.
if ($emp && !in_array($emp['company_id'], orgCompanyIds($db))) { $emp = null; }
if (!$emp) { setFlash('error','Employee not found.'); header('Location: list.php'); exit; }

$salary  = $db->fetchOne("SELECT * FROM employee_salary WHERE employee_id=?", [$id]);
$bank    = $db->fetchOne("SELECT eba.*,bk.name AS bank_name FROM employee_bank_accounts eba LEFT JOIN banks bk ON bk.id=eba.bank_id WHERE eba.employee_id=? AND eba.is_primary=1", [$id]);
$leaves  = $db->fetchAll("SELECT lb.*,lt.name AS leave_name,lt.code FROM employee_leave_balance lb JOIN leave_types lt ON lt.id=lb.leave_type_id WHERE lb.employee_id=? AND lb.year=YEAR(NOW())", [$id]);
$page    = clean($emp['first_name'].' '.$emp['last_name']);

$headerActions = '
<a href="edit.php?id='.$id.'" class="btn btn-pc btn-sm"><i class="ti ti-edit me-1"></i>Edit</a>
<a href="'.BASE_URL.'/modules/payroll/payslip.php?emp='.$id.'" class="btn btn-sm btn-outline-success"><i class="ti ti-receipt me-1"></i>Payslip</a>
<a href="export.php?id='.$id.'" class="btn btn-sm btn-outline-secondary"><i class="ti ti-download me-1"></i>Export</a>
<button onclick="confirmDelete('.$id.',\''.clean($emp['first_name'].' '.$emp['last_name']).'\')" class="btn btn-sm btn-outline-danger"><i class="ti ti-trash me-1"></i>Delete</button>
';
include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <!-- Left column: identity card -->
  <div class="col-md-3">
    <div class="pc-card text-center mb-3">
      <?php if (!empty($emp['photo'])): ?>
        <img src="<?=BASE_URL.'/uploads/'.$emp['photo']?>" class="rounded-circle mb-2" style="width:80px;height:80px;object-fit:cover">
      <?php else: ?>
        <div style="width:80px;height:80px;background:var(--pc-brand-light);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:800;color:var(--pc-brand);margin:0 auto 10px">
          <?=strtoupper(substr($emp['first_name'],0,1).substr($emp['last_name'],0,1))?>
        </div>
      <?php endif; ?>
      <h6 class="fw-bold mb-0"><?=clean($emp['first_name'].' '.$emp['last_name'])?></h6>
      <div class="text-muted small mb-2"><?=clean($emp['designation'] ?? '—')?></div>
      <span class="badge mb-2" style="background:var(--pc-brand-light);color:var(--pc-brand)"><?=clean($emp['employee_id'])?></span>
      <div><?=statusBadge($emp['status'])?></div>
    </div>
    <!-- Leave balance -->
    <div class="pc-card">
      <div class="pc-card-title">Leave Balance <?=date('Y')?></div>
      <?php foreach ($leaves as $lb):
        $avail = ($lb['allocated']??0) - ($lb['used']??0);
      ?>
      <div class="mb-2">
        <div class="d-flex justify-content-between small mb-1">
          <span><?=clean($lb['leave_name'])?></span>
          <span class="fw-bold"><?=$avail?>/<?=$lb['allocated']?></span>
        </div>
        <div class="pc-progress"><div class="pc-progress-fill" style="width:<?=$lb['allocated']>0?round(($avail/$lb['allocated'])*100):0?>%"></div></div>
      </div>
      <?php endforeach; ?>
      <?php if (!$leaves): ?><div class="text-muted small text-center">No balance data</div><?php endif; ?>
    </div>
  </div>

  <!-- Right column: details tabs -->
  <div class="col-md-9">
    <div class="pc-tabs mb-0" style="background:var(--pc-surface);border:1px solid var(--pc-border);border-bottom:none;border-radius:var(--r-md) var(--r-md) 0 0;padding:8px 12px 0">
      <?php foreach (['personal'=>'Personal','professional'=>'Professional','contact'=>'Contact','salary'=>'Salary','bank'=>'Bank','compliance'=>'Compliance'] as $tid=>$tlabel): ?>
      <div class="pc-tab <?=$tid==='personal'?'active':''?>" onclick="switchTab('<?=$tid?>')" id="tabt_<?=$tid?>"><?=$tlabel?></div>
      <?php endforeach; ?>
    </div>
    <div class="pc-card" style="border-radius:0 0 var(--r-md) var(--r-md)">

      <!-- Personal -->
      <div id="tab_personal">
        <?php $rows=[['Employee ID',$emp['employee_id']],['Full Name',$emp['first_name'].' '.$emp['last_name']],['Date of Birth',fmtDate($emp['date_of_birth'])],['Gender',ucfirst($emp['gender']??'—')],['Blood Group',$emp['blood_group']??'—'],['Marital Status',ucfirst($emp['marital_status']??'—')],['Nationality',$emp['nationality']??'—'],['Aadhaar',$emp['aadhaar_number']??'—'],['PAN',$emp['pan_number']??'—'],['Passport',$emp['passport_number']??'—']];?>
        <div class="row g-0">
          <?php foreach ($rows as [$k,$v]): ?>
          <div class="col-md-6">
            <div class="d-flex py-2 border-bottom px-1" style="font-size:12.5px">
              <span class="text-muted" style="width:140px;flex-shrink:0"><?=$k?></span>
              <span class="fw-semibold"><?=clean($v)?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <div class="pc-section-divider mt-3">Emergency Contact</div>
        <div class="row g-0">
          <?php foreach ([['Name',$emp['emergency_name']??'—'],['Relation',$emp['emergency_relation']??'—'],['Phone',$emp['emergency_phone']??'—']] as [$k,$v]): ?>
          <div class="col-md-4">
            <div class="d-flex py-2 border-bottom px-1" style="font-size:12.5px">
              <span class="text-muted" style="width:80px;flex-shrink:0"><?=$k?></span>
              <span class="fw-semibold"><?=clean($v)?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Professional -->
      <div id="tab_professional" style="display:none">
        <?php $rows=[['Date of Joining',fmtDate($emp['date_of_joining'])],['Department',$emp['dept']??'—'],['Designation',$emp['designation']??'—'],['Grade',$emp['grade']??'—'],['Location',$emp['location']??'—'],['Branch',$emp['branch']??'—'],['Shift',$emp['shift']??'—'],['Reporting Manager',$emp['manager']??'—'],['Employment Type',ucfirst($emp['employment_type']??'—')],['Work Type',ucwords(str_replace('_',' ',$emp['work_type']??'—'))],['Probation Period',($emp['probation_months']??0).' months'],['Confirmation Date',fmtDate($emp['confirmation_date'])],['Status',ucfirst(str_replace('_',' ',$emp['status']))]];?>
        <div class="row g-0">
          <?php foreach ($rows as [$k,$v]): ?>
          <div class="col-md-6">
            <div class="d-flex py-2 border-bottom px-1" style="font-size:12.5px">
              <span class="text-muted" style="width:160px;flex-shrink:0"><?=$k?></span>
              <span class="fw-semibold"><?=clean($v)?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Contact -->
      <div id="tab_contact" style="display:none">
        <?php $rows=[['Personal Email',$emp['personal_email']??'—'],['Official Email',$emp['official_email']??'—'],['Mobile',$emp['mobile']??'—'],['Alternate Phone',$emp['alternate_phone']??'—'],['Residential Address',$emp['residential_address']??'—'],['City (Res)',$emp['residential_city']??'—'],['State (Res)',$emp['residential_state']??'—'],['Pincode (Res)',$emp['residential_pincode']??'—'],['Permanent Address',$emp['permanent_address']??'—'],['City (Perm)',$emp['permanent_city']??'—'],['State (Perm)',$emp['permanent_state']??'—'],['Pincode (Perm)',$emp['permanent_pincode']??'—']];?>
        <div class="row g-0">
          <?php foreach ($rows as [$k,$v]): ?>
          <div class="col-md-6">
            <div class="d-flex py-2 border-bottom px-1" style="font-size:12.5px">
              <span class="text-muted" style="width:160px;flex-shrink:0"><?=$k?></span>
              <span class="fw-semibold"><?=clean($v)?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Salary -->
      <div id="tab_salary" style="display:none">
        <?php if ($salary): ?>
        <div class="row g-3 mb-3">
          <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon green" style="width:38px;height:38px;font-size:16px"><i class="ti ti-cash"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($salary['gross_monthly'],0)?></div><div class="pc-stat-label">Gross Monthly</div></div></div>
          <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon brand" style="width:38px;height:38px;font-size:16px"><i class="ti ti-wallet"></i></div><div class="pc-stat-val" style="font-size:18px">₹<?=number_format($salary['ctc_annual'],0)?></div><div class="pc-stat-label">Annual CTC</div></div></div>
          <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon amber" style="width:38px;height:38px;font-size:16px"><i class="ti ti-shield"></i></div><div class="pc-stat-val" style="font-size:14px"><?=ucfirst($emp['tax_regime']??'new')?></div><div class="pc-stat-label">Tax Regime</div></div></div>
          <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon blue" style="width:38px;height:38px;font-size:16px"><i class="ti ti-id-badge"></i></div><div class="pc-stat-val" style="font-size:14px"><?=clean($emp['uan_number']??'—')?></div><div class="pc-stat-label">UAN Number</div></div></div>
        </div>
        <?php foreach ([['Effective Date',fmtDate($salary['effective_date'])],['Basic',number_format($salary['basic']??0,2)],['HRA',number_format($salary['hra']??0,2)]] as [$k,$v]): ?>
        <div class="d-flex py-2 border-bottom" style="font-size:12.5px"><span class="text-muted" style="width:160px"><?=$k?></span><span class="fw-semibold">₹<?=$v?></span></div>
        <?php endforeach; ?>
        <?php else: ?><div class="alert alert-warning small">No salary record found.</div><?php endif; ?>
      </div>

      <!-- Bank -->
      <div id="tab_bank" style="display:none">
        <?php if ($bank): ?>
        <div class="border rounded p-3" style="background:var(--pc-brand-light)">
          <div class="fw-bold mb-2"><i class="ti ti-building-bank me-2"></i><?=clean($bank['bank_name']??'Bank')?></div>
          <?php foreach ([['Account Holder',$bank['account_holder_name']??'—'],['Account Number',$bank['account_number']],['IFSC Code',$bank['ifsc_code']??'—'],['Branch',$bank['branch_name']??'—'],['Account Type',ucfirst($bank['account_type'])],['Payment Mode',ucwords(str_replace('_',' ',$bank['payment_mode']??'—'))],['UPI ID',$bank['upi_id']??'—']] as [$k,$v]): ?>
          <div class="d-flex py-1" style="font-size:12.5px"><span class="text-muted" style="width:140px"><?=$k?></span><span class="fw-semibold"><?=clean($v)?></span></div>
          <?php endforeach; ?>
        </div>
        <?php else: ?><div class="alert alert-warning small">No bank account linked.</div><?php endif; ?>
      </div>

      <!-- Compliance -->
      <div id="tab_compliance" style="display:none">
        <?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'];?>
        <div class="row g-3">
          <?php foreach ($flags as $f=>$l): ?>
          <div class="col-md-3">
            <div class="d-flex align-items-center gap-2 p-2 rounded" style="background:<?=($emp[$f]??0)?'var(--pc-green-bg)':'var(--pc-red-bg)'?>">
              <i class="ti <?=($emp[$f]??0)?'ti-circle-check':'ti-circle-x'?>" style="color:<?=($emp[$f]??0)?'var(--pc-green)':'var(--pc-red)'?>;font-size:18px"></i>
              <span style="font-size:12.5px;font-weight:600"><?=$l?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header py-2"><h6 class="modal-title">Confirm Delete</h6></div>
      <div class="modal-body small" id="delMsg"></div>
      <div class="modal-footer py-2">
        <button class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <a href="#" id="delBtn" class="btn btn-sm btn-danger">Delete</a>
      </div>
    </div>
  </div>
</div>

<?php $extraJs = '<script>
function switchTab(id) {
  document.querySelectorAll("[id^=tab_]").forEach(el => el.style.display="none");
  document.querySelectorAll("[id^=tabt_]").forEach(el => el.classList.remove("active"));
  document.getElementById("tab_"+id).style.display="block";
  document.getElementById("tabt_"+id).classList.add("active");
}
function confirmDelete(id, name) {
  document.getElementById("delMsg").textContent = "Delete employee: " + name + "? This cannot be undone.";
  document.getElementById("delBtn").href = "delete.php?id="+id+"&csrf="+CSRF_TOKEN;
  new bootstrap.Modal(document.getElementById("deleteModal")).show();
}
</script>'; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>