<?php

namespace App\Controllers;

use App\Libraries\EmailTemplateDefaults;
use App\Libraries\EmailTemplateService;
use App\Models\EmailTemplateModel;

class EmailTemplates extends BaseController
{
    public function index()
    {
        $service = new EmailTemplateService();

        return view("admin/email_templates/index", [
            "templates" => $service->all(),
        ]);
    }

    public function edit(string $key)
    {
        $service = new EmailTemplateService();
        $template = $service->find($key);
        if (!$template || !EmailTemplateDefaults::get($key)) {
            return redirect()
                ->to(base_url("admin/email-templates"))
                ->with("error", "Email template not found.");
        }

        if ($this->request->getMethod() === "post") {
            $rules = [
                "subject" => "required|max_length[255]",
                "preheader" => "required|max_length[255]",
                "heading" => "required|max_length[180]",
                "body" => "required|max_length[5000]",
                "cta_label" => "permit_empty|max_length[80]",
                "cta_url" => "permit_empty|max_length[500]",
                "accent_color" => "required|regex_match[/^#[0-9a-fA-F]{6}$/]",
            ];

            if (!$this->validate($rules)) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        implode(" ", $this->validator->getErrors()),
                    );
            }

            (new EmailTemplateModel())->update($template["id"], [
                "subject" => trim((string) $this->request->getPost("subject")),
                "preheader" => trim(
                    (string) $this->request->getPost("preheader"),
                ),
                "heading" => trim((string) $this->request->getPost("heading")),
                "body" => trim((string) $this->request->getPost("body")),
                "cta_label" => trim(
                    (string) $this->request->getPost("cta_label"),
                ),
                "cta_url" => trim((string) $this->request->getPost("cta_url")),
                "accent_color" => strtolower(
                    (string) $this->request->getPost("accent_color"),
                ),
                "enabled" => $this->request->getPost("enabled") ? 1 : 0,
            ]);

            return redirect()
                ->to(base_url("admin/email-templates/" . $key))
                ->with("success", "Email template saved.");
        }

        return view("admin/email_templates/edit", [
            "template" => $template,
            "variables" => $service->variables($key),
        ]);
    }

    public function preview(string $key)
    {
        $rendered = (new EmailTemplateService())->render($key);
        if (!$rendered) {
            return $this->response->setStatusCode(404);
        }

        return $this->response
            ->setContentType("text/html")
            ->setBody($rendered["html"]);
    }

    public function reset(string $key)
    {
        if (!(new EmailTemplateService())->reset($key)) {
            return redirect()
                ->to(base_url("admin/email-templates"))
                ->with("error", "Email template not found.");
        }

        return redirect()
            ->to(base_url("admin/email-templates/" . $key))
            ->with("success", "Default template restored.");
    }
}
