<?php

class Am_Plugin_SmAmemberIntegration extends Am_Plugin
{
    const PLUGIN_STATUS = self::STATUS_PRODUCTION;
    const PLUGIN_REVISION = '1.0';
    const SNAKEMEMBER_URL = 'http://areamembri.it';
    
    // Plugin configuration
    protected $api_user;
    protected $api_key;

    public function __construct(Am_Di $di, array $config)
    {
        $this->api_user = $di->config->get('sm_api_user');
        $this->api_key = $di->config->get('sm_api_key');
        parent::__construct($di, $config);
    }
    public function isConfigured()
    {
        return (!empty($this->api_user) && !empty($this->api_key));
    }
    
    function onSetupForms(Am_Event_SetupForms $forms)
    {
        $form = new Am_Form_Setup('sm_amember_integration');
        $form->setTitle("SnakeMember Integration");
        $forms->addForm($form);
        $form->addElement('text', 'sm_api_user')
             ->setLabel(array('API User', 'This is the API user of your main business.'));
        $form->addElement('text', 'sm_api_key')
             ->setLabel(array('API Key', 'This is the API key of your main business.'));
        
    }
    
    // Product configuration
    function init()
    {
        // Este no es nuestro caso, pues imprime un input type="text" (Am_CustomFieldText)
        //$this->getDi()->productTable->customFields()->add(new Am_CustomFieldText('sm_campaign_nicename', ___('Campaign'), ___('')));
        
        // Este sí lo es, imprime un select (Am_CustomFieldSelect)
        
        $opt = array(
          '' => ___('Select a campaign')
        );
        
        $this->getDi()->productTable->customFields()->add(
            new Am_CustomFieldSelect('sm_campaign_nicename', ___('Campaign'), null, null, array('options' => $opt+$this->getSnakememberCampaigns()))
        );
        
    }
    
    // Este metodo añade este campo a la cabecera de la tabla de productos, para luego llamar, para cada producto, al metodo render inferior
    function onGridProductInitGrid(Am_Event_Grid $event)
    {
        $grid = $event->getGrid();
        $grid->addField(new Am_Grid_Field('sm_campaign_nicename', ___('Campaign'), false))->setRenderFunction(array($this, 'renderCampaignName'));
    }
    
    // Este es el metodo que imprime en el listado de productos el valor que tiene ese producto
    function renderCampaignName(Product $product)
    {
        return '<td align="center">' . ( ($camp_name = $product->data()->get('sm_campaign_nicename')) ? $camp_name : '&ndash;')  . '</td>';
    }
    
    
    function onSubscriptionAdded(\Am_Event $event){
      $user_object = $event->getUser();
      $product_object = $event->getProduct();
      
      self::subscribeToSnakemember($user_object, $product_object);
    }
    
    function onPaymentEvent(\Am_Event $event){
      $user_object = $event->getUser();
      
      $products = $event->getPayment()->getInvoice()->getProducts();
      
      foreach($products as $product){
        self::subscribeToSnakemember($user_object, $product);
      }
      
    }
    
    // Método para la compra del producto => Llamada a SnakeMember#subscribe
    function subscribeToSnakemember($user_object, $product_object) {
      
      $listname = $product_object->data()->get('sm_campaign_nicename');
      
      $user_email = $user_object->email;
      $user_first_name = $user_object->name_f;
      $user_last_name = $user_object->name_l;

      // Send communication to SnakeMember adding the user to a campaign
      $server_url = self::SNAKEMEMBER_URL;
      $server_path = '/campaigns/subscribe.json';

      $post_fields = array(
        "listname" => $listname,
        "email" => $user_email,
        "first_name" => $user_first_name,
        "last_name" => $user_last_name,
        "referer" => '#',
        "redirect" => '#',
        "meta_redirect_onlist" => '#',
        
      );

    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $server_url.$server_path);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    	curl_setopt($ch, CURLOPT_USERAGENT, 'cURL Request');
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    	ob_start();
    		$result = curl_exec($ch);
    	ob_end_clean();
    	curl_close($ch);
      
    }
    
    // Métodos API Snakemember
    
    // Llamada a SnakeMember para obtener las campañas
    function getSnakememberCampaigns(){
      
      $server_url = self::SNAKEMEMBER_URL;
      $server_path = '/campaigns.json';

      $post_fields = array(
        "api_user" => $this->api_user,
        "api_key" => $this->api_key,        
      );

    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $server_url.$server_path);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    	curl_setopt($ch, CURLOPT_USERAGENT, 'cURL Request');
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    	ob_start();
    		$result = curl_exec($ch);
    	ob_end_clean();
    	curl_close($ch);
      
      $result_obj_array = json_decode($result);
      
      $response = array();
      
      foreach($result_obj_array as $result_obj){
        $response[$result_obj->nicename] = sprintf("#%d - %s", $result_obj->id, $result_obj->name);
      }
      
      return $response;
    }

}

Am_Di::getInstance()->hook->add('subscriptionAdded', 'Am_Plugin_SmAmemberIntegration::onSubscriptionAdded');
Am_Di::getInstance()->hook->add('paymentAfterInsert', 'Am_Plugin_SmAmemberIntegration::onPaymentEvent');
