<?php
namespace boru\boruai\UI\Actions;

use boru\boruai\Models\Template;

class TemplateAction extends Ajax {

    public function handle() {
        static::init(true);
        $mode = $this->request("mode");
        if(!$mode) {
            Ajax::error([], "No mode provided");
            return;
        }
        $method = "handle" . ucfirst($mode)."Template";
        if(!method_exists($this, $method)) {
            Ajax::error([], "Invalid mode provided");
            return;
        }
        return $this->$method();
    }

    public function handleLoadTemplate() {
        $template = $this->request("template");
        if(!$template) {
            Ajax::error([], "No template provided");
            return;
        }
        $template = Template::fromId($template);
        if(!$template) {
            Ajax::error([], "Template not found");
            return;
        }
        $result = [
            "success" => true,
            "template" => $template
        ];
        Ajax::response($result);
        return;
    }

    public function handleListTemplates() {
        $templates = Template::getAll();
        $result = [
            "success" => true,
            "templates" => $templates
        ];
        Ajax::response($result);
        return;
    }
    public function handleDeleteTemplate() {
        $template = $this->request("template");
        if(!$template) {
            Ajax::error([], "No template provided");
            return;
        }
        $template = Template::fromId($template);
        if(!$template) {
            Ajax::error([], "Template not found");
            return;
        }
        $template->delete();
        $result = [
            "success" => true,
            "message" => "Template deleted"
        ];
        Ajax::response($result);
        return;
    }
    public function handleSaveTemplate() {
        $template = $this->request("template");
        if(!$template) {
            Ajax::error([], "No template provided");
            return;
        }
        $template = Template::fromId($template);
        if(!$template) {
            Ajax::error([], "Template not found");
            return;
        }
        $template->save();
        $result = [
            "success" => true,
            "message" => "Template saved"
        ];
        Ajax::response($result);
        return;
    }
}