<?php
/**
 * Mailer.php
 * -------------------------------------------------------------------
 * Thin wrapper around PHPMailer configured from the email_settings table
 * (so Mailtrap credentials can be changed from the UI, not hardcoded).
 *
 * REQUIRES PHPMailer. From your app root (the `public` folder that
 * contains dashboard.php, login.php, config.php, components/, and
 * hr_payroll/), run:
 *     composer require phpmailer/phpmailer
 * That creates vendor/autoload.php as a SIBLING of hr_payroll/, i.e.
 * .../public/vendor/autoload.php -- NOT inside hr_payroll itself.
 * -------------------------------------------------------------------
 */

// Try the expected location first, then a couple of common alternates,
// so a misplaced vendor/ folder gives you a clear list instead of a
// raw "failed to open stream" fatal error.
$autoloadCandidates = [
    __DIR__ . '/../../vendor/autoload.php',   // public/vendor/autoload.php (expected)
    __DIR__ . '/../vendor/autoload.php',      // hr_payroll/vendor/autoload.php
    __DIR__ . '/../../../vendor/autoload.php', // one level above public/
];

$autoloadFound = null;
foreach ($autoloadCandidates as $candidate) {
    if (file_exists($candidate)) {
        $autoloadFound = $candidate;
        break;
    }
}

if (!$autoloadFound) {
    $describe = function (string $path): string {
        return $path . ' (resolves to: ' . (realpath($path) ?: 'does not exist') . ')';
    };
    throw new Exception(
        "PHPMailer's vendor/autoload.php was not found. Tried:\n" . implode("\n", array_map($describe, $autoloadCandidates)) .
        "\n\nRun 'composer require phpmailer/phpmailer' from your public/ app root (the folder containing dashboard.php and hr_payroll/), " .
        "which should create public/vendor/autoload.php."
    );
}

require_once $autoloadFound;
require_once __DIR__ . '/helpers.php';

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

class Mailer
{
    private mysqli $conn;
    private array $settings;

    public function __construct(mysqli $conn)
    {
        $this->conn = $conn;
        $this->settings = $conn->query("SELECT * FROM email_settings WHERE is_active = 1 ORDER BY id DESC LIMIT 1")->fetch_assoc();
    }

    /**
     * @param string|null $toEmail
     * @param string|null $toName
     * @param string $subject
     * @param string $htmlBody
     * @return array ['success' => bool, 'error' => string|null]
     */
    public function send(?string $toEmail, ?string $toName, string $subject, string $htmlBody): array
    {
        if (empty($this->settings)) {
            return ['success' => false, 'error' => 'Email settings not configured.'];
        }
        if (empty($toEmail)) {
            return ['success' => false, 'error' => 'Employee has no email on file.'];
        }
        $toName = $toName ?? '';

        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $this->settings['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $this->settings['smtp_username'];
            $mail->Password = $this->settings['smtp_password'];
            $mail->SMTPSecure = $this->settings['encryption'] === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = (int) $this->settings['smtp_port'];

            $mail->CharSet = PHPMailer::CHARSET_UTF8;
            $mail->Encoding = 'base64';

            $mail->setFrom($this->settings['from_email'], $this->settings['from_name']);
            $mail->addAddress($toEmail, $toName);

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $htmlBody;
            $mail->AltBody = strip_tags($htmlBody);

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

    public static function payslipEmailTemplate(array $run): string
    {
        $name = h($run['name']);
        $cycle = h($run['cycle_name']);
        $net = number_format($run['net_pay'], 2);
        $gross = number_format($run['gross_earnings'], 2);
        $deductions = number_format($run['total_deductions'], 2);

        return "
        <div style='font-family: Arial, sans-serif; color:#1e293b; max-width:520px; margin:auto;'>
            <div style='background:#1e1b4b; padding:20px; border-radius:8px 8px 0 0;'>
                <h2 style='color:#fff; margin:0; font-size:16px;'>Payslip Notification</h2>
            </div>
            <div style='border:1px solid #e2e8f0; border-top:0; padding:24px; border-radius:0 0 8px 8px;'>
                <p>Hi $name,</p>
                <p>Your payslip for <strong>$cycle</strong> is ready. Here's a quick summary:</p>
                <table style='width:100%; border-collapse:collapse; margin:16px 0;'>
                    <tr><td style='padding:8px 0; border-bottom:1px solid #e2e8f0;'>Gross Earnings</td><td style='text-align:right; border-bottom:1px solid #e2e8f0;'>₦$gross</td></tr>
                    <tr><td style='padding:8px 0; border-bottom:1px solid #e2e8f0;'>Total Deductions</td><td style='text-align:right; border-bottom:1px solid #e2e8f0;'>₦$deductions</td></tr>
                    <tr><td style='padding:10px 0; font-weight:bold;'>Net Pay</td><td style='text-align:right; font-weight:bold; color:#047857;'>₦$net</td></tr>
                </table>
                <p style='font-size:13px; color:#64748b;'>Please log in to the HR portal to view and download your full payslip.</p>
            </div>
        </div>";
    }
}
