<?php

namespace App\Libraries;

use App\Models\EmailTemplateModel;

class EmailTemplateService
{
    private $templates;

    public function __construct()
    {
        $this->templates = new EmailTemplateModel();
    }

    public function ensureDefaults(): void
    {
        foreach (EmailTemplateDefaults::all() as $default) {
            $key = $default["template_key"];
            if (!$this->templates->where("template_key", $key)->first()) {
                unset($default["variables"]);
                $this->templates->insert($default);
            }
        }
    }

    public function all(): array
    {
        $this->ensureDefaults();
        return $this->templates
            ->orderBy("category", "ASC")
            ->orderBy("id", "ASC")
            ->findAll();
    }

    public function find(string $key): ?array
    {
        $this->ensureDefaults();
        return $this->templates->where("template_key", $key)->first();
    }

    public function variables(string $key): array
    {
        return EmailTemplateDefaults::get($key)["variables"] ?? [];
    }

    public function reset(string $key): bool
    {
        $default = EmailTemplateDefaults::get($key);
        $template = $this->find($key);
        if (!$default || !$template) {
            return false;
        }

        unset($default["variables"], $default["template_key"]);
        return $this->templates->update($template["id"], $default);
    }

    public function sampleVariables(): array
    {
        return [
            "name" => "Aarav Mehta",
            "email" => "aarav@example.com",
            "phone" => "+91 98765 43210",
            "business_name" => "North & Co.",
            "industry" => "Real Estate",
            "style" => "Minimal",
            "budget" => "₹7,999 – ₹14,999",
            "message" =>
                "We need a confident identity for a modern property consultancy.",
            "source" => "homepage",
            "quotation_number" => "BS-Q-1042",
            "invoice_number" => "BS-INV-2081",
            "amount" => "₹12,500",
            "due_date" => date("d M Y", strtotime("+7 days")),
            "attachment_name" => "BrandSquare-quotation.pdf",
            "site_url" => base_url(),
            "admin_leads_url" => base_url("admin/leads"),
            "whatsapp_url" => "https://wa.me/919876543210",
            "from_email" => "hello@brandsquare.com",
        ];
    }

    public function render(string $key, array $variables = []): ?array
    {
        $template = $this->find($key);
        if (!$template) {
            return null;
        }

        $values = array_merge($this->sampleVariables(), $variables);
        $rendered = $template;
        foreach (
            ["subject", "preheader", "heading", "body", "cta_label", "cta_url"]
            as $field
        ) {
            $rendered[$field] = $this->replace(
                (string) ($template[$field] ?? ""),
                $values,
            );
        }

        return [
            "template" => $rendered,
            "subject" => $rendered["subject"],
            "html" => view("emails/branded_template", [
                "template" => $rendered,
            ]),
        ];
    }

    private function replace(string $content, array $variables): string
    {
        return preg_replace_callback(
            "/{{\s*([a-zA-Z0-9_]+)\s*}}/",
            static function ($match) use ($variables) {
                return array_key_exists($match[1], $variables)
                    ? (string) $variables[$match[1]]
                    : $match[0];
            },
            $content,
        );
    }
}
