<?php
class Mweborder extends Model
{
    private $access;

    function __construct()
    {
        parent::__construct();

        $this->load->library('session');
        $this->load->library('PasswordHash');
        $this->load->library('Order');
        $this->load->library('Product');

        $access_id = $this->phpsession->get('access_id');

        $query = "SELECT p.weborder_access AS weborder_access, p.rm_access AS rm_access, auth.ctrID AS ctrID, p.is_admin AS is_admin
            FROM cl_hlusers.partner_authenticate auth
            LEFT JOIN cl_hlusers.partner_permissions p ON p.id = auth.permission_id
            WHERE auth.username = '{$access_id}' LIMIT 1";
        $access = $this->db->query($query)->row();

        $this->access = $access;
    }

    function isAdmin()
    {
        return $this->access->is_admin == 1;
    }

    function weborderAccess()
    {
        $access_id = $this->phpsession->get('access_id');

        if ($access_id == '')
            return false;

        return $this->access->weborder_access == 1;
    }

    function loadLoginTemplate()
    {
        $header = array();

        $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url_components = parse_url($url);

        $header['url']      = $url_components['path'];
        $header['error']    = $_SESSION['error'];
        $header['username'] = $_SESSION['username'];

        $this->load->view('weborder/includes/login.php', $header);
    }

    /**
     * Load the html template
     * @param string $temp - The loaded template
     * @param array $resData - The passed data
     * @param string $title - Title of the page
     * @param string $active - The active page in the menu
     * @param bool $needProduct - Need the product.php
     * @return void
     */
    function loadTemplate($temp, $resData, $title, $active = '', $needProduct)
    {
        $header = array();

        $header['title']    = $title;
        $header['access']   = $this->access;
        $header['username'] = $this->phpsession->get('additional_access_id') != '' ? $this->phpsession->get('additional_access_id') : $this->phpsession->get('access_id');
        $header['isAdmin']  = $this->isAdmin();

        if ($header['isAdmin']) {
            $header['partners'] = $this->getPartners();
            $header['url']      = $this->uri->segment(1);

            if ($this->uri->segment(2))
                $header['url'] .= '_' . $this->uri->segment(2);
        }

        if ($active != '')
            $header['active'] = $active;

        $this->load->view('weborder/includes/header.php', $header);
        $this->load->view($temp, $resData);

        if ($needProduct)
            $this->load->view('weborder/product.php');

        $this->load->view('weborder/includes/footer.php');
    }

    function getPartners()
    {
        $query = "SELECT * FROM cl_hlusers.partner_authenticate auth ORDER BY auth.username ";

        return $this->db->query($query)->result();
    }

    function getDistributors()
    {
        $query = "SELECT * FROM cl_hlusers.distributors dist WHERE dist.id != 0 AND ctrID IS NOT NULL ORDER BY dist.order DESC, dist.name ASC";

        return $this->db->query($query)->result();
    }

    /**
     * Get the orders for the selected country.
     * @param string $ctrID - Country ID
     * @return object
     */
    function getOrdersForCountry($ctrID)
    {
        $query = "SELECT * FROM cl_hlusers.o_orders WHERE country = '{$ctrID}' ORDER BY id DESC";

        return $this->db->query($query)->result();
    }

    function getBundle($ctrID)
    {
        $query = "SELECT termek, kategoria, euro, usd
            FROM cl_hlusers.o_products
            WHERE lang = '{$ctrID}' AND seq = 2 LIMIT 2";
        $bundle = $this->db->query($query)->result();

        return $bundle;
    }

