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

[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');

// Template download
if (isset($_GET['template'])) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="salary_statutory_template.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['employee_id','gross_monthly','ctc_annual','effective_date','pan_number','uan_number','pf_number','esi_number']);
    fputcsv($out, ['EMP-0001','45000','540000','2026-04-01','ABCDE1234F','101234567890','PF/REG/001','ESI/001']);
    fputcsv($out, ['EMP-0002','60000','720000','2026-04-01','','','','']);
    fclose($out); exit;
}

$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['bulk_file'])) {
    verifyCsrf();
    $file = $_FILES['bulk_file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        setFlash('error', 'Upload failed. Please try again.');
        header('Location: bulk_upload.php'); exit;
    }
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['csv','txt'])) {
        setFlash('error', 'Only CSV files are supported. Download the template below and keep it in CSV format.');
        header('Location: bulk_upload.php'); exit;
    }

    // employee_id (code) -> internal id, scoped to this org only
    $empMap = [];
    foreach ($db->fetchAll("SELECT id, employee_id FROM employees WHERE $empOrgClause", $empOrgParams) as $e) {
        $empMap[$e['employee_id']] = $e['id'];
    }

    $handle    = fopen($file['tmp_name'], 'r');
    $header    = fgetcsv($handle);
    $processed = 0;
    $errors    = [];
    $rowNum    = 1;

    while (($row = fgetcsv($handle)) !== false) {
        $rowNum++;
        if (count(array_filter($row, fn($v) => trim((string)$v) !== '')) === 0) continue; // skip blank rows

        [$code, $gross, $ctc, $effDate, $pan, $uan, $pf, $esi] = array_pad($row, 8, '');
        $code = trim($code);

        if (!$code) { $errors[] = "Row $rowNum: employee_id is required."; continue; }
        if (!isset($empMap[$code])) { $errors[] = "Row $rowNum: employee '$code' not found in your organization."; continue; }
        $empId = $empMap[$code];

        try {
            if (trim($gross) !== '' || trim($ctc) !== '') {
                $db->execute(
                    "INSERT INTO employee_salary (employee_id, gross_monthly, ctc_annual, effective_date)
                     VALUES (?,?,?,?)
                     ON DUPLICATE KEY UPDATE gross_monthly=VALUES(gross_monthly), ctc_annual=VALUES(ctc_annual), effective_date=VALUES(effective_date)",
                    [$empId, $gross !== '' ? (float)$gross : 0, $ctc !== '' ? (float)$ctc : 0, $effDate ?: date('Y-m-d')]
                );
            }
            // Statutory fields: only overwrite when the cell isn't blank,
            // so a partially-filled CSV never wipes out existing values.
            $stat = [];
            if (trim($pan) !== '')  $stat['pan_number']  = trim($pan);
            if (trim($uan) !== '')  $stat['uan_number']  = trim($uan);
            if (trim($pf)  !== '')  $stat['pf_number']   = trim($pf);
            if (trim($esi) !== '')  $stat['esi_number']  = trim($esi);
            if ($stat) {
                $set = implode(',', array_map(fn($k) => "$k=?", array_keys($stat)));
                $db->execute("UPDATE employees SET $set WHERE id=?", array_merge(array_values($stat), [$empId]));
            }
            $processed++;
        } catch (Throwable $e) {
            $errors[] = "Row $rowNum: " . $e->getMessage();
        }
    }
    fclose($handle);

    $result = ['processed' => $processed, 'errors' => $errors];
    auditLog('BULK_UPLOAD', 'employee_salary', 0);
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-file-upload me-2"></i>Bulk Upload — Salary & Statutory</div>
      <p class="text-muted small mb-3">Upload gross salary, CTC, PAN, UAN, PF and ESI numbers for many employees at once via CSV. These feed Payroll, Statutory and Earnings &amp; Deductions reports.</p>

      <a href="?template=1" class="btn btn-outline-secondary btn-sm mb-3"><i class="ti ti-download me-1"></i>Download CSV Template</a>

      <form method="POST" enctype="multipart/form-data">
        <?= csrfField() ?>
        <div class="mb-3">
          <label class="pc-label">CSV File</label>
          <input type="file" name="bulk_file" accept=".csv,.txt" class="form-control form-control-sm" required>
        </div>
        <button class="btn btn-pc btn-sm"><i class="ti ti-upload me-1"></i>Upload &amp; Process</button>
      </form>

      <div class="alert alert-light border small mt-3 mb-0">
        <strong>Columns:</strong> employee_id, gross_monthly, ctc_annual, effective_date, pan_number, uan_number, pf_number, esi_number.<br>
        Leave a statutory column blank to keep the employee's existing value — it will not be cleared.
      </div>
    </div>
  </div>

  <div class="col-md-7">
    <?php if ($result): ?>
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-report me-2"></i>Upload Result</div>
      <p class="mb-2"><span class="badge bg-success"><?= $result['processed'] ?> row(s) processed</span>
        <?php if ($result['errors']): ?><span class="badge bg-danger"><?= count($result['errors']) ?> error(s)</span><?php endif; ?>
      </p>
      <?php if ($result['errors']): ?>
      <div style="max-height:300px;overflow-y:auto">
        <ul class="small text-danger mb-0">
          <?php foreach ($result['errors'] as $err): ?><li><?= clean($err) ?></li><?php endforeach; ?>
        </ul>
      </div>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-fingerprint me-2"></i>Other Bulk Uploads</div>
      <p class="text-muted small mb-3">These already have their own dedicated bulk upload screens:</p>
      <ul class="small mb-0">
        <li><a href="<?= BASE_URL ?>/modules/attendance/biometric_upload.php">Attendance / Biometric punches</a> — bulk upload daily in/out times.</li>
      </ul>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>