<?php

namespace OtomaticAi\RestControllers;

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

class TemplateRestController extends RestController
{
    public function index()
    {
        $templates = Template::orderBy("created_at", "desc")->get();

        return $templates;
    }

    public function store()
    {
        $validated = $this->validate([
            "project_id" => ["required", "integer"],
            "name" => ["string", "required"],
        ]);

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

        if (empty($project)) {
            return new WP_Error('not_found', 'Project not found', ['status' => 404]);
        }

        $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()) {
            return $template;
        }

        return new WP_Error('error', 'Unable to create the template.', ['status' => 503]);
    }

    public function import()
    {
        $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);
        }

        $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,
        ]);

        if ($template->save()) {
            return $template;
        }

        return new WP_Error('error', 'Unable to create the template.', ['status' => 503]);
    }

    public function destroy()
    {
        $id = $this->input('id');

        $template = Template::find($id);

        if (empty($template)) {
            return new WP_Error('not_found', 'Template not found', ['status' => 404]);
        }

        $template->delete();
    }
}
