<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

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


// Load .env manually
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue;

        [$key, $value] = array_pad(explode('=', $line, 2), 2, '');
        $value = trim($value, "\"'");
        $_ENV[trim($key)] = $value;
    }
}

function sendPasswordResetEmail($toEmail, $toName, $resetLink) {
    $mail = new PHPMailer(true);

    try {
        // SMTP Configuration (BREVO)
        $mail->isSMTP();
        $mail->Host       = $_ENV['BREVO_SMTP_HOST'] ?? 'smtp-relay.brevo.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['BREVO_SMTP_USER'] ?? '';
        $mail->Password   = $_ENV['BREVO_SMTP_PASS'] ?? '';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $_ENV['BREVO_SMTP_PORT'] ?? 587;

        // Sender details
        $mail->setFrom(
            $_ENV['BREVO_FROM_EMAIL'] ?? 'no-reply@digivortlimited.com',
            $_ENV['BREVO_FROM_NAME'] ?? 'Digital Vortex Technologies (ZM)'
        );

        // Recipient
        $mail->addAddress($toEmail, $toName);

        // Email content
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset Request';
        $mail->Body = "
            <h2>Password Reset</h2>
            <p>Hello <strong>{$toName}</strong>,</p>
            <p>You requested to reset your password for <strong>Custora CRM</strong>.</p>
            <p>Please click the link below to set a new password:</p>
            <p><a href=\"{$resetLink}\">{$resetLink}</a></p>
            <p>This link will expire in <strong>1 hour</strong>.</p>
            <br>
            <p>If you did not request this, please ignore this email.</p>
            <p>– <strong>Custora CRM</strong> by Digivort Limited</p>
        ";

        // Optional plain-text fallback
        $mail->AltBody = "Hello {$toName},\n\nTo reset your password, click the link below:\n{$resetLink}\n\nThis link expires in 1 hour.";

        // Send the email
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer Error: " . $mail->ErrorInfo);
        return false;
    }
}
