<?php 
/*
  Conjuro-Web, Easy web builder: Core library

  Copyright (c) 2022 XWolf Override

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/
  
  class Conjuro{
    private $db;
    private $conf;
    private $modlues=[];
    private $controls=[];
    private $basePath;

    function __construct($conf) {
      $this->conf=$conf;
      //$this->loadControls();
    }

    ///////////////////////////////////////////////////// DATABASE TOOLS
    ////////////////////////////////////////////////////////////////////

    /**
     * Insetrs into db lig
     */
    private function DBLog($user,$action,$type,$info){
      $this->db()->insert('user-log',['time'=>date('Y-m-d H:i:s', time()),'user'=>$user,'action'=>$action,'type'=>$type,'info'=>$info]);
    }

    /**
     * Select a list from te database
     */
    public function DBlist($type,$filter=false){      
      $result=$this->db()->list($type,$filter);
      foreach($data as $i => $row){
        $data[$i]['$type']=$type;
      }
      $this->DBLog($_SESSION['user']['user'],'LIST',$type,['filter'=>$filter,'count'=>count($result)]);
      return $result;
    }

    /**
     * Return single entity from DB
     */
    public function DBget($type,$key=""){
      $data=$this->db()->get($type,$key);
      $this->DBLog($_SESSION['user']['user'],'GET',$type,['id'=>$id]);
      return $data;
    }

    public function DBsave($data){
      $type=$data['$type'];
      if ($type=='') // data is not entity
        return;
      $id=$data['id'];
      $dbdata=$this->db()->get($type,$id);
      if (count($dbdata)==0){
          die(var_Dump($this->db->insert($type,$data)));
          $data['id']=$this->db->insert_id;
          DBLog($_SESSION['user']['user'],'INSERT',$type,$data['id']);
      }else{
        $dbdata=$dbdata[0]; // Select the first row
        die("compose a good chnge detetor or use replace");
        $set='';
        $types='';
        $values=[];
        foreach($data as $i => $v){
          if ($i[0]=='$')
            continue;
          if ($dbdata[$i]!=$v){// only differences
            if (strlen($set)>0)
              $set.=',';
            $set.="$i = ?";
            $types.=$data['$types'][$i];
            $values[]=$v;
          }
        }
        $types.='i';
        $values[]=$id;
        if ($set!=''){
          $this->db()->update($type,$set,'where id=?',$types,...$values);   
          $this->DBLog('user-log','user,action,entity,entity_id','sssi',$_SESSION['user']['user'],'UPDATE',$type,$id);
        }
      }
      return $data;
    }

    // Delete an entity, use DBdelete(<entity>) or DBdelete(<entity_type>,<id>)
    public function DBdelete($data,$id=null){
      if (is_string($data)){
        if ($id){
          $type=$data;
        }
      }else{
        $type=$data['$type'];
        if ($type=='') // data is not entity
          return;
        $id=$data['id'];
      }
      $this->db()->delete($type,$id);
      $this->DBLog($_SESSION['user']['user'],'DELETE',$type,$id);
      return $data;
    }

    // Database
    private function db(){
      if(!isset($this->db)){
        switch($this->conf["db-engine"]){
          case "dirDB":
            $dir=getcwd().DIRECTORY_SEPARATOR.$this->conf["db-path"];
            include_once "dirDB.php";
            $this->db=new dirDB($dir);
            break;
          case "webDB":
            include_once "webDB.php";
            $this->db=new webDB($this->conf["db-endpoint"],$this->conf["db-name"],$this->conf["db-key"],$this->conf["db-data-source"]);
            break;
        }
      }
      return $this->db;
    }

    //STATIC: loads a JSON
    public static function loadJson($path){
      $json=file_get_contents($path);
      return json_decode($json, true);
    }

    /////////////////////////////////////////////////////////////// AUTH
    ////////////////////////////////////////////////////////////////////

    /**
     * Process the login information.
     */
    public function login($usr,$pwd){
      $_SESSION['user']=null; // Reset previous login if any
      $usr=strtolower($usr);
      $user=$this->DBget('users',$usr);// TODO check active field.
      $user['user']=strtolower($user['user']);      
      if ($user)
        return $_SESSION['user']=$user;
      // Check for bootstrap/recover users
      foreach($this->conf['bootusers'] as $buser){
        if (strtolower($buser[0])==$usr && $buser[1]==$pwd)
          return $_SESSION['user']=['user'=>strtolower($buser[0]),'name'=>$buser[0]];
      }
    }

    /**
     * Checks the current login information
     */
    public function checkLogin(){
      return true;
      if ($_SESSION['user']) // refresh user data
        return $_SESSION['user']=$this->db()->selectOne('users',null,'where id=? and active=true','i',$_SESSION['user']['id']);
      // Check for bootstrap/recover users
      foreach($this->conf['bootusers'] as $buser){
        if (strtolower($buser[0])==$_SESSION['user']['user'])
          return $_SESSION['user']=['user'=>strtolower($buser[0]),'name'=>$buser[0]];
      }
      $_SESSION['user']=null; //Drop session if not found anymore
    }

    //////////////////////////////////////////////////// MODULE HANDLING
    ////////////////////////////////////////////////////////////////////

    /**
     * Returns a loaded module or load
     */
    public function module($name){
      if (!isset($name) || strpos($name,".")!==false || strpos($name,"/")!==false){
        throw new Exception("Module name error: '$name'.");
      }
      if (!isset($this->modules[$name])){
        $conf=$this->conf;
        $m=include "content/modules/$name.php";
        if ($m===false)
          throw new Exception("Module '$name' does not exists.");
        if (method_exists($m,"init")){
          $m->init($this);
        }
        $this->modules[$name]=$m;
      }
      return $this->modules[$name];
    }

    /**
     * Return the module name knowing the instance
     */
    public function getModuleName($mod){
      foreach($this->modules as $k => $v)
        if ($v===$mod)
          return $k;
      return null;
    }

    /////////////////////////////////////////////////// CONTROL HANDLING
    ////////////////////////////////////////////////////////////////////

    /**
     * Load a control library
     */
    public function loadControlLibrary($name){
      if (!isset($name) || strpos($name,".")!==false || strpos($name,"/")!==false){
        throw new Exception("Name error");
      }
      $ctrls = include "content/controls/$name.php";
      foreach($ctrls as $ctrl){
        $cname=$ctrl->getName();
        if (isset($controls[$cname]))
          throw new Exception("Control '$cname' already defined loading library '$name'.");
          $this->controls[$cname]=$ctrl;
      }
    }

    /**
     * Return a control
     */
    public function control($name){
      if (isset($this->controls[$name]))
        return $this->controls[$name];
      return new ErrorControl($name);
    }

    /**
     * Return the available controls.
     */
    public function listControls(){
      $arr=[];
      foreach($this->controls as $k => $ctrl){
        $arr[]=$k;
      }
      return $arr;
    }

    /**
     * Render a set of cotnrols based on metadata list
     */
    public function renderContent($metaList,$data){
      if ($metaList['@'])
        $this->control($metaList['@'])->render($metaList,$data);
      else
        foreach($metaList as $meta)
          $this->control($meta['@'])->render($meta,$data);
    }

    /**
     * Return a string with the html attributes controlling missing data and alignments.
     */
    public function htmlAttribs($attribs=null){
      $result='';
      if (!$attribs)
        return $result;
      foreach($attribs as $k => $v){
        $v=trim($v);
        if ($v!=''){
          $result.=" $k=\"$v\"";
        }
      }
      return $result;
    }

    /**
     * Open an html tag
     */
    public function htmlOpen($tag,$attribs=null){
      return "<$tag".$this->htmlAttribs($attribs).'>';
    }

    /**
     * Close an html tag
     */
    public function htmlClose($tag){
      return "</$tag>";
    }

    /**
     * Html render helper
     */
    public function rhtml($tag,$attribs=null,$child=null,$single=false){
      echo $this->htmlOpen($tag,$attribs);
      if ($child)
        $child();
      if (!$single)
        echo $this->htmlClose($tag);
    }

    /**
     * Return true is debig mode is set.
     */
    public function isDebug(){
      return $this->conf["debug"];
    }

  }

  /**
   * Base class for module implementation
   */
  abstract class ModuleBase{
    private $mapi=[];
    protected $conf;

    function __construct($conf) {
      $this->conf=$conf;
    }

    protected function register($name,$function){
      $this->mapi[$name]=$function;
    }

    protected function deregister($name){
      unset($this->mapi[$name]);
    }

    public function do($name="",&...$attrs){
      if (!$name)
        $name="main";
      if (!isset($this->mapi[$name])){
        $modname=c()->getModuleName($this);
        throw new Exception("Action '$name' does not exist in module '$modname'.");
      }
      return $this->mapi[$name](...$attrs);
    }
  }

  /** Class for module implementation */
  class Module extends ModuleBase{

  }

  /**
   * Base class for controls
   */
  abstract class Control{
    private $name;
    function __construct($name) {
      $this->name=$name;
    }

    public function getName(){
      return $this->name;
    }

    public function render($meta=null,$data=null){
      $this->renderControl($meta,$data);
    }

    public function getPlaceholders(){
      $this->getControlPlaceholders();
    }

    abstract protected function renderControl($meta,$data);
    
    abstract protected function getControlPlaceholders();
  }

  /**
   * Error control class
   */
  class ErrorControl extends Control{
    protected function getControlPlaceholders(){
      return [];
    }

    protected function renderControl($meta,$data){
      $name = $this->getName();
      echo "[Control '$name' not found]";
    }
  }

  function C(){
    global $c;
    if (!isset($c)){
      $cfg=include "Config.php";
      if($cfg["debug"]){
        error_reporting(E_ALL ^ E_NOTICE);
        ini_set('error_reporting', E_ALL ^ E_NOTICE);
        ini_set('display_errors',1);    
      }
      $c=new Conjuro($cfg);
    }
    return $c;
  }

  function M($name){
    return C()->module($name);
  }

?>