<?php

namespace Signteer\Core\Writer;

use Plainwork\Database\Database;
use Plainwork\Database\Query;
use Signteer\Core\Database\SheetTable as Table;
use Signteer\Core\WordPress\SheetPostType;

class SheetWriter
{
    public $db = Database::class;

    public function create(string $title, string $description): int
    {
        $wpPostId = SheetPostType::insert($title, $description);

        $q = $this->db->q();

        $q->insertInto(Table::NAME);
        $q->valueInt(Table::COL_ID, $wpPostId);
        $q->valueString(Table::COL_TITLE, $title);
        $q->valueString(Table::COL_DESCRIPTION, $description);

        $id = $q->execute();

        return $id;
    }

    public function delete(int $id)
    {
        $q = $this->db->q();

        $q->deleteFrom(Table::NAME);
        $q->whereInt(Table::COL_ID, '=', $id);

        $q->execute();
    }

    public function update(int $id, ?string $title, ?string $description)
    {
        if (null !== $title or null !== $description) {
            $q = $this->db->q();

            $q->update(Table::NAME);
            if (null !== $title) {
                $q->valueString(Table::COL_TITLE, $title);
            }
            if (null !== $description) {
                $q->valueString(Table::COL_DESCRIPTION, $description);
            }
            $q->whereInt(Table::COL_ID, '=', $id);

            $q->execute();
        }

        if (null !== $title) {
            SheetPostType::updateTitle($id, $title);
        }

        if (null !== $description) {
            SheetPostType::updateDescription($id, $title);
        }
    }
}
