<?php
// ── Mailer ───────────────────────────────────────────────────
// Thin wrapper around PHPMailer (bundled in /lib/PHPMailer, no
// Composer needed) + the smtp_settings table (Companies → Email
// Settings). Used by Payroll → Send Payslip by Email, and can be
// reused anywhere else the app needs to send an email.

require_once __DIR__ . '/../lib/PHPMailer/Exception.php';
require_once __DIR__ . '/../lib/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/../lib/PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

// Returns ['ok'=>bool, 'error'=>string|null]
function sendAppEmail(string $toEmail, string $toName, string $subject, string $htmlBody): array {
    $db = Database::getInstance();
    $cfg = $db->fetchOne("SELECT * FROM smtp_settings WHERE is_active=1 ORDER BY id DESC LIMIT 1");
    if (!$cfg) {
        return ['ok' => false, 'error' => 'Email is not configured yet. Go to Companies → Email Settings first.'];
    }
    if (empty($toEmail) || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
        return ['ok' => false, 'error' => 'No valid email address on file for this employee.'];
    }

    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $cfg['host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $cfg['username'];
        $mail->Password   = $cfg['password'];
        $mail->Port       = (int)$cfg['port'];
        if ($cfg['encryption'] === 'tls') $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        elseif ($cfg['encryption'] === 'ssl') $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        else $mail->SMTPAutoTLS = false;

        $mail->setFrom($cfg['from_email'], $cfg['from_name']);
        $mail->addAddress($toEmail, $toName);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />', '</tr>', '</div>'], "\n", $htmlBody));

        $mail->send();
        return ['ok' => true, 'error' => null];
    } catch (PHPMailerException $e) {
        return ['ok' => false, 'error' => $mail->ErrorInfo ?: $e->getMessage()];
    } catch (Throwable $e) {
        return ['ok' => false, 'error' => $e->getMessage()];
    }
}

