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

$orgCompanies = orgCompanyIds($db);
$rawCompany   = $_GET['company'] ?? post('company_id') ?? 0;
$companyId    = cleanInt($rawCompany) ?: ($orgCompanies[0] ?? 0);
if (!in_array($companyId, $orgCompanies)) { $companyId = $orgCompanies[0] ?? 0; }

$month = cleanInt($_GET['month'] ?? post('month') ?? date('n'));
$year  = cleanInt($_GET['year']  ?? post('year')  ?? date('Y'));

$results = null; // set after sending, holds the sent/failed summary

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send'])) {
    verifyCsrf();
    require_once __DIR__ . '/../../includes/mailer.php';

    $selectedIds = array_map('intval', $_POST['employee_ids'] ?? []);
    $sent = 0; $failed = [];

    foreach ($selectedIds as $empId) {
        // Re-verify this employee actually belongs to this org/company and
        // has a generated payslip for this month — never trust the
        // posted checkbox list alone.
        $emp = $db->fetchOne(
            "SELECT e.first_name, e.last_name, e.employee_id, e.pan_number,
                    e.official_email, e.personal_email,
                    d.name AS designation, dept.name AS department
               FROM employees e
          LEFT JOIN designations d ON d.id = e.designation_id
          LEFT JOIN departments dept ON dept.id = e.department_id
              WHERE e.id=? AND e.company_id=?",
            [$empId, $companyId]
        );
        if (!$emp) { $failed[] = "Employee #$empId — not found in this company"; continue; }

        $slip = $db->fetchOne(
            "SELECT pd.* FROM payroll_details pd
               JOIN payroll_runs pr ON pr.id = pd.payroll_run_id
              WHERE pd.employee_id=? AND pd.month=? AND pd.year=? AND pr.company_id=?",
            [$empId, $month, $year, $companyId]
        );
        if (!$slip) { $failed[] = "{$emp['first_name']} {$emp['last_name']} — payslip not generated for this month"; continue; }

        $toEmail = $emp['official_email'] ?: $emp['personal_email'];
        $bank = $db->fetchOne(
            "SELECT eba.account_number, 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]
        );
        $attendance = $db->fetchOne(
            "SELECT present_days, absent_days, leave_days, lop_days FROM muster_summary WHERE employee_id=? AND month=? AND year=?",
            [$empId, $month, $year]
        );
        $company = $db->fetchOne("SELECT company_name, address, logo_path FROM company_settings LIMIT 1");
        if ($company && !empty($company['logo_path'])) $company['logo_url'] = BASE_URL . '/uploads/' . $company['logo_path'];

        $monthsFull = ['','January','February','March','April','May','June','July','August','September','October','November','December'];
        $body = buildPayslipEmailHtml($slip, $emp, $bank, $company, $attendance, $month, $year);
        $result = sendAppEmail($toEmail, $emp['first_name'].' '.$emp['last_name'], "Payslip — {$monthsFull[$month]} $year", $body);

        try {
            $db->insertRow('payslip_email_log', [
                'employee_id' => $empId, 'month' => $month, 'year' => $year,
                'sent_to' => $toEmail ?: '(none)', 'status' => $result['ok'] ? 'sent' : 'failed',
                'error_message' => $result['ok'] ? null : $result['error'],
                'sent_by' => currentUser()['id'],
            ]);
        } catch (Throwable $e) { /* migration_smtp_settings.sql not run yet — logging is optional */ }

        if ($result['ok']) { $sent++; } else { $failed[] = "{$emp['first_name']} {$emp['last_name']} — {$result['error']}"; }
    }

    $results = ['sent' => $sent, 'failed' => $failed, 'total' => count($selectedIds)];
}

// Employees who have a generated payslip for the selected month/year —
// only these can actually be emailed.
$employees = $db->fetchAll(
    "SELECT e.id, e.first_name, e.last_name, e.employee_id,
            COALESCE(e.official_email, e.personal_email) AS email,
            pd.net_salary,
            (SELECT status FROM payslip_email_log pel WHERE pel.employee_id=e.id AND pel.month=? AND pel.year=? ORDER BY pel.id DESC LIMIT 1) AS last_send_status
       FROM employees e
       JOIN payroll_details pd ON pd.employee_id = e.id
       JOIN payroll_runs pr ON pr.id = pd.payroll_run_id AND pr.month=? AND pr.year=? AND pr.company_id=?
      WHERE e.company_id=? AND e.status='active'
      ORDER BY e.first_name",
    [$month, $year, $month, $year, $companyId, $companyId]
);

