<?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 meta($name){
    return $this->meta[$name];
  }

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

  /**
   * Sets a data field
   */
  public function setData($name,$value){
    $this->data[$name]=$value;
  }

  /**
   * Sets the data dictionary of the page
   */
  public function setAllData($datablock){
    $this->data=$datablock;
  }

  /**
   * Gets the data dictionary of the page
   */
  public function getAllData(){
    return $this->data;
  }

  /**
   * Gets the meta dictionary of the page
   */
  public function getAllMeta(){
    return $this->meta;
  }

  /**
   * Show the content defined for a section on page meta
   */
  public function showContent($name){
    if (isset($this->meta[$name])){
      c()->renderContent($this->meta[$name],$this->data);
    }
  }

  /**
   * Prepare page (load dependencies if any)
   */
  public function prepare(){
    if(isset($this->meta['control-libraries'])){
      foreach($this->meta['control-libraries'] as $clib){
        c()->loadControlLibrary($clib);
      }
    }
    if(isset($this->meta['controller'])){
      foreach($this->meta['controller'] as $ctrl){
        c()->module($ctrl['module'])->do($ctrl['action'],$this);
      }
    }
  }

  /**
   * Page needs authorization of any kind
   */
  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']){
      $page=$this->getPage($this->conf["login-page"]);
    }else{
      $page->setData('username',$_SESSION['user']['name']);
      $page->setData('userid',$_SESSION['user']['id']);
    }
    $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(){
    if ($_GET['logout']=='yes')
      session_destroy();
    // 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
    if ($_POST['user'])
      c()->login($_POST['user'],$_POST['pwd']);
    else
      c()->checkLogin();
  }
  
  // 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();
    });
  }
}
?>