    private function getOrder($category)
    {
        $order = "";

        switch ($category) {
            case 'perp':
                $order .= " AND termek NOT LIKE '%Non-Profit%' ORDER BY
                        CASE
                            WHEN type = 8 AND termek NOT LIKE '% next license %' AND termek NOT LIKE '% LIVE %' AND kategoria != 'comp' THEN 1
                            WHEN type = 8 AND termek LIKE '% next license %' AND kategoria != 'comp' THEN 2
                            WHEN type = 8 AND incl_live = 1 THEN 3
                            WHEN kategoria = 'lt' THEN 4
                            WHEN kategoria = 'live' THEN 5
                            WHEN type = 2 AND termek NOT LIKE '%LIVE%' AND termek NOT LIKE '% Upgr. %' THEN 6
                            WHEN type = 2 AND termek LIKE '%LIVE%' THEN 7
                            WHEN type = 2 AND termek LIKE '% Upgr. %' THEN 8
                            WHEN type = 8 AND kategoria = 'comp' THEN 9
                            WHEN type = 4 AND kategoria = 'comp' THEN 10
                            ELSE 11
                        END,
                        termek ASC";
                break;

            case 'upgrade':
                $order .= " ORDER BY
                        CASE
                            WHEN o_type = 7 THEN 1
                            WHEN o_type = 26 THEN 2
                            WHEN o_type = 27 THEN 3
                            WHEN o_type = 20 THEN 4
                            WHEN o_type = 14 THEN 5
                            WHEN o_type = 28 THEN 6
                            WHEN o_type = 29 THEN 7
                            WHEN o_type = 18 THEN 8
                            WHEN o_type = 22 THEN 9
                            WHEN o_type = 25 THEN 10
                            WHEN o_type = 17 THEN 11
                            WHEN o_type = 16 THEN 12
                            WHEN kategoria = 'crossgrade' THEN 13
                            WHEN kategoria = 'floating' THEN 14
                            WHEN kategoria = 'lan' THEN 15
                            ELSE 16
                        END,
                        termek ASC";
                break;

            case 'nonprofit':
                $order .= " AND termek NOT LIKE '%LT or Professional%' ORDER BY termek ASC";
                break;

            case 'subscription':
                $order .= " ORDER BY
                        CASE
                            WHEN type = 8 THEN 1
                            WHEN type = 4 THEN 2
                            WHEN type = 'L' THEN 3
                            ELSE 4
                        END,
                        termek ASC";
                break;

            default:
                $order .= " ORDER BY termek ASC";
                break;
        }

        return $order;
    }

    /**
     * Get the products for the selected category.
     * @param string $category - The product's category
     * @param string $ctrID - Country ID
     * @return object
     */
    function getProducts($category, $ctrID)
    {
        $cat = '';

        switch ($category) {
            case 'perp':
                $cat = "'lt', 'perp', 'live', 'module', 'comp'";
                break;

            case 'subscription':
                $cat = "'subscription'";
                break;

            case 'upgrade':
                $cat = "'upgrade', 'crossgrade', 'floating', 'lan'";
                break;

            case 'modules':
                $cat = "'module'";
                break;

            case 'nonprofit':
                $cat = "'nonp', 'hardlock', 'module'";
                break;

            default:
                $cat = "''";
                break;
        }

        $query = "SELECT * FROM cl_hlusers.o_products WHERE lang = '{$ctrID}' AND kategoria IN ({$cat}) AND seq != 0";

        $query .= $this->getOrder($category);

        return $this->db->query($query)->result();
    }

    /**
     * Get the selected product.
     * @param int $id - Product ID
     * @param string $ctrID - Country ID
     * @return object 
     */
    function getSelectedProduct($id, $ctrID)
    {
        $query      = "SELECT * FROM cl_hlusers.o_products WHERE id = '{$id}'";
        $product    = $this->db->query($query)->row();

        if ($product->akcio != '' && $product->akcio != null && date('Y-m-d') <= $product->ackio_date) {
            $product->price = $product->akcio;
        } else {
            if (substr($ctrID, 0, 2) == '11')
                $product->price = $product->usd;
            else
                $product->price = $product->euro;
        }

        if (strpos($product->termek, "monthly") && $product->kategoria == 'subscription')
            $product->price *= 3;

        return $product;
    }

    /**
     * Get the four latest versions.
     *
     * @return object
     */
    function getTheFourLatestVersions()
    {
        $query = "SELECT * FROM cl_hlusers.p_versions WHERE verID < (SELECT verID FROM cl_hlusers.p_versions WHERE currentVer = 0 OR currentVer = 1) ORDER BY verID DESC";

        if (Product::$generatePrevProgram)
            $query .= " LIMIT 1, 4";
        else
            $query .= " LIMIT 0, 4";

        return $this->db->query($query)->result();
    }

    /**
     * Get the empty hardlock numbers.
     *
     * @return object
     */
    function getHardlockKeys($ctrID)
    {
        $query = "SELECT hlNum FROM cl_hlusers.hardlock WHERE hlNum LIKE '{$ctrID}%' AND hlStat = 0 AND hlLan = 0";

        return $this->db->query($query)->result();
    }

