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

class Keyword extends CI_Controller {

	public function __construct() {
	  parent::__construct();
	  $this->load->model('keyword_model');
	  $this->load->helper('cookie');
	  $this->load->database(); 
	  
	}

	public function index(){
		echo "string";
	}

	public function newData(){
		$data = '';
		$this->load->view('keyword/view_dashboard', $data);
	}
	
		public function edit(){

		$data['campaign_one'] = $this->keyword_model->get_campaign_one($this->uri->segment(3));
	
		if($data['campaign_one'])	{
			$this->load->view('keyword/view_edit', $data);	
		}
		
	}
	
	public function hash()
	{
	    //die($this->uri->segment(3));
	    $keyword_hash=$this->keyword_model->get_campaign_one_hash($this->uri->segment(3));
	    $url=$keyword_hash->url;
	    $url_keywords=$keyword_hash->keywords;
	    (preg_match_all('/"([^"]+)"/',$url_keywords,$m));
	    foreach($m[0] as $key => $value) 
	    {
	        if($key&1) 
	          {
	              unset($m[0][$key]);
	          }
	    }  
	    
	    $randIndex = array_rand($m[0]);
	    $final_url=str_replace("{{keyword}}",str_replace('"', '', $m[0][$randIndex]),$url);
	    
	    header("Location: $final_url");
        die();
	}
	


	public function campaigns(){
		$data['campaign'] = $this->keyword_model->get_campaign();
		$this->load->view('keyword/view_campaigns', $data);
	}

	public function new_keywords(){
		$str = '';
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$size = strlen( $chars );
		for( $i = 0; $i < 16; $i++ ) {
			$str .= $chars[ rand( 0, $size - 1 ) ];
		}	
		$kq = $this->input->post('newcampaign_keywords');
		$kq = substr(substr($kq, 1), 0, -1);
		$rt = (explode(",",$kq));

		$data_k['name'] = $this->input->post('newcampaign_name');
		$data_k['domain'] = $this->input->post('newcampaign_domain');
		$data_k['url'] = $this->input->post('newcampaign_url');
		$data_k['keywords'] = $kq; 
		$data_k['hash_keyword']	= $str;
		$this->keyword_model->create_keyword($data_k); 
		redirect('keyword/campaigns');	
	}
	
		public function removecampaign(){

		$this->keyword_model->delete_campaign($this->uri->segment(3));
		redirect('keyword/campaigns');		
	}
	
		public function update_keywords(){
		$str = '';
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$size = strlen( $chars );
		for( $i = 0; $i < 16; $i++ ) {
			$str .= $chars[ rand( 0, $size - 1 ) ];
		}	
		$kq = $this->input->post('newcampaign_keywords');
		$kq = substr(substr($kq, 1), 0, -1);
		$rt = (explode(",",$kq));

		$data_k['name'] = $this->input->post('newcampaign_name');
		$data_k['domain'] = $this->input->post('newcampaign_domain');
		$data_k['url'] = $this->input->post('newcampaign_url');
		$data_k['keywords'] = $kq; 
		$data_k['hash_keyword']	= $str;
		$this->keyword_model->update_campaign($this->input->post('c_slug'),$data_k);
		redirect('keyword/campaigns');	
	}
	
	

}