<?php

/*
 * Copyright (c) 2018 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 *  contact@earworks.co.id
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Base_Loader
 *
 * @author Fajar Dwi Rianto <fajar@earworks.co.id>
 * @since 1.0
 */
class Base_Loader extends CI_Loader {

    /**
     * Setting layout file
     * @var string
     */
    public $template = 'main';
    public $template_folder = '';
    public $title = null;

    /**
     * CSS for rendering
     * @var array
     */
    private $_css = array();

    /**
     * JS for rendering
     * @var array 
     */
    private $_js = array();

    /**
     * Meta Tag for rendering
     * @var array 
     */
    private $_meta = array();

    /**
     * Breadcrumbs maps
     * @var array
     */
    private $_maps = array();

    public function __construct() {
        parent::__construct();
        if (!is_dir(LAYOUT) OR ! is_file(LAYOUT . $this->template . '.php')) {
            show_error('Cannot find the layout file or directory : ' . LAYOUT . $this->template . '.php');
        }
    }

    public function view($view, $vars = array(), $return = FALSE) {

        if (APPLICATION == 'backoffice') {
            $this->_backend_view($view, $vars, $return);
        } else {
            $this->_frontend_view($view, $vars, $return);
        }
    }

    public function partials($view, $vars = array()) {
        if (APPLICATION == 'backoffice') {
            return parent::view($this->template_folder . '/' . $view, $vars, TRUE);
        } else {
            return parent::view($view, $vars, TRUE);
        }
    }

    private function _frontend_view($view, $vars = array()) {
        $title = (isset($vars['title']) && !empty($vars['title'])) ?
                $vars['title'] : ucwords(strtolower(CI_NAME));

        unset($vars['title']);

        $content = parent::view($view, $vars, TRUE);
        
        if ($this->title) {
            $title = $this->title;
        };

        $web_parts = array(
            'render_css' => implode("\n", $this->_css) . "\n",
            'render_js' => implode("\n", $this->_js) . "\n",
            'render_meta' => implode("\n", $this->_meta) . "\n",
            'title' => $title,
            'content' => $content
        );
        parent::view('layouts/' . $this->template, $web_parts);
    }

    private function _backend_view($view, $vars = array(), $return = FALSE) {
        $title = (isset($vars['title']) && !empty($vars['title'])) ?
                $vars['title'] : ucwords(strtolower(CI_NAME));
        unset($vars['title']);

        $content = parent::view($this->template_folder . '/' . $view, $vars, TRUE);

        if ($this->title) {
            $title = $this->title;
        };

        $web_parts = array(
            'render_css' => implode("\n", $this->_css) . "\n",
            'render_js' => implode("\n", $this->_js) . "\n",
            'render_meta' => implode("\n", $this->_meta) . "\n",
            'render_maps' => $this->_maps,
            'title' => $title,
            'content' => $content
        );
        parent::view($this->template_folder . '/layouts/' . $this->template, $web_parts);
    }

    /**
     * Dynamically include javascript in the template
     * 
     * NOTE: This function does NOT check for existence of .js file
     *
     * @access  public
     * @param   string   script to import or embed
     * @param   string  'import' to load external file or 'embed' to add as-is
     * @param   boolean  TRUE to use 'defer' attribute, FALSE to exclude it
     * @return  TRUE on success, FALSE otherwise
     */
    public function add_js($script, $type = 'import', $defer = FALSE) {
        $success = TRUE;
        $js = NULL;

        switch ($type) {
            case 'import':
                if (strpos($script, 'http') === false) {
                    $filepath = base_url() . $script;
                } else {
                    $filepath = $script;
                }
                $js = '<script type="text/javascript" src="' . $filepath . '"';
                if ($defer) {
                    $js .= ' defer="defer"';
                }
                $js .= "></script>";
                break;

            case 'embed':
                $js = '<script type="text/javascript"';
                if ($defer) {
                    $js .= ' defer="defer"';
                }
                $js .= ">";
                $js .= $script;
                $js .= '</script>';
                break;

            default:
                $success = FALSE;
                break;
        }

        // Add to js array if it doesn't already exist
        if ($js != NULL && !in_array($js, $this->_js)) {
            $this->_js[] = $js;
        }

        return $success;
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically include CSS in the template
     * 
     * NOTE: This function does NOT check for existence of .css file
     *
     * @access  public
     * @param   string   CSS file to link, import or embed
     * @param   string  'link', 'import' or 'embed'
     * @param   string  media attribute to use with 'link' type only, FALSE for none
     * @return  TRUE on success, FALSE otherwise
     */
    public function add_css($style, $type = 'link', $media = FALSE) {
        $success = TRUE;
        $css = NULL;
        if (strpos($style, 'http') === false) {
            $filepath = base_url() . $style;
        } else {
            $filepath = $style;
        }


        switch ($type) {
            case 'link':

                $css = '<link type="text/css" rel="stylesheet" href="' . $filepath . '"';
                if ($media) {
                    $css .= ' media="' . $media . '"';
                }
                $css .= ' />';
                break;

            case 'import':
                $css = '<style type="text/css">@import url(' . $filepath . ');</style>';
                break;

            case 'embed':
                $css = '<style type="text/css">';
                $css .= $style;
                $css .= '</style>';
                break;

            default:
                $success = FALSE;
                break;
        }

        // Add to js array if it doesn't already exist
        if ($css != NULL && !in_array($css, $this->_css)) {
            $this->_css[] = $css;
        }

        return $success;
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically include meta tags in the template
     * 
     * @param string $key meta name
     * @param string $value meta content
     * @return bool
     */
    public function add_meta($key, $val) {
        $success = FALSE;
        $meta = '<meta name="' . $key . '" content="' . $val . '" />';

        if (!in_array($meta, $this->_meta)) {
            $this->_meta[] = $meta;
            $success = TRUE;
        }

        return $success;
    }

    /**
     * Dynamically include breadcrumbs map in the template
     * 
     * @param string $title title to be display
     * @param string $url url to previews page
     * @return bool
     */
    public function add_map($title, $url = null) {
        $this->_maps[] = array(
            'title' => $title,
            'url' => $url
        );
        return true;
    }

}