    /**
     * Get the actual currency.
     * @param string $ctrID - Country ID
     * @return string
     */
    function getCurrency($ctrID)
    {
        if ($ctrID == '11')
            return '$';
        else
            return '€';
    }

    /**
     * Check if the product needs a live checkbox
     * @param string $category - The product's category
     * @param string $ctrID - Country ID
     * @param string $prod_name - Product Name
     * @return bool
     */
    function needLiveChkbox($category, $ctrID, $prod_name, $params)
    {
        if (isset($params->number_of_programs) && $params->number_of_programs != '' && $params->number_of_programs > 1)
            return false;

        if (($ctrID != "60" && $ctrID != "65" && $ctrID != "37" && $ctrID != "43" && $ctrID != "48" && $ctrID != "55") || strpos($prod_name, 'LIVE'))
            return false;

        if ($category == 'hardlock' || $category == 'live' || $category == 'nonp' || $category == 'module' || $category == 'subscription' || $category == 'lan')
            return false;

        if (($ctrID == "60" || $ctrID == "65") && $category != 'crossgrade')
            return false;

        return true;
    }

    function login($username, $password)
    {
        $user = $this->db->query("SELECT username, ctrID, password FROM cl_hlusers.partner_authenticate WHERE username = '{$username}'")->row();

        if (empty($user))
            return false;

        $phpass = new PasswordHash(10, true);
        $ok     = $phpass->CheckPassword($password, $user->password);

        if (!$ok)
            return false;

        return $user;
    }

    function order($ctrID, $data)
    {
        $order = new Order($data, $ctrID);

        $response = $order->orderProduct();

        return $response;
    }

    function getInstalments($ctrID, $productName)
    {
        $inst = '';

        if (strpos($productName, "discount package"))
            return $inst;

        switch ($ctrID) {
            case '43':
                $inst = 'Instalments: 3 Period: monthly';
                break;

            case '380':
                $inst = 'Instalments: 3 Period: monthly';
                break;

                /*case '44':
                if (strstr($productName, "Professional") || strstr($productName, "Prof."))
                    $inst = 'Instalments: 4 Period: monthly';
                break;*/

            case '42':
                if (!strpos($productName, "Interior"))
                    $inst = 'Instalments: 6x month payments';
                break;

            case '39':
                $inst = 'Instalments: 2 Period: yearly';
                break;

            case '37':
                $inst = 'Instalments: 3 Period: monthly';
                break;

            case '48':
                if (strpos($productName, "Professional") !== false)
                    $inst = 'Instalments: 4 Period: monthly';
                break;

            default:
                break;
        }

        return $inst;
    }

    function getModules($ctrID, $prodName, $category)
    {
        if ($category == 'nonp' || $category == 'module')
            return false;

        if (($category == 'perp' || $category == 'upgrade' || $category == 'lan' || $category == 'subscription') && (strpos($prodName, "Professional") !== false || strpos($prodName, "LIVE") !== false))
            return false;

        if ($category != 'lt' && !strstr($prodName, "Professional") && !strstr($prodName, "Prof.") && $category != 'subscription')
            return false;

        if ($category == 'subscription' && (strpos($prodName, "LIVE") || strpos($prodName, "INTERIOR")))
            return false;

        if ($category == 'subscription')
            return Product::getMEPmoduleForSubscription($prodName, $ctrID);

        $module = new stdClass();

        $product = $this->db->query("SELECT termek, euro, usd, akcio, ackio_date, module_id FROM cl_hlusers.o_products WHERE lang = '{$ctrID}' AND kategoria = 'module' AND termek LIKE 'MEP%'")->row();

        if ($product->akcio != '' && $product->akcio != null && date('Y-m-d') <= $product->ackio_date) {
            $module->price = $product->akcio;
        } else {
            if (substr($ctrID, 0, 2) == '11')
                $module->price = $product->usd;
            else
                $module->price = $product->euro;
        }

        $module->name   = $product->termek;
        $module->mdCode = $product->module_id;

        return $module;
    }

    function canOrder($ctrID)
    {
        $query = "SELECT COUNT(id) AS product_count FROM cl_hlusers.o_products WHERE lang = '{$ctrID}' AND seq > 0 LIMIT 1";
        $products = $this->db->query($query)->row();

        return $products->product_count > 0;
    }

