<?php
/**
 * Created by PhpStorm.
 * User: Kavand
 * Date: 3/14/2018
 * Time: 9:16 PM
 */

class CoreSystem
{

    protected $DAL = null;
    protected $CoreName = "";

    public function CoreSystem($core = "سرویس کاشان کارت")
    {
        require_once 'DAL/DAL.php';
        $this->DAL = new DAL("constant.php");
        $this->CoreName = $core;
        error_reporting(1);
        return $this;
    }

    /*    public function __construct($core = "سرویس کاشان کارت")
        {
            require_once 'DAL/DAL.php';
            $this->DAL = new DAL("constant.php");
            $this->CoreName = $core;
            error_reporting(1);
            return $this;
        }
    */
    public function Title()
    {
        return $this->CoreName;
    }


    public function TitleSite()
    {
        return "<span class='bold h3 fBTitrBold'>{$this->CoreName}</span>";
    }

    public function publicLoadPlugin(array $plugin)
    {
        $query = [];
        foreach ($plugin as $p)
            $query[] = "SELECT * FROM system_plugin_list WHERE (pName='{$p}')";
        $html = array(
            'meta' => '',
            'fav' => '',
            'css' => '',
            'js' => ''
        );
        foreach ($query as $q) {
            $select = $this->DAL->Select($q);
            if ($select) {
                for ($i = 0; $i < count($select); $i += 1) {
                    $row = $select[$i];
                    $local_ling = '';
                    if ($row['pPosition'] == 'global') {
                        $local_ling = '';
                    }
                    if ($row['pPosition'] == 'local') {
                        $local_ling = 'ResourcesHolder/resource/';
                    }
                    switch ($row['pType']) {
                        case 'css':
                            $html['css'] .= "\n\t" . '<link href="' . $local_ling . $row['pUrl'] . '" ' . $row['pSpecialParameter'] . '/>';
                            break;
                        case 'fav':
                            $html['fav'] .= "\n\t" . '<link  ' . $row['pSpecialParameter'] . '/>';
                            break;
                        case 'meta':
                            $html['meta'] .= "\n\t" . '<meta ' . $row['pSpecialParameter'] . '/>';
                            break;
                        case 'js':
                            $html['js'] .= "\n\t" . '<script src="' . $local_ling . $row['pUrl'] . '" ' . $row['pSpecialParameter'] . "></script>";
                            break;
                        default:
                            break;
                    }
                }

            }
        }
        foreach ($html as $h)
            echo $h . "\n";
    }


    /**
     * @param array $content
     */
    public function content(array $content)
    {
        array_reverse($content);
        $base = 'ResourcesHolder/resource/php/content_cms/';
        $end = '.php';
        foreach ($content as $c) {
            try {
                require_once $base . $c . $end;
            } catch (Exception $e) {
                echo $e;
            }
        }
    }

    public function Login()
    {
        session_start();
        if (isset($_COOKIE["user"])) {
            $uniqID = $_SESSION[$_COOKIE["user"]]['uniqid'];
            if (isset($_SESSION[$_COOKIE["user"]][$uniqID]['login']) and
                isset($_SESSION[$_COOKIE["user"]][$uniqID]['access-item']) and
                isset($_SESSION[$_COOKIE["user"]][$uniqID]['access-id']) and
                isset($_SESSION[$_COOKIE["user"]][$uniqID]['access-type']) and
                $_SESSION[$_COOKIE["user"]][$uniqID]['login']
            ) {
                return true;
            }
        }
        return false;
    }


    public function UserName()
    {
        session_start();
        $uniqID = $_SESSION[$_COOKIE["user"]]['uniqid'];
        $id = $_SESSION[$_COOKIE["user"]][$uniqID]['access-id'];
        if (isset($id)) {
            $query = "SELECT system_user_profile.uFirstName, system_user_profile.uLastName FROM system_user_profile WHERE uID='{$id}';";
            $select[] = $this->DAL->Select($query);
            $query = "SELECT system_user_access.aua_item FROM system_user_access WHERE aua_id='{$id}'";
            $select[] = $this->DAL->Select($query);
            if ($select[0] && $select[1]) {
                echo "<span class='fBTitrBold'>" . $select[0][0]['uFirstName'] . " " . $select[0][0]['uLastName'] . "</span>";
            } else {
                echo "404";
            }
        } else {
            echo '404:1';
        }
    }


    public function GetType()
    {
        //limit or direct
        session_start();
        return (isset($_SESSION[$_COOKIE["user"]][$_SESSION[$_COOKIE["user"]]['uniqid']]['access-type']) ? $_SESSION[$_COOKIE["user"]][$_SESSION[$_COOKIE["user"]]['uniqid']]['access-type'] : "not-set");
    }

