<?php

namespace OtomaticAi\Controllers;

use OtomaticAi\Models\Project;
use OtomaticAi\Models\Template;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class TemplateController extends Controller
{
    const MINIMUM_VERSION = "4.0.0";

    public function index()
    {
        $this->verifyNonce();

        $this->response($this->getTemplates());
    }

    public function store()
    {
        $this->verifyNonce();

        $validated = $this->validate([
            "name" => ["string", "required"],
            "project" => ["required", "integer"],
        ]);

        $project = Project::find($this->input("project"));

        $payload = [
            "modules" => $project->modules,
        ];

        Arr::forget($payload, "modules.autopilot");

        $template = new Template([
            "name" => $validated["name"],
            "plugin_version" => OTOMATIC_AI_VERSION,
            "payload" => $payload,
        ]);

        if ($template->save()) {
            $this->emptyResponse();
        }

        $this->response(["message" => "An error occurred", "error" => "Unable to create the template."], 503);
    }

    public function destroy()
    {
        $this->verifyNonce();

        $this->validate([
            "template" => ["required", "integer"],
        ]);

        $template = Template::find($this->input('template'));
        if ($template) {
            $template->delete();
        }

        $this->emptyResponse();
    }

    public function export()
    {
        $this->verifyNonce();

        $this->validate([
            "template" => ["required", "integer"],
        ]);

        $template = Template::find($this->input('template'));
        if ($template) {

            $payload = $template->payload;

            Arr::forget($payload, 'persona_id');
            Arr::forget($payload, "modules.autopilot");
            Arr::forget($payload, "modules.wordpress.author_id");
            Arr::forget($payload, "modules.wordpress.parent_page_id");
            Arr::forget($payload, "modules.wordpress.categories.custom");
            Arr::forget($payload, "modules.wordpress.template");

            $data = [
                "name" => $template->name,
                "plugin_version" => $template->plugin_version,
                "payload" => $payload,
            ];

            $data = json_encode($data);
            $data = base64_encode($data);

            $this->response($data);
        }

        $this->emptyResponse();
    }

    public function import()
    {
        $this->verifyNonce();

        $this->validate([
            "import_data" => ["required", "string"],
        ]);

        $data = $this->input("import_data");
        $data = base64_decode($data);
        $data = json_decode($data, true);

        if (!isset($data["name"])) {
            $this->response(["message" => "The import code is invalid", "errors" => ['import_data' => ["The import code is invalid"]]], 422);
        }

        if (version_compare(Arr::get($data, "plugin_version", "0.0.0"), self::MINIMUM_VERSION, '<')) {
            $this->response(["message" => "The template was made with too low a version (v" . self::MINIMUM_VERSION . " required)", "errors" => ['import_data' => ["The template was made with too low a version (v" . self::MINIMUM_VERSION . " required)"]]], 422);
        }

        $payload = Arr::get($data, "payload", []);

        Arr::forget($payload, 'persona_id');
        Arr::forget($payload, "modules.autopilot");
        Arr::forget($payload, "modules.wordpress.author_id");
        Arr::forget($payload, "modules.wordpress.parent_page_id");
        Arr::forget($payload, "modules.wordpress.categories.custom");
        Arr::forget($payload, "modules.wordpress.template");

        $template = new Template([
            "name" => Arr::get($data, "name", "new template"),
            "plugin_version" => Arr::get($data, "plugin_version", OTOMATIC_AI_VERSION),
            "payload" => $payload,
        ]);

        $template->save();

        $this->emptyResponse();
    }

    private function getTemplates()
    {
        return Template::orderBy("created_at", "desc")->get()->filter(function (Template $template) {
            return version_compare($template->plugin_version, self::MINIMUM_VERSION, '>=');
        })->values();
    }
}
