<?php

namespace Controller;

class Page {

    public static $keyword = "page"; // variable in URL (query string)

    
    function index(\Base $f3, $params) {
        /////////////////////////////
        // what page are we watching?
        $page = $params[self::$keyword];
        $f3->set('page', $page);
        $f3->set('bodyClass',"page-$page");
        
        switch ($page) {
        case 'home':
        default:
            $f3->mset(array(
                'template'=>'tpl/index.html',
                'templateContent'=>'maincontent.html'
            ));
            self::folder2();
            break;
        }        
    }


    ////////////////
    // interfaces //
    ////////////////
    function home() {
        $f3 = \Base::instance();
        self::index($f3, array('page'=>'home'));
    }
    function secondLevel(\Base $f3,$params) {
        self::index($f3, array('page'=>$params['level1']."/".$params['level2']));
    }
    function thirdLevel(\Base $f3,$params) {
        self::index($f3, array('page'=>$params['level1']."/".$params['level2']."/".$params['level3']));
    }
    function fourthLevel(\Base $f3,$params) {
        self::index($f3, array('page'=>$params['level1']."/".$params['level2']."/".$params['level3']."/".$params['level4']));
    }

    
    

    //////////////////
    // main program //
    //////////////////
    function folder2() {
        $f3 = \Base::instance();
        $page = $f3->get('page');
        $f3->set('current_page_folder', $f3->get('CONTENT').$page."/");

        $folder = new \Modules\FilesInFolders(
            $f3->get('current_page_folder'),
            array(
                'content'=>array(
                    'secondary'=>'secondary',
                    'zzz'=>'hidden',
                    'unpublish'=>'hidden'
                ),
                'keyfiles'=>array(
                    'banner'=>array(
                        'until'=>$f3->get("CONTENT"),
                        'type'=>'pic'
                ))
            )
        );

        $folder->prepare_files();
        $folder->fill_content();
        
                // set template variables
        $banner = new \Modules\CachedImage($folder->extras['banner']);
        $f3->set('banner',$banner->get_src(2000));
        // $f3->set('background',$background);
        $f3->set('content', implode("\n", $folder->content['default']));
        $f3->set('secondary_content', implode("\n", $folder->content['secondary']));
        
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    function folder() {
        $f3 = \Base::instance();
        $page = $f3->get('page');
        $folder = $f3->get("CONTENT").$page."/";

        $EXT=array(
            'pic'=>array( 'jpg', 'jpeg', 'png', 'svg' ),
            'tpl'=>array( 'html', 'htm', 'tpl' ),
            'txt'=>array( 'txt', 'text', 'md' ),
            'csv'=>array( 'csv' )
        );
        
        $background = "";
        $banner = "";
        $c1 = array(
           // 'background'=>'',
            'pic'=>array(),
            'txt'=>array(),
            'tpl'=>array(),
            'csv'=>array()
        );
        $c2 = array(
           // 'background'=>'',
            'pic'=>array(),
            'txt'=>array(),
            'tpl'=>array(),
            'csv'=>array()
        );
        $primary = array();
        $secondary = array();

        
        // collect contents of folder into an organised array
        if(!is_dir($folder)) $folder=$f3->get("CONTENT")."../404/";
        $ls = scandir($folder);
        foreach ($ls as $key=>$f) {
            if(!strncmp($f,'.',1)) continue; // ignore hidden files
            $ex=explode(".", $f);
            $ext=end($ex);
            if(in_array(strtolower($ext), $EXT['pic'])) {
                if($ex[0]=='background') {
                    $background=pic_cache($folder.$f,836);
                } elseif($ex[0]=='banner') {
                    $banner=$folder.$f;
                } elseif($ex[0]=='secondary') {
                    $c2['pic'][$ex[1]] = $folder.$f;
                } else {
                    $c1['pic'][$ex[0]] = $folder.$f;
                }
            } elseif(in_array(strtolower($ext), $EXT['txt'])) {
                if($ex[0]=='secondary') {
                    $c2['txt'][$ex[1]] = $folder.$f;
                } else {
                    $c1['txt'][$ex[0]] = $folder.$f;
                }
            } elseif(in_array(strtolower($ext), $EXT['tpl'])) {
                if($ex[0]=='secondary') {
                    $c2['tpl'][$ex[1]] = $folder.$f;
                } else {
                    $c1['tpl'][$ex[0]] = $folder.$f;
                }
            } elseif (in_array(strtolower($ext), $EXT['csv'])) {
                if($ex[0]=='secondary') {
                    $c2['csv'][$ex[1]] = $folder.$f;
                } else {
                    $c1['csv'][$ex[0]] = $folder.$f;
                }
            } else {  }
        }

        if(!$banner) {
            $banner = self::search_up("banner", array($folder,$f3->get("CONTENT")), $EXT['pic']);
        }
       
        // compose elements based on the organised array
        $md = new \Parsedown();
        foreach($c1['txt'] as $key=>$file) {
            $str = file_get_contents($file);
            $str = self::linkify($str);
            $str = self::get_config_from_content($str);
            $str = $md->text($str);
            $str = sprintf("<div class='post'>%s</div>", $str);
            $primary[$key] = sprintf("<div class=\"item %s %s\">%s</div>", $page,$key,$str);
        }
        foreach($c1['tpl'] as $key=>$file) {
            $str = file_get_contents($file);
            $str = \Template::instance()->render($file);
            $str = self::linkify($str);
            if(array_key_exists($key,$c1['pic'])) {
                $str = sprintf("%s\n%s", 
                    \Modules\Pictures::makeImageLink($c1['pic'][$key]),
                    $str);
                    unset($c1['pic'][$key]);
            }
            $primary[$key] = sprintf("<div class=\"item %s %s\">%s</div>", $page ,$key,$str);
        }
        foreach($c1['pic'] as $key=>$file) {
            $primary[$key] = sprintf("<img src=\"$file\" />");
        }
        foreach($c1['csv'] as $key=>$file) {
            $csv = new \Modules\Ography($file,TRUE);
            // $c1sv->filter_field("file");
            $str="<table>";
            foreach($csv->entries as $entry) {
                $tmp="";
                foreach($entry as $key=>$value) {
                    $tmp .= sprintf("<td class=\"%s\">%s</td>", $key, $value);
                }
                $str .= sprintf("<tr>%s</tr>",$tmp);
            }
            $str.="</table>";
            $primary[$key] = $str;
        }

        foreach($c2['txt'] as $key=>$file) {
            $str = file_get_contents($file);
            $str = self::linkify($str);
            $str = self::get_config_from_content($str);
            $str = $md->text($str);
            $str = sprintf("<div class='post'>%s</div>", $str);
            $secondary[$key] = sprintf("<div class=\"item %s %s\">%s</div>", $page,$key,$str);
        }
        foreach($c2['tpl'] as $key=>$file) {
            $str = file_get_contents($file);
            $str = \Template::instance()->render($file);
            $str = self::linkify($str);
            if(array_key_exists($key,$c2['pic'])) {
                $str = sprintf("%s\n%s", 
                    \Modules\Pictures::makeImageLink($c2['pic'][$key]),
                    $str);
                    unset($c2['pic'][$key]);
            }
            $secondary[$key] = sprintf("<div class=\"item %s %s\">%s</div>", $page ,$key,$str);
        }
        foreach($c2['pic'] as $key=>$file) {
            $secondary[$key] = sprintf("<img src=\"$file\" />");
        }
        foreach($c2['csv'] as $key=>$file) {
            $csv = new \Modules\Ography($file,TRUE);
            // $c2sv->filter_field("file");
            $str="<table>";
            foreach($csv->entries as $entry) {
                $tmp="";
                foreach($entry as $key=>$value) {
                    $tmp .= sprintf("<td class=\"%s\">%s</td>", $key, $value);
                }
                $str .= sprintf("<tr>%s</tr>",$tmp);
            }
            $str.="</table>";
            $secondary[$key] = $str;
        }

        // set template variables
        $f3->set('banner',$banner);
        $f3->set('background',$background);
        $f3->set('content', implode("\n", $primary));
        $f3->set('secondary_content', implode("\n", $secondary));
    }

    ////////////////
    // recursions //
    ////////////////
    function search_up($key,$paths,$ext) {
        $return = "";
        
        if(count($paths) == 2) {
            $current = $paths[0];
            $last_try = $paths[1];
            $ls=scandir($current);
            foreach($ls as $f) {
                if(!strncmp($f,'.',1)) continue; // ignore hidden files
                $ex=explode(".", $f);
                if(in_array(strtolower(end($ex)),$ext)) {
                    if($ex[0]==$key) {
                        $return = $current.$f;
                        break;
                    }
                }
            }
        }
        
        if ($return) {
            return $return;
        } elseif($current == $last_try) {
            return false;
        } else {
            $p = explode('/',$current);
            array_pop($p);
            array_pop($p);
            return self::search_up($key,array(implode("/",$p)."/",$last_try),$ext);
        }
    }




    
    ///////////////////////
    // Utility functions //
    ///////////////////////
    function linkify($string) {
        $pattern = "/\s@(\w+)[=]([\w,]+)\s/";
        $count = 0;
        $new = preg_replace_callback
            ($pattern,
             function($m){
                 $f3 = \Base::instance();
                 return $f3->get('SITE_URL')
                     .$f3->alias($m[1],self::$keyword."=".$m[2])
                     ;},
             $string);
        return $new;
    }
    function get_config_from_content($string) {
      $f3 = \Base::instance();
      $f = 0;
      $pattern = "/#\+(\w+):\s?(.*)/";
      
      $f = preg_match_all($pattern, $string,$matches,PREG_PATTERN_ORDER);
      foreach($matches[0] as $match) {
        $string = str_replace($match,"",$string);
      }
      foreach($matches[1] as $key => $match) {
        $f3->set('content_config_'.$match,$matches[2][$key]);
      }
      return $string;
    }  
    public static function check_folder_for_backgroundimage($folder){
        $EXT=array(
            'pic'=>array( 'jpg', 'jpeg', 'png' ),
            'tpl'=>array( 'html', 'htm', 'tpl' ),
            'txt'=>array( 'txt', 'text', 'md' )
        );
        $ls = scandir($folder);
        $background = false;
        foreach ($ls as $key=>$f) {
            if(!strncmp($f,'.',1)) continue;
            $ex=explode(".", $f);
            $ext=array_pop($ex);
            if(in_array(strtolower($ext), $EXT['pic'])) {
                if($ex[0]=='background') {
                    $background=pic_cache($folder.$f,836);
                    break;
                }
            }
        }
        return $background;
    }
}
