<?php

class nc_services_direct_campaign
{

    public $api;
    protected $allowed_strategies = array('HighestPosition', 'WeeklyBudget', 'LowestCost', 'LowestCostPremium', 'WeeklyPacketOfClicks', 'AverageClickPrice');
    public $show_strategies = array('HighestPosition', 'WeeklyBudget');
    public $strategies_fields = array(
      'WeeklyBudget' => array(
        'WeeklySumLimit' => true,
        'MaxPrice' => false
      ),
    );

    /**
     * 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);
        $this->api->set_finance_token($direct->finance_login);
    }

    public function get_list()
    {
        $campaigns = array();

        $this->api->reset_data();
        $this->api->set_method("GetCampaignsList");
        if ($this->api->send_request() === true) {
            foreach ($this->api->result['data'] as $campaign) {
                if ($campaign['StatusShow'] == 'Yes') {
                    $campaign['ShowStopAction'] = 1;
                } else {
                    $campaign['ShowResumeAction'] = 1;
                }

                if ($campaign['StatusArchive'] == 'Yes') {
                    $campaign['ShowResumeAction'] = null;
                    $campaign['ShowUnarchiveAction'] = 1;
                } elseif ($campaign['StatusShow'] == 'No') {
                    $campaign['ShowArchiveAction'] = 1;
                }

                if ($campaign['StatusModerate'] == 'New') {
                    $campaign['ShowModerateAction'] = 1;
                }
                array_push($campaigns, $campaign);
            }
        }
        return $campaigns;
    }

    public function stop($campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("StopCampaign");
        $this->api->add_param("CampaignID", $campaign_id);
        if ($this->api->send_request() === true) {
            
        }
    }

    public function resume($campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("ResumeCampaign");
        $this->api->add_param("CampaignID", $campaign_id);
        if ($this->api->send_request() === true) {
            
        }
    }

    public function remove($campaign_id)
    {
        $result = array();

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

    public function archive($campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("ArchiveCampaign");
        $this->api->add_param("CampaignID", $campaign_id);
        if ($this->api->send_request() === true) {
            
        }
    }

    public function unarchive($campaign_id)
    {
        $this->api->reset_data();
        $this->api->set_method("UnArchiveCampaign");
        $this->api->add_param("CampaignID", $campaign_id);
        if ($this->api->send_request() === true) {
            
        }
    }

    public function get($campaign_id)
    {
        $result = array();
        $this->api->reset_data();
        $this->api->set_method("GetCampaignsParams");
        $this->api->add_param("CampaignIDS", array($campaign_id));
        if ($this->api->send_request() === true) {
            $result = $this->api->result['data'][0];
        } else {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
    }

    public function save($data)
    {
        $result = array();

        //pre-filter
        $data['CampaignID'] = intval($data['CampaignID']);
        $data['StartDate'] = !empty($data['StartDate']) ? date('Y-m-d', strtotime($data['StartDate'])) : "";
        $data['Strategy']['StrategyName'] = !empty($data['Strategy']['StrategyName']) && in_array($data['Strategy']['StrategyName'], $this->allowed_strategies) ? $data['Strategy']['StrategyName'] : $this->allowed_strategies[0];
        
        $data['Strategy'] = $this->clean_strategy_fields($data['Strategy']['StrategyName'], $data['Strategy']);

        $data['Name'] = nc_services::get_instance()->utf8_convert($data['Name']);
        $data['FIO'] = nc_services::get_instance()->utf8_convert($data['FIO']);

        $this->api->reset_data();
        $this->api->set_method("CreateOrUpdateCampaign");

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

        if ($this->api->send_request() === false) {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
    }

    public function add_funds($data)
    {
        $result = array();

        //pre-filter
        $payments = array();
        $payments['CampaignID'] = intval($data['CampaignID']);
        $payments['Sum'] = intval($data['Sum']);
        
        $operation_num = nc_core()->get_settings("yandex_finance_operation_num", "services", 0, 0) + 1;
        nc_core()->set_settings("yandex_finance_operation_num", $operation_num, 'services', 0);
         
        $this->api->reset_data();
        $this->api->set_method("CreateInvoice");

        $this->api->set_request_data('finance_token', hash("sha256", $this->api->finance_token . $operation_num . "CreateInvoice" . $this->api->login));
        $this->api->set_request_data('operation_num', $operation_num);
        $this->api->add_param('Payments', array($payments));

        if ($this->api->send_request() === false) {
            if (!empty($this->api->error)) {
                $result['error'] = $this->api->error;
            }
        }
        return $result;
    }
    
    protected function clean_strategy_fields($strategy_name, $strategy)
    {
        foreach ($strategy as $name => $field) {
            if ($name != 'StrategyName' &&  !in_array($name, $this->strategies_fields[$strategy_name])) {
                unset($strategy[$name]);
            }
        }
        return $strategy;
    }

}
