<?php

namespace Drupal\restaurant\App;


class Misc
{
    protected $conn;
    
    
    
    public function __construct()
    {
        $this->conn = \Drupal::database();
    }
    
    /**
     * {@inheritdoc}
     */
    public function handle()
    {
        // Custom logic goes here.
        $this->forceAdminTheme();
        //return $this->httpKernel->handle($request, $type, $catch);
    }
    
    /**
     * redirect to another path
     * @param $path http path to redirect to
     */
    public function http_redirect($path)
    {
        $path = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . '/' . ltrim(str_replace($_SERVER['SERVER_NAME'], '', $path), '/');
        header("Location: $path");
        exit;
    }
    
    /**
     * Check if parameter exits
     * @param $name name of the parameter to check
     */
    public function hasParam($name)
    {
        $name = \Drupal::routeMatch()->getParameter($name);
        if (empty ($name)) {
            return false;
        }
        return true;
    }
    
    /**
     * Return value of parameter
     * @param $name name of the parameter to return
     */
    public function getParam($name)
    {
        if ($this->hasParam($name)) {
            return \Drupal::routeMatch()->getParameter($name);
        } else if (isset ($_POST[$name])) {
            return $_POST[$name];
        }
        return false;
    }
    
    /**
     * add a drupal error message to the page
     * @param $message message to display
     * @param $type message type, defaults to "message"
     */
    public function addMessage($message, $type)
    {
        switch ($type) {
            case "error":
                \Drupal::messenger()->addError(t($message));
                break;
            case "warning":
                \Drupal::messenger()->addWarning(t($message));
                break;
            case "message":
                \Drupal::messenger()->addMessage(t($message));
        }
        return $this;
    }
    
    /**
     * return true if admin page is in the path
     */
    public function inAdminPath()
    {
        if (strpos($_SERVER['REQUEST_URI'], '/admin') !== false) {
            return true;
        }
        return false;
    }
    
    /**
     * return Drupal session Object
     */
    public function getSession()
    {
        $request = \Drupal::request();
        return $request->getSession();
    }
    
    public function setSetting($name, $value)
    {
        $date = date('Y-m-d H:i:s');
        $count = $this->conn->query("SELECT COUNT(*) FROM restaurant_settings WHERE name = ?", array($name))->fetchField();
        
        if ($count) {
            $update = array(
                'name' => $name,
                'modified' => $date,
                'value' => $value
            );
            $this->conn->update('restaurant_settings')->fields($update)->condition('name', $name)->execute();
            
        } else {
            $insert = array(
                'name' => $name,
                'modified' => $date,
                'created' => $date,
                'value' => $value
            );
            $this->conn->insert('restaurant_settings')->fields($insert)->execute();
        }
        
    }
    
    public function getSetting($name)
    {
        return $this->conn->query("SELECT value FROM restaurant_settings WHERE name = ?", array($name))->fetchField();
    }
    
    /**
     * Force default admin theme even whene user is not the administrator.
     * TODO User must have administrator or restauranthq roles
     *
     */
    public function forceAdminTheme()
    {
        $config = \Drupal::service('config.factory')->getEditable('system.theme');
        
        //$active = \Drupal::service('theme.manager')->getActiveTheme();
        //active);
        
        if ((strpos($_SERVER['REQUEST_URI'], '/admin/appearance') !== false) || (strpos($_SERVER['REQUEST_URI'], '/admin/appearance/default') !== false)) {
            if (isset ($_GET['theme'])) {
                $this->setSetting('defaulttheme', $_GET['theme']);
            }
            return;
        }
        
        if ($this->inAdminPath()) {
            
            \Drupal::service('page_cache_kill_switch')->trigger();
            $config->set('default', 'restaurantadmin')->save();
            
        } else {
            $saved = $this->getSetting('defaulttheme');
            \Drupal::service('page_cache_kill_switch')->trigger();
            $config->set('default', $saved)->save();
            
        }
    } 
}
