<?php

declare(strict_types=1);

function adminNotifierEscape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, "UTF-8");
}

function adminNotifierEnvRecipients(): array
{
    $raw = trim((string) (getenv("PETITE_ADMIN_ALERT_EMAILS") ?: ""));
    if ($raw === "") {
        return [];
    }

    $parts = preg_split("/[;,]+/", $raw) ?: [];
    $emails = [];
    foreach ($parts as $part) {
        $email = strtolower(trim((string) $part));
        if ($email !== "" && filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emails[$email] = $email;
        }
    }

    return array_values($emails);
}

function adminNotifierRecipients(mysqli $conn): array
{
    $recipients = [];

    $stmt = $conn->prepare(
        "SELECT DISTINCT email, name
         FROM users
         WHERE role = 'admin'
           AND email IS NOT NULL
           AND email <> ''"
    );

    if ($stmt) {
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result ? $result->fetch_assoc() : null) {
            if (!is_array($row)) {
                break;
            }

            $email = strtolower(trim((string) ($row["email"] ?? "")));
            if ($email === "" || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                continue;
            }

            $name = trim((string) ($row["name"] ?? ""));
            $recipients[$email] = [
                "email" => $email,
                "name" => $name,
            ];
        }
        $stmt->close();
    }

    foreach (adminNotifierEnvRecipients() as $envEmail) {
        if (!isset($recipients[$envEmail])) {
            $recipients[$envEmail] = [
                "email" => $envEmail,
                "name" => "Admin",
            ];
        }
    }

    return array_values($recipients);
}

function adminNotifierSendRaw(
    mysqli $conn,
    string $subject,
    string $htmlBody,
    string $textBody
): array {
    $autoload = __DIR__ . "/../vendor/autoload.php";
    if (!file_exists($autoload)) {
        return [
            "success" => false,
            "message" => "PHPMailer is not installed.",
        ];
    }

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

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

    $recipients = adminNotifierRecipients($conn);
    if (count($recipients) === 0) {
        return [
            "success" => false,
            "message" => "No admin recipients configured.",
        ];
    }

    try {
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = (string) ($config["host"] ?? "smtp.gmail.com");
        $mail->SMTPAuth = true;
        $mail->Username = (string) ($config["username"] ?? "");
        $mail->Password = (string) ($config["password"] ?? "");
        $mail->Port = (int) ($config["port"] ?? 587);

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

        $fromEmail = (string) ($config["from_email"] ?? "noreply@example.com");
        $fromName = (string) ($config["from_name"] ?? "Petite Fille Cafe");
        $mail->setFrom($fromEmail, $fromName);

        foreach ($recipients as $recipient) {
            $recipientEmail = (string) ($recipient["email"] ?? "");
            $recipientName = (string) ($recipient["name"] ?? "");
            if ($recipientEmail === "") {
                continue;
            }
            $mail->addAddress($recipientEmail, $recipientName);
        }

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

        return [
            "success" => true,
            "message" => "Admin alert email sent.",
        ];
    } catch (\Throwable $exception) {
        return [
            "success" => false,
            "message" => $exception->getMessage(),
        ];
    }
}

function adminNotifierSendEvent(mysqli $conn, string $title, array $details = []): void
{
    $safeTitle = trim($title) !== "" ? trim($title) : "Admin notification";
    $subject = "[Admin Alert] " . $safeTitle;

    $rowsHtml = "";
    $rowsText = [];

    foreach ($details as $label => $value) {
        $safeLabel = adminNotifierEscape((string) $label);
        $safeValue = adminNotifierEscape((string) $value);
        $rowsHtml .= "<tr><td style='padding:6px 10px;border:1px solid #e5e7eb;font-weight:600;'>{$safeLabel}</td>"
            . "<td style='padding:6px 10px;border:1px solid #e5e7eb;'>{$safeValue}</td></tr>";
        $rowsText[] = (string) $label . ": " . (string) $value;
    }

    if ($rowsHtml === "") {
        $rowsHtml = "<tr><td style='padding:6px 10px;border:1px solid #e5e7eb;'>No details</td></tr>";
    }

    $timestamp = date("Y-m-d H:i:s");
    $safeTimestamp = adminNotifierEscape($timestamp);
    $safeHeading = adminNotifierEscape($safeTitle);

    $htmlBody = "
        <div style='font-family: Arial, sans-serif; max-width: 680px; margin: 0 auto; color: #1f2937;'>
            <h2 style='margin-bottom: 8px;'>{$safeHeading}</h2>
            <p style='margin-top: 0; color: #4b5563;'>This alert was generated automatically by Petite Fille Cafe backend.</p>
            <table style='border-collapse: collapse; width: 100%; margin: 12px 0;'>{$rowsHtml}</table>
            <p style='font-size: 12px; color: #6b7280;'>Generated at: {$safeTimestamp}</p>
        </div>
    ";

    $textBody = $safeTitle . "\n"
        . "This alert was generated automatically by Petite Fille Cafe backend.\n\n"
        . implode("\n", $rowsText)
        . "\n\nGenerated at: " . $timestamp;

    $result = adminNotifierSendRaw($conn, $subject, $htmlBody, $textBody);
    if (!($result["success"] ?? false)) {
        error_log("Admin alert email failed: " . (string) ($result["message"] ?? "Unknown error"));
    }
}

