<?php
/*
  Conjuro-Web, Easy web builder: Page render module

  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.
*/

abstract class PageBase{
  private $name;
  private $conf;
  private $meta;
  private $data;

  function __construct($name,$conf) {
    $this->meta=Conjuro::loadJson("content/pages/$name.json");
    if($this->meta===null)
      throw new Exception("Page '$name' does not exists.");
    $this->name=$name;
    $this->conf=$conf;
  }

  // META:LAYOUT
  protected function getLayoutFile(){
    return "content/fragment/".$this->meta["layout"].".php";
  }
  // META:NAME
  protected function getName(){
    return $this->name;
  }

  // Renders a fragmet (but in child class context)
  abstract protected function showFragment($name);

  /**
   * Return the value defined for a page meta key
   */
  public function conf($name){
    return $this->conf[$name];
  }

  /**
   * Return the value defined for a page meta key
   */
  public function value($name){
    return $this->meta[$name];
  }

  /**
   * Return the value defined for a page meta key
   */
  public function data($name){
    return "{{$name}}";//$this->data[$name];
  }

  /**
   * Show the content defined for a section on page meta
   */
  public function showContent($name){
    if (isset($this->meta[$name])){
      foreach($this->meta[$name] as $ci){//ControlInfo
        echo"<div class='control ".$ci["class"]."' style='".$ci["css"]."' id='".$ci["id"]."' data-type='".$ci["@"]."'>";
        c()->control($ci["@"])->render($ci["meta"]); //TODO: Data here when implemented
        echo"</div>";
      }
    }
  }

  public function prepare(){
    if(isset($this->meta["control-libraries"])){
      foreach($this->meta["control-libraries"] as $clib){
        c()->loadControlLibrary($clib);
      }
    }
  }
  
  public function needAuth(){
    return isset($this->meta["auth"]);
  }

}

class Page extends PageBase{

  // Renders the page
  public function showPage(){
    self::prepare();
    include(self::getLayoutFile());
  }

  // Renders a fragment
  protected function showFragment($name){
    include self::filePath($name.".php");
  }

}

return new class($conf) extends Module{

  private $pages=[];
  private $page="";

  // Render current page
  public function showPage(){
    $this->processRequest();
    $page=$this->getPage($this->currentPage());
    if ($page->needAuth() && !$_SESSION['user']){
      //TODO Goes to Auth module
      $page=$this->getPage($this->conf["login-page"]);
    }
    $page->showPage();
  }

  //Loads page meta from page name (id)
  private function getPage($name){
    if (!isset($this->pages[$name]))
      $this->pages[$name]=new Page($name,$this->conf);
    return $this->pages[$name];
  }

  private function processRequest(){
    // Current page
    if (isset($_GET["page"]))
      $this->page=$_GET["page"];
    else if (isset($_SESSION["page"]))
      $this->page=$_SESSION["page"];
    else
      $this->page=$this->conf["index-page"];
    $_SESSION["page"]=$this->page;
    // Session (TODO: Goes to Auth Module)
    if ($_POST['user'])
      $_SESSION['user']=$this->doLogin($_POST['user'],$_POST['pwd']);
    else if ($_SESSION['user']) // refresh user data
      $_SESSION['user']=$this->db->selectOne('users',null,'where user=?','s',$_SESSION['user']['user']);
    if ($_GET['logout']=='yes')
      session_reset();
  }

  //TODO Goes to Auth module
  private function doLogin($user,$access){
    return $this->db->selectOne("users",null,'where user=? and pass=sha1(?)','ss',$user,$access);
  }
  
  // Get current selected page
  private function currentPage(){
    return $this->page;      
  }

  public function init(){
    $this->register("main",function(){
      $this->showPage();
    });
    $this->register("showPage",function(){
      $this->showPage();
    });
  }
}
?>