<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class provides a way for users to subscribe to redirection links.
 *
 * @package    Redir
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Controller_Redirection extends lnApp_Controller_TemplateDefault {
	final public function action_ajaxcheck() {
		$po = ORM::factory('Price',array('chars'=>strlen($_REQUEST['path'])));
		$ro = ORM::factory('Redir',array('servername'=>$_REQUEST['domain'],'path'=>$_REQUEST['path']));

		$result = array(
			'result'=>! $ro->loaded(),
			'domain'=>$_REQUEST['domain'],
			'path'=>$_REQUEST['path'],
			'month'=>$po->price_month,
			'monthstr'=>number_format($po->price_month,2),
			'year'=>$po->price_year,
			'yearstr'=>number_format($po->price_year,2),
		);

		$this->auto_render = FALSE;
		$this->response->headers('Content-Type','application/json');
		$this->response->body(json_encode($result));
	}

	final public function action_index() {
		$output = '';

		$output .= View::factory('redirection/new')
			->set('domains',ORM::factory('Domain')->where_active()->find_all());

                Script::add(array('type'=>'stdin','data'=>'
                        $(document).ready(function() {
                                $("input[name=path]").change(function() {
					$.ajax({
						url: "redirection/ajaxcheck",
						data: { "domain": $("select[name=domain]").val(), "path" : $(this).val() },
						dataType: "json",
						success: function(data) {
							if (data.result) {
								price = (data.month>0 ? data.monthstr+"/Monthly or " : "")+(data.year>0 ? data.yearstr+"/Yearly" : "");
								$("button[type=submit]").prop("disabled",false);
								$("#help-path").html(data.domain+"/"+data.path+" is available"+(price ? " for "+price : ""));
								if ($(".control-group").has("error"))
									$(".control-group").removeClass("error");
								$(".control-group").addClass("success");

							} else {
								$("button[type=submit]").prop("disabled",true);
								$("#help-path").html(data.domain+"/"+data.path+" is NOT available");
								if ($(".control-group").has("success"))
									$(".control-group").removeClass("success");
								$(".control-group").addClass("error");
							}
						},
						error: function(data){
								//error
						}
					});
				});
                        });'
                ));

		$this->template->content = $output;
		$this->template->meta->keywords = join(',',array(
			'Web URL Shortener',
			'URL Shortener',
			'URL Redirector',
			'Web Redirector',
		));
	}

	final public function action_post() {
		$output = '';

		if (! $this->request->post())
			HTTP::redirect(strtolower($this->request->controller()));

		$url = $this->request->post('url');
		if (! strpos($url,'://'))
			$url = 'http://'.$url;

		// Get pricing
		$po = ORM::factory('Price',array('chars'=>strlen($_REQUEST['path'])));

		if ($po->price_month OR $po->price_year) {
			$price = array();

			if ($po->price_year)
				$price['Yearly'] = number_format($po->price_year,2);
			if ($po->price_month)
				$price['Monthly'] = number_format($po->price_month,2);

			$posthidden = array(
				'cmd'=>'_cart',
				'business'=>Kohana::$config->load('debug')->paypaltest ? 'deon_1260578114_biz@graytech.net.au' : 'deon@leenooks.net',
				'bn'=>'Redir_BuyNow_WPS_AU',
				'cancel_return'=>URL::site('redirection',TRUE),
//				'custom'=>'',
				'currency_code'=>'AUD',
				'notify_url'=>URL::site('redirection/notify',TRUE),
				'return'=>URL::site('redirection/after',TRUE),
				'upload'=>'1',
				'item_number_1'=>sprintf('%s/%s',$this->request->post('domain'),$this->request->post('path')),
				'item_name_1'=>sprintf('Redirection to %s',$url),
			);

			$output .= View::factory('redirection/post')
				->set('domain',$this->request->post('domain'))
				->set('url',$url)
				->set('price',$price)
				->set('posthidden',$posthidden)
				->set('posturl',sprintf('https://%s/cgi-bin/webscr',Kohana::$config->load('debug')->paypaltest ? 'www.sandbox.paypal.com' : 'www.paypal.com'))
				#->set('posturl','/x.php')
				->set('path',$this->request->post('path'));

		// If this is a free redireciton, set it up if the domain exists
		} elseif (ORM::factory('Domain',array('domain'=>$this->request->post('domain')))->loaded()) {

			$ro = ORM::factory('Redir');
			$ro->servername = $this->request->post('domain');
			$ro->path = $this->request->post('path');
			$ro->redirect = $url;
			$ro->date_create = time();
			$ro->date_expire = time()+365*86400;
			$ro->save();

			$output .= 'Web redirection set up, you can try it '.HTML::anchor(sprintf('http://%s/%s',$this->request->post('domain'),$this->request->post('path')),'here');

		} else {
			HTTP::redirect(strtolower($this->request->controller()));
		}

		$this->template->content = $output;
	}
}
?>
