<?php

spl_autoload_register(function ($class_name) {
    $path = explode('\\', $class_name);
    $fileName = $path[sizeof($path) - 1];

    $path[sizeof($path) - 1] = '';

    //$path = strtolower(DIR_ROOT. implode(DIRECTORY_SEPARATOR, $path));
    $path = DIR_ROOT . strtolower(implode(DIRECTORY_SEPARATOR, $path));

    if (is_file($path . $fileName . '.php')) {
        return include $path . $fileName . '.php';
    }

    if (is_file(strtolower($path . $fileName . '.php'))) {
        return include strtolower($path . $fileName . '.php');
    }

    @include $path . $fileName . '.php';
});

function is_ajax_request()
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
        return true;
    } else if (isset($_SERVER['HTTP_REQUEST_TYPE']) && $_SERVER['HTTP_REQUEST_TYPE'] == 'fetch') {
        return true;
    } else {
        return false;
    }
}

global $_LANG;
$_LANG = array();

class Lang
{

    public static function getStrings($module = '', $lang = null)
    {
        global $_LANG;
        if ($lang == null) {
            $lang = APP_LANG;
        }
        if (isset($_LANG[$lang][$module])) {
            return $_LANG[$lang][$module];
        }
        return $module;
    }

    public static function getString($string = '', $module = null, $lang = null)
    {
        global $_LANG;
        if ($lang == null) {
            $lang = APP_LANG;
        }

        if (isset($_LANG[$lang][$string]) && is_string($_LANG[$lang][$string])) {
            return $_LANG[$lang][$string];
        }

        if (isset($_LANG[$lang][$module][$string])) {
            return $_LANG[$lang][$module][$string];
        }

        return $string;
    }

    public static function buildStrings()
    {
        global $_LANG;

        if (isset($_SESSION['cache']['strings']) && CACHE_LANG) {
            $_LANG = $_SESSION['cache']['strings'];
            return;
        }

        $rdi = new RecursiveDirectoryIterator(DIR_APP);
        foreach (new RecursiveIteratorIterator($rdi) as $file) {
            if (preg_match("/lang\/.*\.php$/", $file)) {
                $included_lang = explode('/', $file);
                $included_lang = end($included_lang);
                $included_lang = str_replace('.php', '', $included_lang);
                $lang = array();
                include_once $file;
                $_LANG[$included_lang][array_keys($lang)[0]] = array_values($lang)[0];
            }
        }
    }
}

abstract class Singleton
{
    private static $instance;

    private function __construct()
    {
    }

    private static function newObj()
    {
        if (!isset(self::$instance)) {
            $class = get_called_class();
            self::$instance = new $class;
        }
        return self::$instance;
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            return self::newObj();
        }
        return self::$instance;
    }
}

use App\Core\Datatables\Datatables as Datatables;
use ORM\DBInstance;

abstract class DefaultController
{

    protected $_class;
    protected $_baseUrl;

    function table()
    {
        if (isset($_GET['selective']) && $_GET['selective'] == 'true') {
            echo Datatables::getTable($this->_class, $this->_baseUrl);
        } else {
            echo Datatables::getTable($this->_class, $this->_baseUrl, false);
        }
    }

    function searchTable()
    {
        $records = [];
        $total = 0;

        try {
            if ($_POST['search']['value'] != '') {
                $search = [];
                foreach ($this->_class::_searchable as $searchable) {
                    $search[$searchable] = ['OR like', $_POST['search']['value']];
                }
                $records = $this->_class::findMany($search, $this->_class::_listable)->get(true);
            } else {
                $records = $this->_class::findAll($this->_class::_listable, ['limit' => $_POST['length'], 'offset' => $_POST['start']])->get();
            }
            $total = DBInstance::queryOne("SELECT count(*) as count FROM {" . $this->_class::_tableName .  '}')->count;
        } catch (Exception $e) {
            if (APP_STATUS != 'production') {
                for ($i = $_POST['start']; $i <= $_POST['length'] + $_POST['start']; $i++) {
                    $line = new stdClass();
                    $line->id = $i;
                    $line->name = md5($i);
                    $records[] = $line;
                }
                $total = 10000;
            }
        }

        if (!is_array($records)) {
            $records = [$records];
        }

        foreach ($records as $record) {
            if ($_GET['selective'] == 'true') {
                $record->id = Datatables::getActionMenu($record->id, $this->_baseUrl);
            } else {
                $record->id = Datatables::getSelectMenu($record->id);
            }
        }

        \RR\Response::json([
            'draw' => $_POST['draw'],
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $records
        ])->send();
    }
}

/**
 * Request obtainers helpers
 */
function request($param, $default = false)
{
    if (is_string($param)) {
        return requestString($param, $default = false);
    }

    if (is_array($param)) {
        return requestArray($param, $default);
    }
}

function requestString($param, $default = false)
{
    if (isset($_POST[$param])) {
        return $_POST[$param];
    }

    if (isset($_GET[$param])) {
        return $_GET[$param];
    }

    return $default;
}

function requestArray($params, $default = false) : array
{

    $return = [];

    foreach ($params as $param) {
        $return[] = requestString($param, $default);
    }

    return $return;
}

/**
 * Development helpers
 */
function dd($param, $die = true) : void
{
    if ($param) {
        echo '<pre>';
        var_dump($param);
    }
    if ($die) {
        die;
    }
}

function ddd($param, $die = true) : void
{
    if ($param) {
        error_log(print_r($param, true));
    }
    if ($die) {
        die;
    }
}
/**
 * Summary of icon
 * @return void
 */
function icon($icon) : String
{
    return "<i class='fa fa-$icon'></i>";
}
