<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Communicator_activity extends CI_Controller
{
	public function index()
	{
		$this->load->model('common_model');
		$receipent = $this->common_model->getAllMultipleJoin('communicator','','','date DESC');
		$activity = array();
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		$mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
	    $tags = array();
	    $senders = array('noreply@castleevents.com');
	    $api_keys = array('TveFwCTbtHjorrsBDKwJ8Q');
	    $limit = 1000;
	    //pr($receipent);
	    if(count($receipent)>0)
	    {
	    	foreach ($receipent as $key => $value) {
	    		$arr = explode(' ',trim($value['subject']));
				$query = 'subject:'.str_replace(':', '', $arr[0]).'';
	    		$date_from = $value['date'];
	    		$date_to = $value['date'];
	    		$activity = $mandrill->messages->search($query, $date_from, $date_to, $tags, $senders, $api_keys, $limit);
	    		//echo '<pre>';print_r($activity);
	    		if($activity)
	    		{
	    			foreach ($activity as $k => $val) {
	    				$userdetails = $this->common_model->getAllRow('usr_users',array('email'=>$val['email']));
	    				$communicatordetails = $this->common_model->getAllRow('communicator_to_user',array('communicator_id'=>$value['id'],'user_id'=>$userdetails['id']));
	    				$this->common_model->UpdateData('communicator_to_user',array('open'=>0,'click'=>0),array('communicator_id'=>$value['id'],'user_id'=>$userdetails['id']));
	    				//$this->common_model->UpdateData('communicator',array('open'=>0,'click'=>0),array('id'=>$value['id']));
	    				//echo $userdetails['id'].'|'.$value['id'].'|'.$val['opens'].'|'.$val['clicks'];die;
	    				if($communicatordetails)
	    				{
	    					$this->common_model->UpdateData('communicator_to_user',array('open'=>$val['opens'],'click'=>$val['clicks']),array('communicator_id'=>$value['id'],'user_id'=>$userdetails['id']));
	    					//$this->common_model->UpdateData('communicator',array('open'=>($val['opens']+$value['open']),'click'=>($val['clicks']+$value['click'])),array('id'=>$value['id']));
	    				}
	    				
	    				echo $this->db->last_query();//die;
	    				
	    			}
	    			
	    		}
	    	}
	    }
	    die;
	}
}