<?php

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

    require_once $autoload;
    $config = require __DIR__ . '/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($reservation["email"], $reservation["full_name"])) {
            return ["success" => false, "message" => "Invalid recipient email address."];
        }
        $mail->isHTML(true);
        $mail->Subject = "Thank you for your reservation - Petite Fille Cafe";
        $mail->Body = buildReservationThankYouBody($reservation, $cancellationLink);
        $mail->AltBody = buildReservationThankYouTextBody($reservation, $cancellationLink);
        $mail->send();

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

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

    require_once $autoload;
    $config = require __DIR__ . '/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."];
        }

        $safeOtpCode = htmlspecialchars($otpCode, ENT_QUOTES, "UTF-8");
        $mail->isHTML(true);
        $mail->Subject = "Your reservation verification code - Petite Fille Cafe";
        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 640px; margin: 0 auto; color: #2f2f2f;'>
                <h2 style='margin-bottom: 12px;'>Verify your email address</h2>
                <p>Use the verification code below to continue your reservation.</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;'>{$safeOtpCode}</p>
                </div>
                <p>This code expires in 10 minutes.</p>
                <p>Petite Fille Cafe</p>
            </div>
        ";
        $mail->AltBody = "Your Petite Fille Cafe reservation verification code is: {$otpCode}. This code expires in 10 minutes.";
        $mail->send();

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

function buildReservationThankYouBody(array $reservation, string $cancellationLink): string
{
    $name = htmlspecialchars($reservation["full_name"], ENT_QUOTES, "UTF-8");
    $date = htmlspecialchars($reservation["reservation_date"], ENT_QUOTES, "UTF-8");
    $time = htmlspecialchars($reservation["reservation_time"], ENT_QUOTES, "UTF-8");
    $guests = (int) $reservation["guests"];

    return "
        <div style='font-family: Arial, sans-serif; max-width: 640px; margin: 0 auto; color: #2f2f2f;'>
            <h2 style='margin-bottom: 12px;'>Thank you for your reservation</h2>
            <p>Hi {$name},</p>
            <p>Your booking request has been received by Petite Fille Cafe.</p>
            <div style='background: #f9f7f1; border: 1px solid #e2ddcf; border-radius: 8px; padding: 16px; margin: 16px 0;'>
                <p style='margin: 4px 0;'><strong>Date:</strong> {$date}</p>
                <p style='margin: 4px 0;'><strong>Time:</strong> {$time}</p>
                <p style='margin: 4px 0;'><strong>Guests:</strong> {$guests}</p>
            </div>
            <p>Thank you,<br>Petite Fille Cafe</p>
        </div>
    ";
}

function buildReservationThankYouTextBody(array $reservation, string $cancellationLink): string
{
    return "Thank you for your reservation at Petite Fille Cafe.\n"
        . "Date: " . $reservation["reservation_date"] . "\n"
        . "Time: " . $reservation["reservation_time"] . "\n"
        . "Guests: " . (int) $reservation["guests"] . "\n\n"
        . "If you are unable to fulfil your booking, please cancel as soon as possible:\n"
        . $cancellationLink . "\n\n"
        . "Petite Fille Cafe";
}