$smtpConfigured = false;
try { $smtpConfigured = (bool)$db->fetchOne("SELECT id FROM smtp_settings WHERE is_active=1 LIMIT 1"); } catch (Throwable $e) {}

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card">
  <div class="pc-card-title"><i class="ti ti-mail-forward me-2"></i>Send Payslip by Email</div>

  <?php if (!$smtpConfigured): ?>
    <div class="alert alert-warning">
      Email isn't set up yet. Go to <a href="<?= BASE_URL ?>/modules/company/email_settings.php">Companies → Email Settings</a> and save your SMTP details first.
    </div>
  <?php endif; ?>

  <?php if ($results): ?>
    <div class="alert alert-<?= $results['sent'] > 0 && !$results['failed'] ? 'success' : ($results['sent']>0 ? 'warning' : 'danger') ?>">
      <strong><?= $results['sent'] ?> of <?= $results['total'] ?></strong> payslip email(s) sent successfully.
      <?php if ($results['failed']): ?>
        <div class="mt-2 small">
          <strong>Not sent:</strong>
          <ul class="mb-0">
            <?php foreach ($results['failed'] as $f): ?><li><?= clean($f) ?></li><?php endforeach; ?>
          </ul>
        </div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <form method="GET" class="row g-2 align-items-end mb-3">
    <?php if (count($orgCompanies) > 1): ?>
    <div class="col-md-3"><label class="pc-label">Company</label>
      <select name="company" class="form-select form-select-sm" onchange="this.form.submit()">
        <?php foreach ($orgCompanies as $cid): $c = $db->fetchOne("SELECT name FROM companies WHERE id=?", [$cid]); ?>
        <option value="<?= $cid ?>" <?= $cid==$companyId?'selected':'' ?>><?= clean($c['name'] ?? "Company $cid") ?></option>
        <?php endforeach; ?>
      </select></div>
    <?php endif; ?>
    <div class="col-md-3"><label class="pc-label">Month</label>
      <select name="month" class="form-select form-select-sm" onchange="this.form.submit()">
        <?php foreach (['January','February','March','April','May','June','July','August','September','October','November','December'] as $i => $m): ?>
        <option value="<?= $i+1 ?>" <?= ($i+1)==$month?'selected':'' ?>><?= $m ?></option>
        <?php endforeach; ?>
      </select></div>
    <div class="col-md-3"><label class="pc-label">Year</label>
      <input type="number" name="year" class="form-control form-control-sm" value="<?= $year ?>" onchange="this.form.submit()"></div>
  </form>

  <?php if (!$employees): ?>
    <div class="text-muted small">No payslips generated for this month yet — run <a href="<?= BASE_URL ?>/modules/payroll/calculate.php?month=<?= $month ?>&year=<?= $year ?>&company=<?= $companyId ?>">Payroll → Calculate</a> first.</div>
  <?php else: ?>
    <form method="POST">
      <?= csrfField() ?>
      <input type="hidden" name="company_id" value="<?= $companyId ?>">
      <input type="hidden" name="month" value="<?= $month ?>">
      <input type="hidden" name="year" value="<?= $year ?>">

      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead><tr>
            <th style="width:36px;"><input type="checkbox" id="selectAll" onclick="document.querySelectorAll('.emp-chk').forEach(c=>c.checked=this.checked)"></th>
            <th>Employee</th><th>Email</th><th class="text-end">Net Pay</th><th>Last Sent</th>
          </tr></thead>
          <tbody>
            <?php foreach ($employees as $e): ?>
            <tr>
              <td><input type="checkbox" class="emp-chk" name="employee_ids[]" value="<?= $e['id'] ?>" <?= $e['email']?'':'disabled' ?>></td>
              <td><?= clean($e['first_name'].' '.$e['last_name']) ?> <span class="text-muted small">(<?= clean($e['employee_id']) ?>)</span></td>
              <td class="small <?= $e['email']?'':'text-danger' ?>"><?= clean($e['email'] ?: 'No email on file') ?></td>
              <td class="text-end">₹<?= number_format($e['net_salary'], 2) ?></td>
              <td>
                <?php if ($e['last_send_status']==='sent'): ?><span class="badge bg-success">Sent</span>
                <?php elseif ($e['last_send_status']==='failed'): ?><span class="badge bg-danger">Failed</span>
                <?php else: ?><span class="text-muted small">—</span><?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <button type="submit" name="send" value="1" class="btn btn-pc" <?= $smtpConfigured?'':'disabled' ?>>
        <i class="ti ti-send me-1"></i>Send Payslip Email to Selected
      </button>
    </form>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
