<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();
$page = 'TDS Calculation';

$fy    = get('fy')  ?: FINANCIAL_YEAR;
$month = cleanInt($_GET['month'] ?? date('n'));
$year  = cleanInt($_GET['year']  ?? date('Y'));
$empId = cleanInt($_GET['emp']   ?? 0);

// ── TDS Engine ──────────────────────────────────────────────
function calculateTDS(int $empId, int $month, int $year, string $fy, Database $db): array {
    $emp    = $db->fetchOne("SELECT * FROM employees WHERE id=?", [$empId]);
    $regime = $emp['tax_regime'] ?? 'new';

    // Gross annual income (annualise current month salary)
    $salRow = $db->fetchOne("SELECT gross_monthly FROM employee_salary WHERE employee_id=?", [$empId]);
    $grossM = $salRow['gross_monthly'] ?? 0;
    $grossA = $grossM * 12;

    // Standard deduction
    $stdDed = 50000;

    // Investment declarations
    $declarations = $db->fetchAll(
        "SELECT td.section, SUM(id2.declared_amount) AS total, td.max_limit
           FROM investment_declarations id2
           JOIN tds_heads td ON td.id=id2.tds_head_id
          WHERE id2.employee_id=? AND id2.financial_year=? AND id2.status IN ('submitted','verified')
          GROUP BY td.section, td.max_limit",
        [$empId, $fy]
    );

    $totalInvDed = 0;
    $invDetails  = [];
    if ($regime === 'old') {
        foreach ($declarations as $d) {
            $claimed = min($d['total'], $d['max_limit'] > 0 ? $d['max_limit'] : PHP_INT_MAX);
            $totalInvDed += $claimed;
            $invDetails[] = ['section'=>$d['section'],'declared'=>$d['total'],'allowed'=>$claimed];
        }
    }

    // HRA exemption (old regime)
    $hraExempt = 0;
    if ($regime === 'old') {
        $basic  = $grossM * 0.40;
        $hraRec = $grossM * 0.20;
        $hraExempt = min($hraRec, $basic * 0.50);
        $hraExempt *= 12;
    }

    $taxableIncome = $grossA - $stdDed - $totalInvDed - $hraExempt;
    $taxableIncome = max(0, $taxableIncome);

    // Get tax slabs
    $slabs = $db->fetchAll(
        "SELECT * FROM tax_slabs WHERE financial_year=? AND regime=? AND is_active=1 ORDER BY income_from",
        [$fy, $regime]
    );

    $totalTax = 0;
    $slabCalc = [];
    foreach ($slabs as $slab) {
        if ($taxableIncome > $slab['income_from']) {
            $taxable  = min($taxableIncome, $slab['income_to']) - $slab['income_from'];
            $slabTax  = $taxable * $slab['tax_rate'] / 100;
            $totalTax += $slabTax;
            $slabCalc[] = [
                'range'   => money($slab['income_from']) . ' – ' . money($slab['income_to']),
                'rate'    => $slab['tax_rate'] . '%',
                'taxable' => $taxable,
                'tax'     => $slabTax,
            ];
        }
    }

    // Surcharge (income > 50L)
    $surcharge = 0;
    if ($taxableIncome > 5000000 && $taxableIncome <= 10000000) $surcharge = $totalTax * 0.10;
    elseif ($taxableIncome > 10000000)                          $surcharge = $totalTax * 0.15;

    // Health & Education Cess 4%
    $cess       = ($totalTax + $surcharge) * 0.04;
    $totalTax   = $totalTax + $surcharge + $cess;

    // Rebate u/s 87A (income <= 7L new regime, <= 5L old regime)
    $rebateLimit = $regime === 'new' ? 700000 : 500000;
    if ($taxableIncome <= $rebateLimit) $totalTax = 0;

    // TDS already deducted this FY
    $monthsElapsed    = $month <= 3 ? $month + 9 : $month - 3; // Apr=1 to Mar=12
    $tdsAlreadyDeducted = $db->fetchValue(
        "SELECT COALESCE(SUM(tds_this_month),0) FROM tds_calculations WHERE employee_id=? AND financial_year=? AND (year<?  OR (year=? AND month<?))",
        [$empId, $fy, $year, $year, $month]
    ) ?? 0;

    $remainingMonths = 12 - $monthsElapsed + 1;
    $remainingTax    = max(0, $totalTax - $tdsAlreadyDeducted);
    $tdsThisMonth    = $remainingMonths > 0 ? round($remainingTax / $remainingMonths, 2) : 0;

    return [
        'employee_id'        => $empId,
        'emp_name'           => $emp['first_name'] . ' ' . $emp['last_name'],
        'regime'             => $regime,
        'gross_annual'       => $grossA,
        'std_deduction'      => $stdDed,
        'investment_ded'     => $totalInvDed,
        'hra_exempt'         => $hraExempt,
        'taxable_income'     => $taxableIncome,
        'tax_liability'      => $totalTax,
        'tds_ytd'            => $tdsAlreadyDeducted,
        'tds_this_month'     => $tdsThisMonth,
        'slab_calc'          => $slabCalc,
        'inv_details'        => $invDetails,
        'surcharge'          => $surcharge,
        'cess'               => $cess,
    ];
}

