<?php

class nc_services_direct_banner
{

    public $api;
    
    //week
    protected $regions_uptime = 604800;
    
    // установите false, если нужны все регионы
    protected $allowed_regions = array(225, 166);

    /**
     * Constructor
     * @param nc_services_direct $direct
     */
    public function __construct(nc_services_direct $direct)
    {
        $this->api = new nc_services_direct_api();
        $this->api->set_token($direct->auth_token);
        $this->api->set_login($direct->direct_login);
    }

    public function get_list($campaign_id)
    {
        $banners = array();

        $this->api->reset_data();
        $this->api->set_method("GetBanners");
        $this->api->add_param("CampaignIDS", array($campaign_id));
        if ($this->api->send_request() === true) {
            foreach ($this->api->result['data'] as $banner) {
                if ($banner['StatusShow'] == 'Yes') {
                    $banner['ShowStopAction'] = 1;
                } else {
                    $banner['ShowResumeAction'] = 1;
                }

                if ($banner['StatusArchive'] == 'Yes') {
                    $banner['ShowResumeAction'] = null;
                    $banner['ShowUnarchiveAction'] = 1;
                } elseif ($banner['StatusShow'] == 'No') {
                    $banner['ShowArchiveAction'] = 1;
                }               
                $banner['StatusText'] = constant(NETCAT_MODULE_SERVICES_DIRECT_BANNER_STATUS_.  strtoupper($banner['StatusBannerModerate']));
                $banner['StatusPhrasesText'] = constant(NETCAT_MODULE_SERVICES_DIRECT_PHRASES_STATUS_.  strtoupper($banner['StatusPhrasesModerate']));
                array_push($banners, $banner);
            }
        }
        return $banners;
    }
    
    public function get($banner_id)
    {
        $result = array();
        $this->api->reset_data();
        $this->api->set_method("GetBanners");
        $this->api->add_param("GetPhrases", "WithPrices");
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === true) {
            $result = $this->api->result['data'][0];
            $result['MinusKeywords'] = implode(',', $result['MinusKeywords']);
            $phrases = array();
            foreach ($result['Phrases'] as $phrase) {
                array_push($phrases, $phrase['Phrase']);
            }
            $result['Phrases'] = implode(',', $phrases);
            $result['GeoArr'] = explode(',', $result['Geo']);
        } else {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
        
    }    
    
    public function get_regions() 
    {
        $regions = array(); $fresh = false;
        $yandex_regions_collected_time = (int)nc_core()->get_settings("yandex_regions_collected_time", "services", false, 0);
        if ($yandex_regions_collected_time < (time() - $this->regions_uptime)) {
            $this->api->reset_data();
            $this->api->set_method("GetRegions");
            if ($this->api->send_request() === true) {
                $insert_arr = array();
                $insert_str = "INSERT INTO `Services_YandexRegions` (`RegionID`, `ParentID`, `RegionName`) VALUES ";
                foreach ($this->api->result['data'] as $region) {
                    if ($region['RegionID'] == 0) {
                        $region['ParentID'] = -1;
                    }
                    array_push($insert_arr, "('".intval($region['RegionID'])."', '".intval($region['ParentID'])."', '".nc_db()->escape($region['RegionName'])."')");
                }
                $insert_str .= implode(',', $insert_arr);
                nc_db()->query("TRUNCATE TABLE `Services_YandexRegions`");
                nc_db()->query($insert_str);
                
                nc_core()->set_settings("yandex_regions_collected_time", time(), 'services', 0);
                $fresh = true;
            }
        }
        if ($fresh === true) {
            $regions = $this->api->result['data'];
        } else {
            $sql = "SELECT `RegionID`, `ParentID`, `RegionName` FROM `Services_YandexRegions`";
            $regions = nc_db()->get_results($sql, ARRAY_A);
        }
        $result = $this->build_tree($regions);
        
        return $this->clean_tree($result);
    }
 
        
    public function remove($banner_id, $campaign_id)
    {
        $result = array();

        $this->api->reset_data();
        $this->api->set_method("DeleteBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === false) {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
    }

     
    public function stop($banner_id, $campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("StopBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === true) {
            
        }
    }
    
    public function resume($banner_id, $campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("ResumeBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === true) {
            
        }
    }    

    public function archive($banner_id, $campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("ArchiveBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === true) {
            
        }
    }    
    
    public function unarchive($banner_id, $campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("UnArchiveBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", array($banner_id));
        if ($this->api->send_request() === true) {
            
        }
    }    
    public function save($data)
    {
        $result = array();
        //pre-filter
        $data['CampaignID'] = intval($data['CampaignID']);
        $data['BannerID'] = intval($data['BannerID']);
        $data['Title'] = nc_services::get_instance()->utf8_convert($data['Title']);
        $data['Text'] = nc_services::get_instance()->utf8_convert($data['Text']);
        $data['Href'] = "http://".$data['Href'];
        
        $phrases_tmp = explode(',', $data['Phrases']);
        $data['Phrases'] = array();
        foreach ($phrases_tmp as $phrase) {
            array_push($data['Phrases'], array( 
              'PhraseID' => 0, 
              'AutoBudgetPriority' => 'Medium', 
              'Phrase' =>nc_services::get_instance()->utf8_convert(trim($phrase))
              ));
        }

        $minus_tmp = explode(',', $data['MinusKeywords']);
        $data['MinusKeywords'] = array();
        foreach ($minus_tmp as $phrase) {
            array_push($data['MinusKeywords'], nc_services::get_instance()->utf8_convert(trim($phrase)));
        }
        $this->api->reset_data();
        $this->api->set_method("CreateOrUpdateBanners");

        $this->api->req_data['param'] = array($data);

        if ($this->api->send_request() === false) {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
    }
    
    public function send_moderate($banners, $campaign_id) 
    {

        $result = array();

        $banners_ids = array();
        
        foreach ($banners as $banner) {
            array_push($banners_ids, $banner['BannerID']);
        }
        $this->api->reset_data();
        $this->api->set_method("ModerateBanners");
        $this->api->add_param("CampaignID", $campaign_id);
        $this->api->add_param("BannerIDS", $banners_ids);
        if ($this->api->send_request() === false) {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
        
    }
    
    protected function build_tree($arr)
    {
        $childs = array();

        foreach ($arr as &$item)
            $childs[$item['ParentID']][] = &$item;
        unset($item);

        foreach ($arr as &$item)
            if (isset($childs[$item['RegionID']]))
                $item['childs'] = $childs[$item['RegionID']];

        return $childs[0];
    }
    
    protected function clean_tree($tree) 
    {
        if ($this->allowed_regions !== false && is_array($this->allowed_regions)) {
            foreach ($tree as $key => $item) {
                if ($item['ParentID'] == 0 && !in_array($item['RegionID'], $this->allowed_regions)) {
                    unset($tree[$key]);
                }
            }
        }
        return $tree;
    }

}
