<?php
namespace SPAATG\Model;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}

use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;

class SettingsModel extends \SPAATG\Model
{
		private static $instance;

		private $option_name = 'spaatg_settings';

		private $updated = false;

	protected $model = array(
        'siteAuthUser' => ['s' => 'string', 'default' => ''], // string
        'siteAuthPass' => ['s' => 'string', 'default' => ''], // string
				'mediaLibraryViewMode' => ['s' => 'int', 'default' => false], // set in installhelper
				'currentVersion' => ['s' => 'string', 'default' => null, 'export' => false], // last known version of plugin. Used for updating
				'quotaExceeded' => ['s' => 'int', 'default' => 0, 'export' => false], // indicator for quota
				'httpProto' => ['s' => 'string', 'default' => 'https'], // Less than optimal setting for using http(s)
				'activationDate' => ['s' => 'int', 'default' => null, 'export' => false], // date of activation
				'currentStats' => ['s' => 'array', 'default' => array(), 'export' => false], // whatever the current stats are.
        'currentVersion' => ['s' => 'string', 'default' => '', 'export' => false],
        'redirectedSettings' => ['s' => 'int', 'default' => 0],
        'exif_ai' => ['s' => 'int', 'default' => 0],
        'enable_ai' => ['s' => 'boolean', 'default' => true],
        'autoAI' => ['s' => 'boolean', 'default' => false],
        'autoAIBulk' => ['s' => 'boolean', 'default' => true],
        'aiPreserve' => ['s' => 'boolean', 'default' => false ],
        'ai_general_context' => ['s' => 'string', 'default' => 'callback', 'maxlength' => 500],
        'ai_use_post' => ['s' => 'boolean', 'default' => true],
        'ai_gen_alt' => ['s' => 'boolean', 'default' => true],
        'ai_gen_caption' => ['s' => 'boolean', 'default' => true],
        'ai_gen_description' => ['s' => 'boolean', 'default' => true],
        'ai_gen_post_title' => ['s' => 'boolean', 'default' => true], 
        'ai_filename_prefercurrent' => ['s' => 'boolean', 'default' => false],
        'ai_limit_alt_chars' => ['s' => 'int', 'default' => 100, 'max' => 200],
        'ai_alt_context' => ['s' => 'string', 'default' => '', 'maxlength' => 200],
        'ai_limit_description_chars' => ['s' => 'int', 'default' => 200, 'max' => 500],
        'ai_description_context' => ['s' => 'string', 'default' => '', 'maxlength' => 200],
        'ai_limit_caption_chars' => ['s' => 'int', 'default' => 150, 'max' => 250],
        'ai_caption_context' => ['s' => 'string', 'default' => '', 'maxlength' => 200],
        'ai_post_title_context' => ['s' => 'string',  'default' => '', 'maxlength' => 200], 
        'ai_limit_post_title_chars' => ['s' => 'string', 'default' => 50, 'max' => 100],
        'ai_gen_filename' => ['s' => 'boolean', 'default' => false],
        'ai_limit_filename_chars' => ['s' => 'int', 'default' => 30, 'max' => 200],
        'ai_filename_context' => ['s' => 'string', 'default' => '', 'maxlength' => 200],
        'ai_use_exif' => ['s' => 'boolean', 'default' => true],
        'ai_language' => ['s' => 'string', 'default' => 'callback'],
     
 

    );

		private $settings;

		public function __construct()
		{
       $this->model['ai_general_context']['default'] = array($this, 'generateContextDefault');
       $this->model['ai_language']['default'] = array($this, 'returnSiteLanguage');

			 $this->load();
		}

		public static function getInstance()
		{
			 if (is_null(self::$instance))
			 {
					self::$instance = new static();
			 }
			 return self::$instance;
		}

		protected function load()
		{
       $this->settings = $this->check(get_option($this->option_name, []));

       if (false === function_exists('register_shutdown_function'))
       {
          Log::addError('Register shutdown function not found!');
       }
       else
       {
          register_shutdown_function([$this, 'onShutdown']);
       }

       // This is done dual since it seems that -sometimes- for reasons unknown the PHP solution doesn't work. 
       add_action('shutdown', [$this, 'onShutdown']);
			 
		}

		protected function save()
		{
				$res = update_option($this->option_name, $this->settings);
        $this->updated = false; // Prevent double saves with this.
		}

		public function __get($name)
		{
			 if (isset($this->settings[$name]))
			 {
				  return $this->sanitize($name, $this->settings[$name]);
			 }
       elseif (isset($this->model[$name]))
       {
          if (isset($this->model[$name]['default']))
          {
              $default = $this->model[$name]['default']; 
              if (is_array($default))
              {
                  if (is_callable($default))                 
                  {
                    return call_user_func($default);
                  }
              }
              else
              {
                return $default; 
              }

          }

       }
			 else {
			 	Log::addWarn('Call for non-existing setting: ' . $name);
			 }
		}

    protected function generateContextDefault()
    {
       $site_title = get_bloginfo('name'); 
       $wp_url = get_bloginfo('url');

       $string = sprintf('Act like an SEO expert and generate an SEO-friendly ALT tag, caption, and description for the images from %s, titled %s, focusing on keywords and relevance for optimal image SEO.', $wp_url, $site_title);
       return $string;
    }

    protected function returnSiteLanguage()
    {
       return get_locale();
    }

    // This function is meant for version checks ( settings removed / added ) and filter overrides for specific use-cases.
    protected function check($settings)
    {
        $settings = apply_filters('spaatg/settings/check', $settings);
        return $settings;
    }

    public function __set($name, $value)
    {
      $this->set($name, $value);
    }

    protected function set($name, $value)
    {
      if (isset($this->model[$name]))
      {
        $this->settings[$name] =  $this->sanitize($name, $value);
				$this->updated = true;
      }
      else {
         Log::addWarn('Setting ' . $name . ' not defined in settingsModel');
      }
    }

    public function setIfEmpty($name, $value)
    {
        if (true === $this->exists($name) && false === $this->isset($name))
        {
           $this->set($name, $value);
					 return true;
        }

				return false;
    }

		// Simple function which can be expanded.
		public function exists($name)
		{
			  return (isset($this->model[$name])) ? true : false;
		}

		public function isset($name)
		{
			return (isset($this->settings[$name])) ? true : false;

		}

    /** Check if this entry in settings should be in import / export function . Some are internal / site only .
     * 
     * @param string $name 
     * @return bool 
     */
    public function forExport($name)
    {
       if (false === $this->exists($name))
       {
         return false; 
       }

       if (isset($this->model[$name]['export']))
       {
          return $this->model[$name]['export'];
       }

       return true; // if no rules, ok .

    }

    public function getExport()
    {
        $data = $this->getData(); 
        $export = []; 
        foreach($data as $name => $value)
        {
           if (false === $this->forExport($name))
           {
             continue; 
           }
           $export[$name] = $value; 
        }

        return $export;
    }


		public function deleteOption($name)
		{
				if ($this->exists($name) && $this->isset($name))
				{
					 unset($this->settings[$name]);
					 $this->save();
				}
		}


    public function deleteAll()
    {
        delete_option($this->option_name);
    }

    /**
     * PHP shutdown function, check if settings are updated and save on closing time.
     * @return null
     *
     *  Note: This is public instead of protected /private because of bug in PHP 7.4 not liking that.
     */
		public function onShutdown()
		{
				if (true === $this->updated)
				{
						$this->save();

				}
		}

} // class
