<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db  = Database::getInstance();

$user  = currentUser();
$empId = cleanInt($_GET['emp'] ?? 0);
$month = intval($_GET['month'] ?? date('n'));
$year  = intval($_GET['year']  ?? date('Y'));
$months = ['','January','February','March','April','May','June','July','August','September','October','November','December'];

// FIX (07 Jul 2026): this used to let ANY logged-in user view ANY
// employee's payslip (salary, PAN, UAN, bank account) via ?emp=<id> —
// no ownership check and no org check at all. Now: an 'employee' role
// can only ever see their own; anyone else is restricted to employees
// within their own organization.
if (hasRole('employee')) {
    $empId = $user['emp_id'];
} else {
    $orgCompanies = orgCompanyIds($db);
    $orgEmpIds = $orgCompanies ? array_column($db->fetchAll(
        "SELECT id FROM employees WHERE company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
        $orgCompanies
    ), 'id') : [];
    if ($empId && !in_array($empId, $orgEmpIds)) { $empId = 0; }
}

$emp = $empId ? $db->fetchOne("SELECT e.*,d.name AS dept,des.name AS designation,l.name AS location 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 locations l ON l.id=e.location_id WHERE e.id=?", [$empId]) : null;
if (!$emp) { setFlash('error','Employee not found.'); header('Location: '.BASE_URL.'/modules/employees/list.php'); exit; }

// FIX: scope the payroll run to the employee's own company (also
// guarantees it can't be a different org's run).
$run  = $db->fetchOne("SELECT * FROM payroll_runs WHERE month=? AND year=? AND company_id=?", [$month,$year,$emp['company_id']]);
$slip = $run ? $db->fetchOne("SELECT * FROM payroll_details WHERE payroll_run_id=? AND employee_id=?", [$run['id'],$empId]) : null;
$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", [$empId]);
$company = $db->fetchOne("SELECT * FROM company_settings LIMIT 1");

