<?php

/**
 * Created by PhpStorm.
 * User: MainUser
 * Date: 09.07.2016
 * Time: 17:12
 */
class Shop extends AccountModule
{
    public $Config;
    public function __construct()
    {
        parent::__construct();
        //$this->Config = file_get_contents("configs/modules/DB_" . $_SESSION['user_db'] . "/Shop.json");
        $this->Config = App::$Configs->mod_Shop;
    }

    public function Buy($ItemID)
    {
        if($this->AccountOnline)
        {
            return false;
        }
        $Item = $this->Config['Items'][$ItemID];

        $FinalArray = array();
        $Price = $Item['StartPrice'];

        if (property_exists(App::$Post, 'level') && App::$Post->level >= 0 && App::$Post->level <= $Item['MaxLevel']){
            $FinalArray['Level'] = App::$Post->level;
            $Price += App::$Post->level * $this->Config['Price']['Level'];
        } else {
            Messages::Add('fail_buy');
            Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy in level", 'Modules.log');
            return false;
        }
        //--Option(Addition)-----------------------------
        if (property_exists(App::$Post, 'option') && App::$Post->option >= 0 && App::$Post->option <= $Item['MaxAddition']){
            $FinalArray['Addition'] = App::$Post->option;
            $Price += App::$Post->option * $this->Config['Price']['Option'];
        } else {
            Messages::Add('fail_buy');
            Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy in add(opt)", 'Modules.log');
            return false;
        }
        //--Luck-----------------------------
        if (property_exists(App::$Post, 'luck') && $Item['Luck']){
            $FinalArray['Luck'] = 1;
            $Price += $this->Config['Price']['Luck'];
        } else {
            $FinalArray['Luck'] = 0;

        }
        //--Skill-----------------------------
        if (property_exists(App::$Post, 'skill') && $Item['Skill']){
            $FinalArray['Skill'] = 1;
            $Price += $this->Config['Price']['Skill'];
        } else {
            $FinalArray['Skill'] = 0;
        }
        //--Ancient-----------------------------
        if (property_exists(App::$Post, 'select_anc')){
            if (App::$Post->select_anc == 5 && $Item['Ancient1'] != ''){
                $FinalArray['Ancient'] = '05';
                $Price += $this->Config['Price']['Ancient'];
            } elseif (App::$Post->select_anc == 10 && $Item['Ancient2'] != ''){
                $FinalArray['Ancient'] = '10';
                $Price += $this->Config['Price']['Ancient'];
            } else {
                $FinalArray['Ancient'] = '00';
            }

        } elseif ($Item['Ancient1'] != 0 || $Item['Ancient2'] != 0) {
            Messages::Add('fail_buy');
            Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy in ancient", 'Modules.log');
            return false;
        } else {
            $FinalArray['Ancient'] = "00";
        }
        //--Excellent-----------------------------
        $CountExc = 0;
        $FinalArray['Excellent'] = 0;
        if (App::$Post->exc1){ $CountExc++; $FinalArray['Excellent'] += 1;}
        if (App::$Post->exc2){ $CountExc++; $FinalArray['Excellent'] += 2;}
        if (App::$Post->exc3){ $CountExc++; $FinalArray['Excellent'] += 4;}
        if (App::$Post->exc4){ $CountExc++; $FinalArray['Excellent'] += 8;}
        if (App::$Post->exc5){ $CountExc++; $FinalArray['Excellent'] += 16;}
        if (App::$Post->exc6){ $CountExc++; $FinalArray['Excellent'] += 32;}

        if ($CountExc > $Item['MaxExcellent']){
            Messages::Add('fail_buy_max_excellent');
            Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy in excellent", 'Modules.log');
            return false;
        } else {
            //$FinalArray['Excellent'] = App::$Post->exc1 + App::$Post->exc2 + App::$Post->exc3 + App::$Post->exc4 + App::$Post->exc5 + App::$Post->exc6;
            $Price += $CountExc * $this->Config['Price']['Excellent'];
        }

        //--Harmony-----------------------------
        if (property_exists(App::$Post, 'select_joh') && property_exists(App::$Post, 'select_joh_value') && App::$Post->select_joh && App::$Post->select_joh_value){
            $FinalArray['Harmony'] = dechex(App::$Post->select_joh).dechex(App::$Post->select_joh_value);
            $Price += $this->Config['Price']['Harmony'] + App::$Post->select_joh_value * $this->Config['Price']['HarmonyLevel'];
        } else {
            $FinalArray['Harmony'] = '00';
        }

        if ($Price > 0 && ValuteManager::Check($this->Config['MainValute'], $Price)) {
            $ItemClass = new Item();
            $ItemClass->LoadItemBase();
            App::$DBs[$_SESSION['user_db']]->simple_query("declare @it varbinary(1920); set @it=(select [Items] from [warehouse] where [AccountID]='".$_SESSION['login']."'); print @it");
            $inv_items = mssql_get_last_message();
            $inv_items = substr($inv_items,2);

            $col_i = strlen($inv_items)/32;
            $str =0;
            if (round($col_i) == 0) {
                return false;
            }
            $RewardItem = $ItemClass->CreateItem($Item['Type'], $Item['Index'], $FinalArray['Level'], $FinalArray['Skill'], $FinalArray['Luck'], $FinalArray['Addition'], $FinalArray['Excellent'],'00','00','00','00','00', '0', $FinalArray['Ancient'], $FinalArray['Harmony']);
            $itemo = $ItemClass->GetItemInfo($RewardItem);
            if ($itemo == false){
                Messages::Add('fail_buy_create_item');
                Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy in create item", 'Modules.log');
                return false;
            }
            $SmartSearch = $ItemClass->SmartSearch($inv_items,$itemo['X'],$itemo['Y']);
            if($SmartSearch != -1){

                $returnItem = substr_replace($inv_items,$RewardItem,($SmartSearch*32),32);

                ValuteManager::Take($this->Config['MainValute'], $Price);
                if(App::$DBs[$_SESSION['user_db']]->simple_query('UPDATE warehouse SET Items= 0x'.$returnItem.' WHERE AccountID = \''.($_SESSION["login"]).'\'')){
                    //INSERT INTO [Web_Shop]([memb___id],[item],[price],[time]) VALUES ('$Username','$NewItem','$ItemPrice','$BuyTime');
                    //date('d.m.Y H:i');
                    App::$DBs[$_SESSION['user_db']]->insert('ETWShop', array(
                        'memb___id' => $_SESSION['login'],
                        'item' => $RewardItem,
                        'price' => $Price,
                        'time' => date('d.m.Y H:i')
                    ));
                    Messages::Add('Success buy '. $itemo['Name']);
                    Logs::WriteLog("Account: {$_SESSION['login']} Success buy item {$itemo['Name']}, ItemID = {$itemo['Name']}}",'modules.log');
                    return true;
                }
                Logs::WriteLog("Account: {$_SESSION['login']} Fail to buy item {$itemo['Name']}, ItemID = {$itemo['Name']}}",'modules.log');
                Messages::Add('Donate fail');
                return false;
            }

        } else {
            //Messages::Add('fail_buy_need_money');
            Logs::WriteLog("Module: [Shop], Account [{$_SESSION['login']}]. Fail buy need money", 'Modules.log');
            return false;
        }







        //echo $Price;
        //$ItemClass->CreateItem($Item['Type']);
    }
    public function GetReturnList()
    {
        $ItemClass = new Item();
        $ItemClass->LoadItemBase();
        $List = App::$DBs[$_SESSION['user_db']]->select()->from('ETWShop')->where('memb___id', $_SESSION['login'])->get()->result_array();
        for($i=0; $i < count($List); $i++) {
            $List[$i]['item'] = $ItemClass->GetItemInfo($List[$i]['item']);
        }
        return $List;
    }
    public static function MainConfig($Db)
    {
        $Config = file_get_contents("configs/modules/DB_" . $Db . "/Shop.json");
        $Config = json_decode($Config,true);
        if (property_exists(App::$Post,'Enable')) {
            $Config['Enable'] = true;
        }
        else {
            $Config['Enable'] = false;
        }
        if (property_exists(App::$Post,'main_valute') && App::$Post->main_valute != '')
            $Config['MainValute'] = App::$Post->main_valute;
        else
            $Config['MainValute'] = 0;
        if (property_exists(App::$Post,'return_proc') && App::$Post->return_proc != '')
            $Config['ReturnProcent'] = App::$Post->return_proc;
        else
            $Config['ReturnProcent'] = 0;
        if (property_exists(App::$Post,'opt_luck') && App::$Post->opt_luck != '')
            $Config['Price']['Luck'] = App::$Post->opt_luck;
        else
            $Config['Price']['Luck'] = 0;
        if (property_exists(App::$Post,'opt_skill') && App::$Post->opt_skill != '')
            $Config['Price']['Skill'] = App::$Post->opt_skill;
        else
            $Config['Price']['Skill'] = 0;
        if (property_exists(App::$Post,'opt_level') && App::$Post->opt_level != '')
            $Config['Price']['Level'] = App::$Post->opt_level;
        else
            $Config['Price']['Level'] = 0;
        if (property_exists(App::$Post,'opt_addition') && App::$Post->opt_addition != '')
            $Config['Price']['Option'] = App::$Post->opt_addition;
        else
            $Config['Price']['Option'] = 0;
        if (property_exists(App::$Post,'opt_harmony') && App::$Post->opt_harmony != '')
            $Config['Price']['Harmony'] = App::$Post->opt_harmony;
        else
            $Config['Price']['Harmony'] = 0;
        if (property_exists(App::$Post,'opt_excellent') && App::$Post->opt_excellent != '')
            $Config['Price']['Excellent'] = App::$Post->opt_excellent;
        else
            $Config['Price']['Excellent'] = 0;
        if (property_exists(App::$Post,'opt_harmony_level') && App::$Post->opt_harmony_level != '')
            $Config['Price']['HarmonyLevel'] = App::$Post->opt_harmony_level;
        else
            $Config['Price']['HarmonyLevel'] = 0;
        if (property_exists(App::$Post,'opt_ancient') && App::$Post->opt_ancient != '')
            $Config['Price']['Ancient'] = App::$Post->opt_ancient;
        else
            $Config['Price']['Ancient'] = 0;
        if (property_exists(App::$Post,'opt_soc1') && App::$Post->opt_soc1 != '')
            $Config['Price']['Socket1'] = App::$Post->opt_soc1;
        else
            $Config['Price']['Socket1'] = 0;
        if (property_exists(App::$Post,'opt_soc2') && App::$Post->opt_soc2 != '')
            $Config['Price']['Socket2'] = App::$Post->opt_soc2;
        else
            $Config['Price']['Socket2'] = 0;
        if (property_exists(App::$Post,'opt_soc3') && App::$Post->opt_soc3 != '')
            $Config['Price']['Socket3'] = App::$Post->opt_soc3;
        else
            $Config['Price']['Socket3'] = 0;
        if (property_exists(App::$Post,'opt_soc4') && App::$Post->opt_soc4 != '')
            $Config['Price']['Socket4'] = App::$Post->opt_soc4;
        else
            $Config['Price']['Socket4'] = 0;
        if (property_exists(App::$Post,'opt_soc5') && App::$Post->opt_soc5 != '')
            $Config['Price']['Socket5'] = App::$Post->opt_soc5;
        else
            $Config['Price']['Socket5'] = 0;
        
        file_put_contents('configs/modules/DB_' . $Db . '/Shop.json', json_encode($Config));

    }
    public static function AddItem($Db, $id = null)
    {
        $Config = file_get_contents("configs/modules/DB_" . $Db . "/Shop.json");
        $Config = json_decode($Config,true);

        if (property_exists(App::$Post,'add_item_class') && App::$Post->add_item_class != '')
            $Item['CharClass'] = App::$Post->add_item_class;
        else
            $Item['CharClass'] = 0;
        if (property_exists(App::$Post,'add_item_name') && App::$Post->add_item_name != '')
            $Item['Name'] = App::$Post->add_item_name;
        else
            $Item['Name'] = 0;
        if (property_exists(App::$Post,'add_item_type') && App::$Post->add_item_type != '')
            $Item['Type'] = App::$Post->add_item_type;
        else
            $Item['Type'] = 0;
        if (property_exists(App::$Post,'add_item_index') && App::$Post->add_item_index != '')
            $Item['Index'] = App::$Post->add_item_index;
        else
            $Item['Index'] = 0;
        if (property_exists(App::$Post,'add_item_luck') && App::$Post->add_item_luck != '')
            $Item['Luck'] = App::$Post->add_item_luck;
        else
            $Item['Luck'] = 0;
        if (property_exists(App::$Post,'add_item_skill') && App::$Post->add_item_skill != '')
            $Item['Skill'] = App::$Post->add_item_skill;
        else
            $Item['Skill'] = 0;
        if (property_exists(App::$Post,'add_item_harmony') && App::$Post->add_item_harmony != '')
            $Item['Harmony'] = App::$Post->add_item_harmony;
        else
            $Item['Harmony'] = 0;
        if (property_exists(App::$Post,'add_item_anc1') && App::$Post->add_item_anc1 != '')
            $Item['Ancient1'] = App::$Post->add_item_anc1;
        else
            $Item['Ancient1'] = 0;
        if (property_exists(App::$Post,'add_item_anc2') && App::$Post->add_item_anc2 != '')
            $Item['Ancient2'] = App::$Post->add_item_anc2;
        else
            $Item['Ancient2'] = 0;
        if (property_exists(App::$Post,'add_item_max_level') && App::$Post->add_item_max_level != '')
            $Item['MaxLevel'] = App::$Post->add_item_max_level;
        else
            $Item['MaxLevel'] = 0;
        if (property_exists(App::$Post,'add_item_max_exl') && App::$Post->add_item_max_exl != '')
            $Item['MaxExcellent'] = App::$Post->add_item_max_exl;
        else
            $Item['MaxExcellent'] = 0;
        if (property_exists(App::$Post,'add_item_max_add') && App::$Post->add_item_max_add != '')
            $Item['MaxAddition'] = App::$Post->add_item_max_add;
        else
            $Item['MaxAddition'] = 0;
        if (property_exists(App::$Post,'add_item_max_soc') && App::$Post->add_item_max_soc != '')
            $Item['MaxSockets'] = App::$Post->add_item_max_soc;
        else
            $Item['MaxSockets'] = 0;
        if (property_exists(App::$Post,'add_item_price') && App::$Post->add_item_price != '')
            $Item['StartPrice'] = App::$Post->add_item_price;
        else
            $Item['StartPrice'] = 0;

        if(is_numeric($id))
            $Config['Items'][$id] = $Item;
        else
            $Config['Items'][] = $Item;

        file_put_contents('configs/modules/DB_' . $Db . '/Shop.json', json_encode($Config));
    }
    public static function DeleteItem($Id, $Db)
    {
        $Config = file_get_contents("configs/modules/DB_" . $Db . "/Shop.json");
        $Config = json_decode($Config,true);


        unset($Config['Items'][$Id]);
        file_put_contents('configs/modules/DB_' . $Db . '/Shop.json', json_encode($Config));
    }
    public static function UpdateItem($Id, $Db)
    {
        $Config = file_get_contents("configs/modules/DB_" . $Db . "/Shop.json");
        $Config = json_decode($Config,true);

        $Config['Items'][$Id]['Key'] = $Id;
        return $Config['Items'][$Id];
    }


