<?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 — Leave Balance';

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

// ── CSV template download ───────────────────────────────────
if (isset($_GET['template'])) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="leave_balance_template.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['employee_id','leave_type_code','year','allocated','carry_forward']);
    fputcsv($out, ['EMP-0001','CL', date('Y'), '12', '2']);
    fputcsv($out, ['EMP-0002','SL', date('Y'), '10', '0']);
    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_balance.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_balance.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'];
    }
    // leave_type_code -> internal id
    $ltMap = [];
    foreach ($db->fetchAll("SELECT id, code FROM leave_types WHERE is_active=1") as $lt) {
        $ltMap[strtoupper($lt['code'])] = $lt['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, $ltCode, $year, $alloc, $carry] = array_pad($row, 5, '');
        $code   = trim($code);
        $ltCode = strtoupper(trim($ltCode));
        $year   = trim($year) !== '' ? (int)$year : (int)date('Y');

        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; }
        if (!$ltCode) { $errors[] = "Row $rowNum: leave_type_code is required."; continue; }
        if (!isset($ltMap[$ltCode])) { $errors[] = "Row $rowNum: leave type '$ltCode' not found (check Configuration → Leave Types)."; continue; }
        if (trim($alloc) === '' || !is_numeric($alloc)) { $errors[] = "Row $rowNum: allocated must be a number."; continue; }

        $empId = $empMap[$code];
        $ltId  = $ltMap[$ltCode];

        try {
            // carry_forward only overwritten when the cell isn't blank, so a
            // partially-filled CSV never wipes out an existing carry-forward.
            if (trim((string)$carry) !== '' && is_numeric($carry)) {
                $db->execute(
                    "INSERT INTO employee_leave_balance (employee_id,leave_type_id,year,allocated,used,carry_forward)
                     VALUES (?,?,?,?,0,?)
                     ON DUPLICATE KEY UPDATE allocated=VALUES(allocated), carry_forward=VALUES(carry_forward)",
                    [$empId, $ltId, $year, (float)$alloc, (float)$carry]
                );
            } else {
                $db->execute(
                    "INSERT INTO employee_leave_balance (employee_id,leave_type_id,year,allocated,used,carry_forward)
                     VALUES (?,?,?,?,0,0)
                     ON DUPLICATE KEY UPDATE allocated=VALUES(allocated)",
                    [$empId, $ltId, $year, (float)$alloc]
                );
            }
            $processed++;
        } catch (Throwable $e) {
            $errors[] = "Row $rowNum: " . $e->getMessage();
        }
    }
    fclose($handle);

    $result = ['processed' => $processed, 'errors' => $errors];
    auditLog('BULK_UPLOAD', 'employee_leave_balance', 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 — Leave Balance</div>
      <p class="text-muted small mb-3">Upload leave allocation (and optional carry-forward) for many employees at once via CSV. This updates each employee's balance for Leave Management, approvals and the mobile app.</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, leave_type_code, year, allocated, carry_forward.<br>
        <code>leave_type_code</code> must match a code under Configuration → Leave Types (e.g. CL, SL, EL).<br>
        Leave <code>carry_forward</code> blank to keep the employee's existing value — it will not be cleared. <code>used</code> is never touched by this upload; it only changes when a leave application is approved.
      </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-beach me-2"></i>Related</div>
      <ul class="small mb-0">
        <li><a href="<?= BASE_URL ?>/modules/leave/index.php">Leave Management</a> — apply, approve/reject and allocate balance one employee at a time.</li>
        <li><a href="<?= BASE_URL ?>/modules/reports/monthly_summary.php?type=leave_report">Leave Report</a> — see applications with status, dates and approver.</li>
      </ul>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
