<?php
use \Medoo\Medoo;

/**
 * Database configuration handler class
 * @author Jérôme Brilland
 * @version 3.0
 * @copyright (c) 2019-2023, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class DatabaseConfigurationHandler extends ConfigurationHandler {

    /**
     * @var Medoo Database connection
     * @access private
     */
    private $database = null;

    /**
     * @var string Table name
     * @access private
     */
    private $tableName = null;

    /**
     * @var string Name column
     * @access private
     */
    private $nameColumn = null;

    /**
     * @access private
     */
    private $valueColumn = null;
    
    /**
     * @access protected
     */
    protected $logger = null; 

    /**
     * Class constructor
     * @param string tableName table name
     * @param string nameColumn
     * @param string valueColumn
     * @param Meedo database
     * @access public
     */
    public function __construct( string $tableName, string $nameColumn, string $valueColumn, Medoo $database, ILogger $logger ) {
        $this->database = $database;
        $this->tableName = $tableName;
        $this->nameColumn = $nameColumn;
        $this->valueColumn = $valueColumn;
        $this->logger = $logger;
    }

    /**
     * @access public
     */
    public function load() {
        $this->values = array_column( $this->database->select( $this->tableName, [$this->nameColumn, $this->valueColumn] ), $this->valueColumn, $this->nameColumn );
        $error = $this->database->error;
        if ( $error ) {
            throw new ErrorException( $error );
        }
        return $this;
    }

    /**
     * Saves settings to database
     * @access public
     */
    public function save() {
        foreach ( $this->values as $key => $value ) {
            if ( $this->database->has( $this->tableName, ['name' => $key] ) ) {
                $this->database->update( $this->tableName, ['value' => $value], ['name' => $key] );
            } else {
                $this->database->insert( $this->tableName, ['name' => $key, 'value' => $value] );
            }
            $error = $this->database->error;
            $this->logger->debug( $this->database->last() );
            if ( $error ) {
                throw new ErrorException( $error );
            }
        }

        foreach( $this->database->select( $this->tableName, [$this->nameColumn] ) as $data ) {
            if ( !array_key_exists( $data[$this->nameColumn], $this->values ) ) {
                $this->database->delete( $this->tableName, [$this->nameColumn => $data[$this->nameColumn]] );
                $error = $this->database->error;
                $this->logger->debug( $this->database->last() );
                if ( $error ) {
                    throw new ErrorException( $error );
                }
            }
        }
        return $this;
    }

}
