<?php

declare(strict_types=1);

function sendCustomerOtpEmail(string $email, string $otpCode): array
{
    $autoload = __DIR__ . '/../vendor/autoload.php';
    if (!file_exists($autoload)) {
        return [
            "success" => false,
            "message" => "PHPMailer is not installed. Run composer install."
        ];
    }

    require_once $autoload;
    $config = require __DIR__ . '/../reservation/mail_config.php';

    if (empty($config["password"])) {
        return [
            "success" => false,
            "message" => "SMTP password is missing. Set PETITE_GMAIL_APP_PASSWORD."
        ];
    }

    try {
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $config["host"];
        $mail->SMTPAuth = true;
        $mail->Username = $config["username"];
        $mail->Password = $config["password"];
        $mail->Port = $config["port"];

        if ($config["secure"] === "ssl") {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        }

        $mail->setFrom($config["from_email"], $config["from_name"]);
        if (!$mail->addAddress($email)) {
            return ["success" => false, "message" => "Invalid recipient email address."];
        }

        $safeOtp = htmlspecialchars($otpCode, ENT_QUOTES, "UTF-8");
        $mail->isHTML(true);
        $mail->Subject = "Your Petite Fille login code";
        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 640px; margin: 0 auto; color: #2f2f2f;'>
                <h2 style='margin-bottom: 12px;'>Sign in to Petite Fille</h2>
                <p>Use the verification code below to continue.</p>
                <div style='background: #f9f7f1; border: 1px solid #e2ddcf; border-radius: 8px; padding: 16px; margin: 16px 0; text-align: center;'>
                    <p style='font-size: 28px; letter-spacing: 4px; margin: 0; font-weight: 700;'>{$safeOtp}</p>
                </div>
                <p>This code expires in 10 minutes.</p>
                <p>If this wasn't you, you can ignore this email.</p>
            </div>
        ";
        $mail->AltBody = "Your Petite Fille verification code is {$otpCode}. It expires in 10 minutes.";
        $mail->send();

        return ["success" => true, "message" => "Verification email sent"];
    } catch (\PHPMailer\PHPMailer\Exception $exception) {
        error_log("Customer OTP email failed: " . $exception->getMessage());
        return ["success" => false, "message" => $exception->getMessage()];
    }
}