// POST: Run TDS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && post('action') === 'calculate_tds') {
    verifyCsrf();
    $pMonth = postInt('month');
    $pYear  = postInt('year');
    $pFy    = post('fy') ?: FINANCIAL_YEAR;

    // FIX (07 Jul 2026): scope to current org — this used to run TDS
    // calculation across every organization's tds_applicable employees.
    [$bulkClause, $bulkParams] = orgScopeClause($db, 'company_id');
    $employees = $db->fetchAll("SELECT id FROM employees WHERE status='active' AND tds_applicable=1 AND $bulkClause", $bulkParams);
    $processed = 0;
    $db->beginTransaction();
    try {
        foreach ($employees as $e) {
            $tds = calculateTDS($e['id'], $pMonth, $pYear, $pFy, $db);
            $db->execute(
                "INSERT INTO tds_calculations
                   (employee_id,financial_year,month,year,gross_income,total_deductions,net_taxable_income,tax_liability,tds_this_month,tds_deducted_ytd)
                 VALUES (?,?,?,?,?,?,?,?,?,?)
                 ON DUPLICATE KEY UPDATE gross_income=VALUES(gross_income),total_deductions=VALUES(total_deductions),
                   net_taxable_income=VALUES(net_taxable_income),tax_liability=VALUES(tax_liability),
                   tds_this_month=VALUES(tds_this_month),tds_deducted_ytd=VALUES(tds_deducted_ytd)",
                [$e['id'],$pFy,$pMonth,$pYear,$tds['gross_annual'],
                 $tds['investment_ded']+$tds['std_deduction'],$tds['taxable_income'],
                 $tds['tax_liability'],$tds['tds_this_month'],$tds['tds_ytd']]
            );
            $processed++;
        }
        $db->commit();
        setFlash('success', "TDS calculated for $processed employees for " . monthName($pMonth) . " $pYear.");
        $month = $pMonth; $year = $pYear; $fy = $pFy;
    } catch (Exception $ex) {
        $db->rollback();
        setFlash('error', 'TDS calculation failed: ' . $ex->getMessage());
    }
}

// Fetch TDS data
// FIX: scope to current org.
[$tdsOrgClause, $tdsOrgParams] = orgScopeClause($db, 'e.company_id');
$tdsData = $db->fetchAll(
    "SELECT tc.*, e.employee_id AS emp_code, e.first_name, e.last_name, e.tax_regime,
            d.name AS dept
       FROM tds_calculations tc
       JOIN employees e ON e.id=tc.employee_id
  LEFT JOIN departments d ON d.id=e.department_id
      WHERE tc.financial_year=? AND tc.month=? AND tc.year=? AND $tdsOrgClause
      ORDER BY e.employee_id",
    array_merge([$fy, $month, $year], $tdsOrgParams)
);