    /*
     * Help Titles/Links static methods
     */
    public static function GetImageChar($Class)
    {
        switch ($Class) {
            case 0: $classnum = "/web/templates/default/images/Characters/sm.png"; break;
            case 2: $classnum = "/web/templates/default/images/Characters/bk.png"; break;
            case 3: $classnum = "/web/templates/default/images/Characters/me.png"; break;
            case 4: $classnum = "/web/templates/default/images/Characters/su.png"; break;
            case 5: $classnum = "/web/templates/default/images/Characters/mg.png"; break;
            case 6: $classnum = "/web/templates/default/images/Characters/dl.png"; break;
            case 7: $classnum = "/web/templates/default/images/Characters/rf.png"; break;
        }
        return $classnum;
    }
    public static function GetClassChar($Class)
    {
        switch ($Class) {
            case 0: $classnum = "Dark Wizard"; break;
            case 2: $classnum = "Dark Knight"; break;
            case 3: $classnum = "Fairy Elf"; break;
            case 4: $classnum = "Summoner"; break;
            case 5: $classnum = "Magic Gladiator"; break;
            case 6: $classnum = "Dark Lord"; break;
            case 7: $classnum = "Rage Fighter"; break;
        }
        return $classnum;
    }
    public static function ClassesNames($Class)
    {
        $classnum = '';
        switch ($Class) {
        case"0": $classnum = 'Dark Wizard'; break;
        case"1": $classnum = 'Dark Knight'; break;
        case"2": $classnum = 'Fairy Elf'; break;
        case"3": $classnum = 'Summoner'; break;
        case"4": $classnum = 'Magic Gladiator'; break;
        case"5": $classnum = 'Dark Lord'; break;
        case"6": $classnum = 'Rage Fight'; break;
        case"7": $classnum = 'Other Item'; break;
        }
        return $classnum;
    }
    function getCategoryName($cat){
        switch ($cat) {
            case 0: return 'Swords'; break;
            case 1: return 'Axes'; break;
            case 2: return 'Scepters'; break;
            case 3: return 'Spears'; break;
            case 4: return 'Bows'; break;
            case 5: return 'Staffs'; break;
            case 6: return 'Shields'; break;
            case 7: return 'Helms'; break;
            case 8: return 'Armors'; break;
            case 9: return 'Pants'; break;
            case 10: return 'Gloves'; break;
            case 11: return 'Boots'; break;
            case 12: return 'Wings/Ords/Seeds/Boxes'; break;
            case 13: return 'Miscs'; break;
            case 14: return 'Jewels/Potions/Tickets'; break;
            case 15: return 'Skills'; break;
            default: return 'Unknown';break;
        }
    }
}