    public function GetUser()
    {
        return (isset($_COOKIE["user"]) ? $_COOKIE["user"] : "not-set");
    }


    private function MenuItem($mod, $text, $icon, $active = false)
    {
        $html = '';
        $html .= '<li class=" ' . ($active ? "active" : "") . ' item-menu">';
        $html .= '<a href="javascript:void(0);" target-mod="' . $mod . '">';
        if (strlen($icon) > 0) {
            $html .= '<i class="material-icons">' . $icon . '</i>';
        }
        $html .= '<span class="fBTitrBold">' . $text . '</span>';
        $html .= '</a>';
        $html .= '</li>';
        return $html;
    }

    public function UserAccess()
    {
        session_start();
        $return = array();
        $uniqID = $_SESSION[$_COOKIE["user"]]['uniqid'];
        if (isset($uniqID)) {
            $item = $_SESSION[$_COOKIE["user"]][$uniqID]['access-item'];
            $type = $_SESSION[$_COOKIE["user"]][$uniqID]['access-type'];
            if (isset($item) and isset($type)) {

                $add = '';
                $fullAccess = false;
                if (strlen($item) > 0) {
                    $add = '';
                    if ($item == "*") {
                        $add = '';
                        $fullAccess = true;
                    } else {
                        $array = explode(",", $item);
                        if (count($array) > 0) {
                            $add .= 'WHERE';
                            for ($i = 0; $i < count($array); $i += 1) {
                                if ($i > 0) $add .= 'OR';
                                $quest = str_replace(" ", "", $array[$i]);
                                $add .= " (panelCode='{$quest}') ";
                            }
                        } else {
                            $add = " WHERE (panelCode='{$array}')";
                        }
                    }
                } else {
                    $add = 'WHERE panelCode="page-404"';
                }
                if (strlen($add) === 0)
                    $add .= "WHERE `panelType`='direct'";

                $select = $this->DAL->Select("SELECT * FROM system_user_panel " . $add . "  ORDER BY `panelIndex`");
                $get = '';
                if (isset($_GET['page']) AND strlen($_GET['page']) > 0)
                    foreach ($select as $item) {
                        if ($item['panelCode'] === $_GET['page']) {
                            $get = $_GET['page'];
                        }
                    }
                if ($select) {
                    $active = true;
                    if (strlen($get) > 0)
                        $active = false;
                    for ($i = 0; $i < count($select); $i += 1) {
                        $row = $select[$i];
                        if ($fullAccess) {
                            if ($row['panelCode'] !== "page-404") {
                                $return[] = $this->MenuItem(
                                    $row['panelCode'],
                                    $row['panelName'],
                                    $row['panelIcon'],
                                    ($active ? $active : $row['panelCode'] === $get)
                                );
                                $active = false;
                            }
                        } else {
                            $return[] = $this->MenuItem(
                                $row['panelCode'],
                                $row['panelName'],
                                $row['panelIcon'],
                                ($active ? $active : $row['panelCode'] === $get)
                            );
                            $active = false;
                        }
                    }
                }
            }
        }
        return $return;
    }

    public function checkState()
    {
        return preg_match("/(android-app|android-application|telegram-bot)/i", $_SERVER['HTTP_USER_AGENT']) OR (@$_REQUEST['developer'] == "true");
    }

    public function checkStateKey($key)
    {
        return preg_match("/($key)/i", $_SERVER['HTTP_USER_AGENT']);
    }

    public function getState()
    {
        return $_SERVER['HTTP_USER_AGENT'];
    }


    public function CheckAllDataInArray(array $checkedData, $object)
    {
        foreach ($checkedData as $item)
            if (!isset($object[$item]))
                return false;
        return true;
    }

    public function PageRequest()
    {
        $state = (isset($_REQUEST['page-code']) AND isset($_REQUEST['page-id']));
        if ($state) {
            $code = $_REQUEST['page-code'];
            $id = $_REQUEST['page-id'];
            $panel = $this->DAL->Select("SELECT `ID` FROM `system_user_panel` WHERE `panelCode`='{$code}' AND `ID`='{$id}' AND `panelExtend`=true ");
            if ($panel AND count($panel) === 1) {
                return true;
            }
        }

        return false;
    }

    public function ProcessPage()
    {
        $code = $_REQUEST['page-code'];
        $id = $_REQUEST['page-id'];
        echo $this->http_get_contents("http://android.kashancard.digihelp.net/ResourcesHolder/core/index.php?request=proxy&action=$code");
    }

    public function http_get_contents($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}