<?php

namespace pictpostpersonal\model;

use pictpostpersonal\InvalidDataException;
use pictpostpersonal\SQLiteCRUD;
use pictpostpersonal\SQL;

class Template
{

    private SQLiteCRUD $sqlcrud;

    public function __construct(\PDO $sqlcrud)
    {
        $this->sqlcrud = new SQLiteCRUD($sqlcrud);
    }

    public static function initialize(SQLiteCRUD $sql_crud)
    {

        $sql_crud->table('templates')->createTable(
            [
                SQL::Id('id'),
                SQL::Text('template_name'),
                SQL::Integer('template_sort', 10),
                SQL::Text('value'),
                SQL::Text('option1'),
                SQL::Text('option2'),
                SQL::Text('option3'),
                SQL::Text('option4'),
                SQL::Text('option5'),
                SQL::Text('option6')
            ],
            [
                'template_name',
            ]
        );
    }

    public function getTemplates(string $template_name = ''): array
    {
        if ($template_name != '') {
            $query = 'template_name = :template_name';
            $conditions = ['template_name' => $template_name];
        } else {
            $query = '';
            $conditions = [];
        }
        return $this->sqlcrud->table('templates')->orderBy('id asc')->where($query, $conditions)->fetch();
    }

    public function add(string $template_name, $sort, string $value, array $options): array
    {
        if ($template_name == '') {
            throw new InvalidDataException('テンプレート名を指定してください');
        }
        if (!is_numeric($sort)) {
            throw new InvalidDataException('ソートは数字で指定してください');
        }
        $data = [
            'template_name' => $template_name,
            'template_sort' => $sort,
            'value' => $value,
        ];
        for ($i = 1; $i <= 6; $i++) {
            if (isset($options[$i])) {
                $data["option$i"] = $options[$i];
            }
        }
        $id = $this->sqlcrud->table('templates')->create($data);
        $data['id'] = $id;
        return $data;
    }

    public function delete($id): void
    {
        $this->sqlcrud->delete('templates', $id);
    }
}