[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = hasRole('employee') ? [] : $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
$page = 'Payslip';
include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3 no-print">
  <form method="GET" class="d-flex gap-2 align-items-end flex-wrap">
    <input type="hidden" name="emp" value="<?=$empId?>">
    <div><label class="pc-label">Month</label>
      <select name="month" class="form-select form-select-sm"><?php for($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$month==$m?'selected':''?>><?=$months[$m]?></option><?php endfor; ?></select></div>
    <div><label class="pc-label">Year</label>
      <select name="year" class="form-select form-select-sm"><?php for($y=date('Y');$y>=date('Y')-3;$y--): ?><option value="<?=$y?>" <?=$year==$y?'selected':''?>><?=$y?></option><?php endfor; ?></select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>View</button>
    <?php if($slip): ?><button type="button" onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="ti ti-printer me-1"></i>Print</button><?php endif; ?>
  </form>
</div>

<?php if ($slip): ?>
<div id="payslipDoc">
  <div class="pc-payslip-header d-flex justify-content-between align-items-start">
    <div class="d-flex align-items-center gap-2">
      <?php if ($company['logo_path'] ?? ''): ?>
        <img src="<?= BASE_URL ?>/uploads/<?= clean($company['logo_path']) ?>" alt="<?= clean($company['company_name'] ?? '') ?>" style="max-height:48px;max-width:140px;object-fit:contain;background:#fff;border-radius:6px;padding:3px;">
      <?php endif; ?>
      <div>
        <h5 class="fw-bold mb-0"><?=clean($company['company_name'] ?? 'Company Name')?></h5>
        <div class="opacity-75 small"><?=clean($company['address'] ?? '')?></div>
      </div>
    </div>
    <div class="text-end opacity-90">
      <div class="fw-bold">SALARY SLIP</div>
      <div class="small"><?=$months[$month]?> <?=$year?></div>
    </div>
  </div>
  <div class="pc-payslip-body">
    <!-- Employee info -->
    <div class="row g-3 mb-3">
      <div class="col-md-6">
        <?php foreach([['Employee ID',$emp['employee_id']],['Name',$emp['first_name'].' '.$emp['last_name']],['Designation',$emp['designation']??'—'],['Department',$emp['dept']??'—']] as [$k,$v]): ?>
        <div class="pc-payslip-row"><span class="text-muted"><?=$k?></span><span class="fw-semibold"><?=clean($v)?></span></div>
        <?php endforeach; ?>
      </div>
      <div class="col-md-6">
        <?php foreach([['UAN',$emp['uan_number']??'—'],['PAN',$emp['pan_number']??'—'],['Bank',$bank['bank_name']??'—'],['A/C No',($bank['account_number']??'—')]] as [$k,$v]): ?>
        <div class="pc-payslip-row"><span class="text-muted"><?=$k?></span><span class="fw-semibold"><?=clean($v)?></span></div>
        <?php endforeach; ?>
      </div>
    </div>
    <!-- Attendance -->
    <div class="row g-2 mb-3">
      <div class="col-md-3"><div class="pc-stat py-2"><div class="pc-stat-val" style="font-size:18px"><?=$slip['present_days']??0?></div><div class="pc-stat-label">Present Days</div></div></div>
      <div class="col-md-3"><div class="pc-stat py-2"><div class="pc-stat-val" style="font-size:18px"><?=$slip['lop_days']??0?></div><div class="pc-stat-label">LOP Days</div></div></div>
    </div>
    <!-- Earnings vs Deductions -->
    <div class="row g-3">
      <div class="col-md-6">
        <div class="fw-bold mb-2 small" style="color:var(--pc-green)"><i class="ti ti-plus-circle me-1"></i>EARNINGS</div>
        <?php $earnings=[['Basic','basic'],['HRA','hra'],['DA','da'],['Conveyance','conveyance'],['Medical','medical'],['Special Allowance','special_allowance'],['LTA','lta'],['Bonus','bonus'],['Arrears','arrears'],['Other Earnings','other_earnings']];
        $totalEarn=0;
        foreach($earnings as [$lbl,$col]):
          $val=$slip[$col]??0;
          if($val<=0) continue;
          $totalEarn+=$val;
        ?>
        <div class="pc-payslip-row"><span><?=$lbl?></span><span>₹<?=number_format($val,2)?></span></div>
        <?php endforeach; ?>
        <div class="pc-payslip-total mt-2"><span>Gross Salary</span><span>₹<?=number_format($slip['gross_salary'],2)?></span></div>
      </div>
      <div class="col-md-6">
        <div class="fw-bold mb-2 small" style="color:var(--pc-red)"><i class="ti ti-minus-circle me-1"></i>DEDUCTIONS</div>
        <?php $deductions=[['PF (Employee)','pf_employee'],['ESI (Employee)','esi_employee'],['Professional Tax','professional_tax'],['Income Tax (TDS)','income_tax'],['Advance Recovery','advance_recovery'],['Other Deductions','other_deductions']];
        $totalDed=0;
        foreach($deductions as [$lbl,$col]):
          $val=$slip[$col]??0;
          if($val<=0) continue;
          $totalDed+=$val;
        ?>
        <div class="pc-payslip-row"><span><?=$lbl?></span><span>₹<?=number_format($val,2)?></span></div>
        <?php endforeach; ?>
        <div class="pc-payslip-total mt-2" style="background:var(--pc-red-bg);color:var(--pc-red)"><span>Total Deductions</span><span>₹<?=number_format($slip['total_deductions'],2)?></span></div>
      </div>
    </div>
    <!-- Net Pay -->
    <div class="pc-payslip-total mt-3" style="font-size:16px">
      <span>NET PAY</span>
      <span>₹<?=number_format($slip['net_salary'],2)?></span>
    </div>
    <div class="mt-3 text-muted small text-center">This is a system-generated payslip and does not require a signature.</div>
  </div>
</div>
<?php else: ?>
<div class="pc-card">
  <div class="text-muted text-center py-4">
    <i class="ti ti-receipt-off" style="font-size:36px;opacity:0.3"></i><br>
    No payslip found for <?=$months[$month]?> <?=$year?>. Process payroll first.
  </div>
</div>
<?php endif; ?>
<style>
@media print {
  .pc-topbar,.pc-sidebar,.no-print,.pc-page-header { display:none !important; }
  .pc-main-wrap { display:block !important; }
  .pc-content { overflow:visible !important; }
  #payslipDoc { box-shadow:none !important; }
}
</style>
<?php include __DIR__ . '/../../includes/footer.php'; ?>