// Builds the same professional payslip layout used by
// modules/payroll/payslip.php and the mobile apps, as a self-contained
// HTML email body (inline styles only — email clients strip <style>
// blocks and external stylesheets).
function buildPayslipEmailHtml(array $slip, array $emp, ?array $bank, ?array $company, ?array $attendance, int $month, int $year): string {
    $months = ['','January','February','March','April','May','June','July','August','September','October','November','December'];
    $rupee  = fn($v) => '₹' . number_format((float)($v ?? 0), 2);
    $row    = fn($label, $val) => "<tr><td style='padding:5px 0;color:#555;'>$label</td><td style='padding:5px 0;text-align:right;font-weight:600;'>" . $rupee($val) . "</td></tr>";
    $info   = fn($label, $val) => "<tr><td style='padding:3px 0;color:#757575;width:40%;'>$label</td><td style='padding:3px 0;font-weight:600;'>" . htmlspecialchars($val ?: '—') . "</td></tr>";
    $stat   = fn($label, $val) => $val === null ? '' : "<td style='padding:8px 10px;background:#f5f6f8;border-radius:6px;text-align:center;'><div style='font-size:16px;font-weight:800;color:#0B2A5C;'>$val</div><div style='font-size:10px;color:#757575;'>$label</div></td><td width='8'></td>";

    $logoHtml = ($company['logo_url'] ?? null) ? "<img src='{$company['logo_url']}' style='height:32px;background:#fff;border-radius:6px;padding:3px;'><br>" : '';

    ob_start(); ?>
    <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;color:#212121;">
      <div style="background:#0B2A5C;color:#fff;padding:16px 20px;border-radius:8px 8px 0 0;">
        <?= $logoHtml ?>
        <div style="font-size:16px;font-weight:700;"><?= htmlspecialchars($company['company_name'] ?? 'Company') ?></div>
        <div style="font-size:11px;opacity:.8;"><?= htmlspecialchars($company['address'] ?? '') ?></div>
        <div style="margin-top:8px;font-size:12px;opacity:.9;">SALARY SLIP — <?= $months[$month] ?> <?= $year ?></div>
      </div>
      <div style="border:1px solid #e0e0e0;border-top:none;padding:18px 20px;border-radius:0 0 8px 8px;">
        <p>Hi <?= htmlspecialchars($emp['first_name']) ?>,</p>
        <p style="font-size:13px;color:#555;">Please find your payslip for <?= $months[$month] ?> <?= $year ?> below.</p>
        <table style="width:100%;border-collapse:collapse;margin:12px 0;">
          <tr>
            <td style="width:50%;vertical-align:top;"><table style="width:100%;">
              <?= $info('Employee ID', $emp['employee_id']) ?>
              <?= $info('Designation', $emp['designation'] ?? null) ?>
              <?= $info('Department', $emp['department'] ?? null) ?>
            </table></td>
            <td style="width:50%;vertical-align:top;"><table style="width:100%;">
              <?= $info('PAN', $emp['pan_number'] ?? null) ?>
              <?= $info('Bank', $bank['bank_name'] ?? null) ?>
              <?= $info('A/C No', $bank['account_number'] ?? null) ?>
            </table></td>
          </tr>
        </table>
        <?php if ($attendance): ?>
        <table style="margin-bottom:14px;"><tr>
          <?= $stat('Present', $attendance['present_days'] ?? null) ?>
          <?= $stat('Absent', $attendance['absent_days'] ?? null) ?>
          <?= $stat('LOP', $attendance['lop_days'] ?? null) ?>
          <?= $stat('Leave', $attendance['leave_days'] ?? null) ?>
        </tr></table>
        <?php endif; ?>
        <table style="width:100%;border-collapse:collapse;">
          <tr>
            <td style="width:50%;vertical-align:top;padding-right:10px;">
              <div style="font-weight:700;color:#0B2A5C;border-bottom:2px solid #0B2A5C;padding-bottom:4px;margin-bottom:4px;font-size:12px;text-transform:uppercase;">Earnings</div>
              <table style="width:100%;">
                <?= $row('Basic', $slip['basic']) ?><?= $row('HRA', $slip['hra']) ?><?= $row('DA', $slip['da']) ?>
                <?= $row('Conveyance', $slip['conveyance']) ?><?= $row('Medical', $slip['medical']) ?><?= $row('Special Allowance', $slip['special_allowance']) ?>
                <tr><td style="padding-top:8px;font-weight:700;border-top:1px solid #ccc;">Gross</td><td style="padding-top:8px;font-weight:700;text-align:right;border-top:1px solid #ccc;"><?= $rupee($slip['gross_salary']) ?></td></tr>
              </table>
            </td>
            <td style="width:50%;vertical-align:top;padding-left:10px;">
              <div style="font-weight:700;color:#0B2A5C;border-bottom:2px solid #0B2A5C;padding-bottom:4px;margin-bottom:4px;font-size:12px;text-transform:uppercase;">Deductions</div>
              <table style="width:100%;">
                <?= $row('PF', $slip['pf_employee']) ?><?= $row('ESI', $slip['esi_employee']) ?>
                <?= $row('Professional Tax', $slip['professional_tax']) ?><?= $row('Income Tax', $slip['income_tax']) ?>
                <tr><td style="padding-top:8px;font-weight:700;border-top:1px solid #ccc;">Total</td><td style="padding-top:8px;font-weight:700;text-align:right;border-top:1px solid #ccc;"><?= $rupee($slip['total_deductions']) ?></td></tr>
              </table>
            </td>
          </tr>
        </table>
        <div style="background:#E8F5E9;padding:12px;border-radius:8px;text-align:center;margin-top:14px;">
          <div style="font-size:12px;color:#555;">Net Pay</div>
          <div style="font-size:20px;font-weight:800;color:#2E7D32;"><?= $rupee($slip['net_salary']) ?></div>
        </div>
        <p style="text-align:center;color:#9e9e9e;font-size:11px;margin-top:14px;">This is a system-generated payslip and does not require a signature.</p>
      </div>
    </div>
    <?php
    return ob_get_clean();
}
