<?php

/**
 * Created by PhpStorm.
 * User: MainUser
 * Date: 28.07.2016
 * Time: 14:31
 */
class CharacterMarket extends CharacterModule
{
    public function Sell()
    {
        $Config = App::$Configs->mod_CharacterMarket;
        if ($this->AccountOnline){
            Messages::Add('account_online');
            return false;
        }

        $Nick = App::Validate(App::$Post->selected_char);
        $Price = App::Validate(App::$Post->price);
       if (property_exists(App::$Post, 'sell_email'))
           $Email = App::Validate(App::$Post->sell_email);

        if (!in_array($Nick, Character::GetListCharsInAccount($_SESSION['login']))) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Sell (Nick excluded to account)", 'Modules.log');
            Messages::Add('fail_sell_char');
            return false;
        }
        $List = static::GetListToAcc($_SESSION['login'], $_SESSION['user_db']);
        $ListInSell = array();

        foreach($List as $list) {
            $ListInSell[] = $list['nickname'];
        }
        if (in_array($Nick, $ListInSell)) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Sell (Character for sale)", 'Modules.log');
            Messages::Add('fail_sell_char_for_sale');
            return false;
        }
        if (!is_numeric($Price) && $Price > 0) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Sell (Incorrect Price)", 'Modules.log');
            Messages::Add('fail_sell_char_incorrect_price');
            return false;
        }
        if ($Config['CheckEmail']){
            if (!App::$DBs[$_SESSION['user_db']]->select()->from('MEMB_INFO')->where('memb___id', $_SESSION['login'])->where('mail_addr', $Email)->count_all_results()) {
                Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Sell (Incorrect email)", 'Modules.log');
                Messages::Add('fail_sell_char_incorrect_email');
                return false;
            }

        }

        if (
            App::$DBs[$_SESSION['user_db']]->insert('ETW_MARKET_CHARACTER',array(
                'account' => $_SESSION['login'],
                'nickname' => $Nick,
                'time' => date('d.m.Y H:i'),
                'price' => $Price,
            ))
        ) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Success Sell", 'Modules.log');
            Messages::Add('success_sell');
            return true;

        } else {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Sell (Sql error)", 'Modules.log');
            Messages::Add('fail_sell_char');
            return false;
        }
    }
    public function Update()
    {
        $Config = App::$Configs->mod_CharacterMarket;
        if ($this->AccountOnline){
            Messages::Add('account_online');
            return false;
        }
        $Nick = App::Validate(App::$Post->selected_char);
        $Price = App::Validate(App::$Post->price);


        if (!in_array($Nick, Character::GetListCharsInAccount($_SESSION['login']))) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Update (Nick excluded to account)", 'Modules.log');
            Messages::Add('fail_update_char');
            return false;
        }
        $List = static::GetListToAcc($_SESSION['login'], $_SESSION['user_db']);
        $ListInSell = array();

        foreach($List as $list) {
            $ListInSell[] = $list['nickname'];
        }
        if (!in_array($Nick, $ListInSell)) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Update (Character for sale)", 'Modules.log');
            Messages::Add('fail_update_char_for_sale');
            return false;
        }
        if (!is_numeric($Price) && $Price > 0) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Update (Incorrect Price)", 'Modules.log');
            Messages::Add('fail_update_char_incorrect_price');
            return false;
        }


        if (
            App::$DBs[$_SESSION['user_db']]->update('ETW_MARKET_CHARACTER',array(
                'time' => date('d.m.Y H:i'),
                'price' => $Price,
            ), array(
                'account' => $_SESSION['login'],
                'nickname' => $Nick,
            ))
        ) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Success Update", 'Modules.log');
            Messages::Add('success_update');
            return true;

        } else {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Fail Update (Sql error)", 'Modules.log');
            Messages::Add('fail_update_char');
            return false;
        }
    }
    public function Buy()
    {
        $Config = App::$Configs->mod_CharacterMarket;
        //Account Online
        if ($this->AccountOnline){
            Messages::Add('account_online');
            return false;
        }
        $Id = App::Validate(App::$Post->buy_character);
        //Check id
        if (!is_numeric($Id)){
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (Error in ID)", 'Modules.log');
            Messages::Add('fail_buy_char');
            return false;
        }
        $NeedChar = App::$DBs[$_SESSION['user_db']]->select()->from('ETW_MARKET_CHARACTER')->where('id', $Id)->get()->result_array();

        //Isset ID char
        if (!count($NeedChar)){
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (Error in ID)", 'Modules.log');
            Messages::Add('fail_buy_char');
            return false;
        }
        $NeedChar = $NeedChar[0];


        //Check same account
        if ($NeedChar['account'] == $_SESSION['login']) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (The same accounts)", 'Modules.log');
            Messages::Add('fail_buy_same_acc');
            return false;
        }
        //Check Price
        if (!ValuteManager::Check($Config['Valute'], $NeedChar['price'])) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (need money)", 'Modules.log');
            Messages::Add('fail_buy_need_money');
            return false;
        }
        //Check Space Max 5
        $AccountCharacters = App::$DBs[$_SESSION['user_db']]->select()->from('AccountCharacter')->where('ID', $_SESSION['login'])->get()->result_array();
        if (
            ($AccountCharacters[0]['GameID1'] != '' && $AccountCharacters[0]['GameID1'] != ' ')  &&
            ($AccountCharacters[0]['GameID2'] != '' && $AccountCharacters[0]['GameID2'] != ' ')  &&
            ($AccountCharacters[0]['GameID3'] != '' && $AccountCharacters[0]['GameID3'] != ' ')  &&
            ($AccountCharacters[0]['GameID4'] != '' && $AccountCharacters[0]['GameID4'] != ' ')  &&
            ($AccountCharacters[0]['GameID5'] != '' && $AccountCharacters[0]['GameID5'] != ' ')
        ) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (Max Space (5))", 'Modules.log');
            Messages::Add('fail_buy_max_space');
            return false;
        }
        
        //Check Seller account online?
        if (User::AccountOnline($NeedChar['account'])) {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Buy (Seller account online)", 'Modules.log');
            Messages::Add('fail_buy_seller_acc_online');
            return false;
        }
        
        if (
            App::$DBs[$_SESSION['user_db']]->where('Name', $NeedChar['nickname'])->update('Character', array('AccountID' => $_SESSION['login'])) &&
            App::$DBs[$_SESSION['user_db']]->where('ID', $NeedChar['account'])->where('GameID1', $NeedChar['nickname'])->update('AccountCharacter', array('GameIDC' => '', 'GameID1' => '')) &&
            App::$DBs[$_SESSION['user_db']]->where('ID', $NeedChar['account'])->where('GameID2', $NeedChar['nickname'])->update('AccountCharacter', array('GameIDC' => '', 'GameID2' => '')) &&
            App::$DBs[$_SESSION['user_db']]->where('ID', $NeedChar['account'])->where('GameID3', $NeedChar['nickname'])->update('AccountCharacter', array('GameIDC' => '', 'GameID3' => '')) &&
            App::$DBs[$_SESSION['user_db']]->where('ID', $NeedChar['account'])->where('GameID4', $NeedChar['nickname'])->update('AccountCharacter', array('GameIDC' => '', 'GameID4' => '')) &&
            App::$DBs[$_SESSION['user_db']]->where('ID', $NeedChar['account'])->where('GameID5', $NeedChar['nickname'])->update('AccountCharacter', array('GameIDC' => '', 'GameID5' => ''))
        ) {
            ValuteManager::Take($Config['Valute'], $NeedChar['price']);
            
            //Add To AccountCharacter
            for ($i = 1; $i <= 5; $i++ ) {
                if( $AccountCharacters[0]['GameID' . $i] == '' || $AccountCharacters[0]['GameID' . $i] == ' ') {
                    App::$DBs[$_SESSION['user_db']]->where('ID', $_SESSION['login'])->update('AccountCharacter', array('GameID'.$i => $NeedChar['nickname']));
                    break;
                }
            }
            ValuteManager::Reward($Config['Valute'], $NeedChar['price'], $NeedChar['account']);
            App::$DBs[$_SESSION['user_db']]->where('ID', $Id)->delete('ETW_MARKET_CHARACTER');

            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Success Buy Char ({$NeedChar['nickname']}) From Acc ({$NeedChar['account']})", 'Modules.log');
            Messages::Add('success_buy');
            return $NeedChar['nickname'];
        }


    }
    public function Take()
    {
        $Config = App::$Configs->mod_CharacterMarket;
        //Account Online
        if ($this->AccountOnline){
            Messages::Add('account_online');
            return false;
        }
        $Id = App::Validate(App::$Post->take_character);
        //Check id
        if (!is_numeric($Id)){
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Take (Error in ID)", 'Modules.log');
            Messages::Add('fail_take_char');
            return false;
        }
        $NeedChar = App::$DBs[$_SESSION['user_db']]->select()->from('ETW_MARKET_CHARACTER')->where('id', $Id)->get()->result_array();

        //Isset ID char
        if (!count($NeedChar)){
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Take (Error in ID)", 'Modules.log');
            Messages::Add('fail_take_char');
            return false;
        }
        $NeedChar = $NeedChar[0];


        //Check same account
        if ($NeedChar['account'] == $_SESSION['login']) {
        	if ( App::$DBs[$_SESSION['user_db']]->where('account', $_SESSION['login'])->where('id', $Id)->delete('ETW_MARKET_CHARACTER')) {
        		Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}] Nick: [{$Nick}]. Success Take", 'Modules.log');
	            Messages::Add('charmarket_success_take');
	            return true;
        	}
        } else {
            Logs::WriteLog("Module: [CharacterMarket], Account: [{$_SESSION['login']}]. Fail Take (The not same accounts)", 'Modules.log');
            Messages::Add('fail_take_not_same_acc');
            return false;
        }
       
    }
    public function GetListInfo()
    {
        $Data = App::$DBs[$_SESSION['user_db']]->select(array('Name', 'cLevel', 'Class', App::$DBs[$_SESSION['user_db']]->column_names['Resets'], App::$DBs[$_SESSION['user_db']]->column_names['GrandResets'], 'LevelUpPoint', 'Money', 'Strength', 'Dexterity', 'Vitality', 'Energy', 'Leadership', 'AccountID', 'price' , 'ETW_MARKET_CHARACTER.price', 'ETW_MARKET_CHARACTER.time', 'ETW_MARKET_CHARACTER.id'))->from('ETW_MARKET_CHARACTER')
            ->join('Character','Character.Name = ETW_MARKET_CHARACTER.nickname COLLATE DATABASE_DEFAULT', 'left' ,false)
            ->get()->result_array();

        for ($i = 0; $i < count($Data); $i++) {
            if (App::$DBs[$_SESSION['user_db']]->column_names['Resets'] != 'Resets')
                $Data[$i]['Resets'] = $Data[$i][App::$DBs[$_SESSION['user_db']]->column_names['Resets']];
            if (App::$DBs[$_SESSION['user_db']]->column_names['GrandResets'] != 'GrandResets')
                $Data[$i]['GrandResets'] = $Data[$i][App::$DBs[$_SESSION['user_db']]->column_names['GrandResets']];
        }

        return $Data;
    }

    public function ViewInv($Nick) 
    {
        if ($Nick == ''){
            return false;
        }
        $Items = new Item();
        $Items->LoadItemBase();
        $result = mssql_fetch_array(mssql_query('SELECT [Inventory] FROM [Character] WHERE [Name]= \''.$Nick. '\'' , App::$DBs[$_SESSION['user_db']]->conn_id));
        $result = $result[0];
        $result = bin2hex($result);
        $result = strtoupper($result);

        $Inventory = '<div>';

        for ($i=0; $i < 480; $i++) {
            $db_item_code[$i] = substr($result,(32*$i), 32);
            if($db_item_code[$i] != 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') {
                $db_item_info[$i] = $Items->GetItemInfo(substr($result,(32*$i), 32));
                if($db_item_info[$i] != NULL) {
                    $title_content[$i] = $db_item_info[$i]['info'];
                    $Inventory .= "<a href='#' title='' class='lightbox' style='width:130px;height:130px;' onmouseover=\"Tip('".$title_content[$i]."');\" onmouseout=\"UnTip();\" ><img src='".$db_item_info[$i]['thumb']."' alt=''></a>";
                   // $Inventory .= "<div style='position:absolute; left:6px; top:242px; width:69px; height:129px; background: url(".$db_item_info[$i][thumb].") no-repeat center center;' onmouseover=\"Tip('".$title_content[0]."');\" onmouseout=\"UnTip();\">&nbsp;</div>";
                }
            }
        }
        $Inventory .= '</div>';

        return $Inventory;
    }
    
    public function GetListToAcc($Acc, $Db)
    {
        $Acc = App::Validate($Acc);
        return App::$DBs[$Db]->select()->from('ETW_MARKET_CHARACTER')->where('account', $Acc)->get()->result_array();
    }
    public static function CreateTable()
    {
        App::$DBs[0]->simple_query(
            '
            CREATE TABLE ETW_MARKET_CHARACTER(
            [id] [int] IDENTITY(1,1) NOT NULL,
            [account] [varchar](50) COLLATE Cyrillic_General_CI_AS NULL,
            [nickname] [varchar](50) COLLATE Cyrillic_General_CI_AS NULL,
            [time] [varchar](50) COLLATE Cyrillic_General_CI_AS NULL,
            [price] [int] NULL,
        ) ON [PRIMARY]
            '
        );
    }
    public static function ConfigModules($Db)
    {
        $Config = file_get_contents("configs/modules/DB_" . $Db . "/CharacterMarket.json");
        $Config = json_decode($Config,true);
        if (property_exists(App::$Post,'Enable')) {
            $Config['Enable'] = true;
        }
        else {
            $Config['Enable'] = false;
        } if (property_exists(App::$Post,'CheckEmail')) {
            $Config['CheckEmail'] = true;
        }
        else {
            $Config['CheckEmail'] = false;
        }

        if (property_exists(App::$Post,'main_valute') && App::$Post->main_valute != '')
            $Config['Valute'] = App::$Post->main_valute;
        else
            $Config['Valute'] = 0;

        file_put_contents('configs/modules/DB_' . $Db . '/CharacterMarket.json', json_encode($Config));

    }
}