    function getCtrID($username)
    {
        $user = $this->db->query("SELECT ctrID FROM cl_hlusers.partner_authenticate WHERE username = '{$username}'")->row();

        return $user->ctrID;
    }

    function getPartnerById($id)
    {
        $query = "SELECT * FROM cl_hlusers.partner_authenticate WHERE id = {$id} LIMIT 1";

        return $this->db->query($query)->row();
    }

    private function getPermissionId($permission)
    {
        $query = "SELECT id 
            FROM cl_hlusers.partner_permissions
            WHERE rm_access = {$permission->rm_access} AND weborder_access = {$permission->weborder_access} AND is_admin = {$permission->is_admin}";

        return (int)$this->db->query($query)->row()->id;
    }

    function generateRandomString($length = 22)
    {
        return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$', ceil($length / strlen($x)))), 1, $length);
    }

    private function getDefaultTemplateName($i)
    {
        $templateName = '';

        switch ($i) {
            case 0:
                $templateName = '2022 Trial';
                break;

            case 1:
                $templateName = '2022 Commercial';
                break;
            case 2:
                $templateName = '2022 LIVE';
                break;

            default:
                break;
        }

        return $templateName;
    }

    private function createDefaultTemplate($authID)
    {
        $db_template = array();

        for ($i = 0; $i < 3; $i++) {
            $templateID     = $this->generateRandomString();
            $templateName   = $this->getDefaultTemplateName($i);
            $productID      = $i == 0 || $i == 1 ? 1 : 2;
            $prType         = $i == 0 || $i == 1 ? ["8", "4"] : [];
            $ctrCode        = $i == 0 ? "trial" : "comm";

            $db_template[$templateID]               = new stdClass();
            $db_template[$templateID]->name         = $templateName;
            $db_template[$templateID]->product      = $productID;
            $db_template[$templateID]->types        = (array)$prType;
            $db_template[$templateID]->versions     = (array)"39";
            $db_template[$templateID]->country_code = (array)$ctrCode;
            $db_template[$templateID]->interval     = "0";
            $db_template[$templateID]->chart_type   = 'bar';
        }

        $json_string = '{"templates":' . json_encode($db_template, JSON_UNESCAPED_UNICODE) . '}';

        $new_template               = new stdClass();
        $new_template->partner_id   = $authID;
        $new_template->template     = $json_string;


        $this->db->insert("cl_hlusers.partner_templates", $new_template);

        return true;
    }

    private function userExist($username)
    {
        $query = "SELECT * FROM cl_hlusers.partner_authenticate WHERE username = '{$username}'";
        $user = $this->db->query($query)->row();

        return !empty($user);
    }

    function createUser($user)
    {
        $result = array();

        if ($this->userExist($user->username)) {
            $result['success']  = false;
            $result['error']    = 'This username already exists.';

            return $result;
        }

        $permission                     = new stdClass();
        $permission->rm_access          = $user->rm_access == 'on' || $user->admin == 'on' ? 1 : 0;
        $permission->weborder_access    = $user->weborder == 'on' || $user->admin == 'on' ? 1 : 0;
        $permission->is_admin           = $user->admin == 'on' ? 1 : 0;

        $permissionID = $this->getPermissionId($permission);

        $query = "SELECT auth.name AS ctrName, auth.prefix AS prefix, auth.flag AS flag
            FROM cl_hlusers.partner_authenticate auth
            WHERE auth.ctrID = {$user->country} LIMIT 1";
        $ctr = $this->db->query($query)->row();

        $phpass     = new PasswordHash(10, true);
        $password   = $phpass->HashPassword($user->password);

        $auth                   = new stdClass();
        $auth->username         = $user->username;
        $auth->password         = $password;
        $auth->name             = $ctr->ctrName;
        $auth->prefix           = $ctr->prefix;
        $auth->flag             = $ctr->flag;
        $auth->profile_email    = $user->email;
        $auth->ctrID            = $user->country;
        $auth->permission_id    = $permissionID;

        $this->db->insert("cl_hlusers.partner_authenticate", $auth);
        $authID = $this->db->insert_id();

        $result['success'] = $this->createDefaultTemplate($authID);
        $result['authID'] = $authID;

        return $result;
    }
}
