<?php

namespace GriffinForms\Admin\App;

use GriffinForms\Traits\Singleton;

class Utility extends \GriffinForms\Admin\App\Format
{
    use Singleton;
    
    protected $form_id_name = 'form_id';
    protected $is_form_id_set;
    protected $form_id;
    protected $is_form_id_valid;
    protected $form;
    protected $form_count;
    protected $context;

    protected function setIsFormIdSet()
    {
        if (isset($_GET[$this->form_id_name]) && !empty($_GET[$this->form_id_name]) && absint(wp_unslash($_GET[$this->form_id_name])) > 0) {
            $this->is_form_id_set = true;
        } else {
            $this->is_form_id_set = false;
        }
    }

    protected function setFormId()
    {
        if ($this->is_form_id_set) {
            $this->form_id = absint($_GET[$this->form_id_name]);
        }
    }

    protected function setIsFormIdValid()
    {
        if ($this->is_form_id_set) {
            $test = $this->sql->itemExists('form', $this->form_id);
            if ($test) {
                $this->is_form_id_valid = true;
            } else {
                $this->is_form_id_valid = false;
            }
        } else {
            $this->is_form_id_valid = false;
        }
    }

    protected function setForm()
    {
        if ($this->is_form_id_valid) {
            $this->form = new \GriffinForms\Items\Form();
            $this->form->loadItem($this->form_id);
        }
    }

    public function getForm()
    {
        if ($this->is_form_id_valid and is_object($this->form)) {
            return $this->form;
        } else {
            return false;
        }
    }

    public function getFormId() {
        if ($this->is_form_id_valid && !empty($this->form_id)) {
            return $this->form_id;
        }
        return false;
    }

    public function setFormContext(int $form_id): void
    {
        $_GET[$this->form_id_name] = $form_id;
        $this->setIsFormIdSet();
        $this->setFormId();
        $this->setIsFormIdValid();
        $this->setForm();
    }

    protected function setFormCount()
    {
        $this->form_count = $this->sql->getItemCount('form');
    }

    protected function setContext()
    {
        if ($this->is_form_id_valid) {
            $this->context = 'form-layout';
            return;
        }

        if (!$this->is_form_id_valid and $this->form_count > 0) {
            $this->context = 'form-select';
            return;
        }

        $this->context = 'form-create';
    }
}