[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,employee_id,first_name,last_name FROM employees WHERE status='active' AND tds_applicable=1 AND $empOrgClause ORDER BY first_name", $empOrgParams);

// Single employee detail
// FIX: confirm ?emp= belongs to current org before computing/showing it.
if ($empId && !in_array($empId, array_column($employees, 'id'))) { $empId = 0; }
$empDetail = null;
if ($empId) {
    $empDetail = calculateTDS($empId, $month, $year, $fy, $db);
}

$fyOptions = ['2026-27','2025-26','2024-25'];

$headerActions = '
<form method="POST" class="d-inline" onsubmit="return confirm(\'Calculate TDS for all employees?\')">
  '.csrfField().'
  <input type="hidden" name="action" value="calculate_tds">
  <input type="hidden" name="month" value="'.$month.'">
  <input type="hidden" name="year"  value="'.$year.'">
  <input type="hidden" name="fy"    value="'.$fy.'">
  <button class="btn btn-pc btn-sm"><i class="ti ti-calculator me-1"></i>Calculate TDS</button>
</form>
<a href="monthly_chart.php?fy='.$fy.'" class="btn btn-sm btn-outline-secondary ms-1">TDS Chart</a>
<a href="form16.php?fy='.$fy.'" class="btn btn-sm btn-outline-secondary ms-1">Form 16</a>';

include __DIR__ . '/../../includes/header.php';
?>

<!-- Filters -->
<div class="pc-card mb-3">
  <form method="GET" class="pc-filters">
    <div><label class="pc-label">Financial Year</label>
      <select name="fy" class="form-select form-select-sm">
        <?php foreach ($fyOptions as $f): ?>
        <option value="<?= $f ?>" <?= $fy===$f?'selected':'' ?>><?= $f ?></option>
        <?php endforeach; ?>
      </select></div>
    <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 ?>" <?= $m===$month?'selected':'' ?>><?= monthName($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=2024;$y<=2027;$y++): ?>
        <option value="<?= $y ?>" <?= $y===$year?'selected':'' ?>><?= $y ?></option>
        <?php endfor; ?>
      </select></div>
    <div><label class="pc-label">Employee (Detail)</label>
      <select name="emp" class="form-select form-select-sm">
        <option value="">All</option>
        <?php foreach ($employees as $e): ?>
        <option value="<?= $e['id'] ?>" <?= $empId==$e['id']?'selected':'' ?>><?= clean($e['first_name'].' '.$e['last_name']) ?></option>
        <?php endforeach; ?>
      </select></div>
    <div style="margin-top:auto"><button class="btn btn-pc btn-sm">Fetch</button></div>
  </form>
</div>

<!-- Employee TDS Detail -->
<?php if ($empDetail): ?>
<div class="row g-3 mb-3">
  <div class="col-md-6">
    <div class="pc-card">
      <div class="pc-card-title fw-bold"><?= clean($empDetail['emp_name']) ?> – TDS Detail (<?= monthName($month) ?> <?= $year ?>)</div>
      <table class="table table-sm table-bordered mb-0" style="font-size:12px">
        <tr><th>Gross Annual Income</th><td class="text-end"><?= money($empDetail['gross_annual']) ?></td></tr>
        <tr><th>Standard Deduction</th><td class="text-end text-danger">– <?= money($empDetail['std_deduction']) ?></td></tr>
        <tr><th>Investment Deductions</th><td class="text-end text-danger">– <?= money($empDetail['investment_ded']) ?></td></tr>
        <tr><th>HRA Exemption</th><td class="text-end text-danger">– <?= money($empDetail['hra_exempt']) ?></td></tr>
        <tr class="table-warning fw-bold"><th>Net Taxable Income</th><td class="text-end"><?= money($empDetail['taxable_income']) ?></td></tr>
        <tr><th>Surcharge</th><td class="text-end"><?= money($empDetail['surcharge']) ?></td></tr>
        <tr><th>Health & Edu Cess (4%)</th><td class="text-end"><?= money($empDetail['cess']) ?></td></tr>
        <tr class="table-primary fw-bold"><th>Total Tax Liability</th><td class="text-end"><?= money($empDetail['tax_liability']) ?></td></tr>
        <tr><th>TDS Deducted YTD</th><td class="text-end text-success"><?= money($empDetail['tds_ytd']) ?></td></tr>
        <tr class="table-success fw-bold"><th>TDS This Month</th><td class="text-end"><?= money($empDetail['tds_this_month']) ?></td></tr>
        <tr><th>Tax Regime</th><td class="text-end"><span class="badge bg-info"><?= strtoupper($empDetail['regime']) ?></span></td></tr>
      </table>
    </div>
  </div>
  <?php if ($empDetail['slab_calc']): ?>
  <div class="col-md-6">
    <div class="pc-card">
      <div class="pc-card-title">Slab-wise Calculation</div>
      <table class="table table-sm" style="font-size:12px">
        <thead><tr><th>Range</th><th>Rate</th><th>Taxable Amt</th><th>Tax</th></tr></thead>
        <tbody>
        <?php foreach ($empDetail['slab_calc'] as $s): ?>
        <tr><td><?= $s['range'] ?></td><td><?= $s['rate'] ?></td><td><?= money($s['taxable']) ?></td><td><?= money($s['tax']) ?></td></tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php if ($empDetail['inv_details']): ?>
    <div class="pc-card mt-3">
      <div class="pc-card-title">Investment Declarations (Old Regime)</div>
      <table class="table table-sm" style="font-size:12px">
        <thead><tr><th>Section</th><th>Declared</th><th>Allowed</th></tr></thead>
        <tbody>
        <?php foreach ($empDetail['inv_details'] as $d): ?>
        <tr><td><?= clean($d['section']) ?></td><td><?= money($d['declared']) ?></td><td><?= money($d['allowed']) ?></td></tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- All Employees TDS Table -->
<div class="pc-card">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div class="fw-semibold">TDS Summary – <?= monthName($month) ?> <?= $year ?> (FY <?= $fy ?>)</div>
    <?php if ($tdsData): ?>
    <a href="export_tds.php?month=<?= $month ?>&year=<?= $year ?>&fy=<?= $fy ?>" class="btn btn-sm btn-outline-secondary">
      <i class="ti ti-download me-1"></i>Export
    </a>
    <?php endif; ?>
  </div>
  <?php if ($tdsData): ?>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead>
        <tr><th>Employee</th><th>Dept</th><th>Regime</th><th>Gross Annual</th><th>Inv. Ded.</th><th>Taxable Income</th><th>Tax Liability</th><th>TDS YTD</th><th>TDS This Month</th></tr>
      </thead>
      <tbody>
      <?php
      $totals = array_fill_keys(['gross_income','total_deductions','net_taxable_income','tax_liability','tds_deducted_ytd','tds_this_month'], 0);
      foreach ($tdsData as $t):
        foreach ($totals as $k=>$_) $totals[$k] += $t[$k];
      ?>
      <tr>
        <td>
          <div class="fw-semibold"><?= clean($t['first_name'].' '.$t['last_name']) ?></div>
          <div style="font-size:10px;color:var(--pc-text2)"><?= clean($t['emp_code']) ?></div>
        </td>
        <td><?= clean($t['dept']??'') ?></td>
        <td><span class="badge bg-<?= $t['tax_regime']==='new'?'success':'info' ?>"><?= strtoupper($t['tax_regime']) ?></span></td>
        <td><?= money($t['gross_income']) ?></td>
        <td><?= money($t['total_deductions']) ?></td>
        <td><?= money($t['net_taxable_income']) ?></td>
        <td><?= money($t['tax_liability']) ?></td>
        <td><?= money($t['tds_deducted_ytd']) ?></td>
        <td class="fw-bold text-danger"><?= money($t['tds_this_month']) ?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr class="fw-bold" style="background:var(--pc-brand-light)">
          <td colspan="3">TOTAL</td>
          <td><?= money($totals['gross_income']) ?></td>
          <td><?= money($totals['total_deductions']) ?></td>
          <td><?= money($totals['net_taxable_income']) ?></td>
          <td><?= money($totals['tax_liability']) ?></td>
          <td><?= money($totals['tds_deducted_ytd']) ?></td>
          <td class="text-danger"><?= money($totals['tds_this_month']) ?></td>
        </tr>
      </tfoot>
    </table>
  </div>
  <?php else: ?>
  <div class="text-center py-5 text-muted">
    <i class="ti ti-file-invoice d-block fs-1 mb-2"></i>
    No TDS data found. Click <strong>Calculate TDS</strong> to process.
  </div>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>