<?php defined("IN_DOCEBO") or die('Direct access is forbidden.');

/* ======================================================================== \
| 	DOCEBO - The E-Learning Suite											|
| 																			|
| 	Copyright (c) 2008 (Docebo)												|
| 	http://www.docebo.com													|
|   License 	http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt		|
\ ======================================================================== */

class CartLmsController extends LmsController {

	public $name = 'catalog';

	private $path_course = '';

	protected $_default_action = 'show';

	var $model;
	var $json;
	var $acl_man;

	public function isTabActive($tab_name)
	{
		return false;
	}

	public function init()
	{
		YuiLib::load('base,tabview');
		Lang::init('course');
		$this->path_course = $GLOBALS['where_files_relative'].'/doceboLms/'.Get::sett('pathcourse').'/';
		$this->model = new CartLms();

		require_once(_base_.'/lib/lib.json.php');
		$this->json = new Services_JSON();

		$this->acl_man =& Docebo::user()->getAclManager();

		Util::get_css(Get::rel_path(_base_).'/doceboLms/views/cart/cart.css', true, true);
	}

	public function show()
	{
		$total_price = $this->model->getTotalPrice();

		$id_trans = Get::req('id_transaction', DOTY_INT, 0);

		if(isset($_GET['cancel']) && $_GET['cancel'] == 1)
			UIFeedback::error(Lang::t('_TRANSACTION_ABORTED', 'cart'));
		if(isset($_GET['error']) && $_GET['error'] == 1)
			UIFeedback::error(Lang::t('_TRANSACTION_CREATION_ERROR', 'cart'));
//UIFeedback::info(Lang::t('_COURSE_ACTIVATION_SUCCESS', 'cart'));
		$this->render('show', array('total_price' => $total_price));
	}

	public function getCartList()
	{
		$sort = Get::req('sort', DOTY_MIXED, 'name');
		$dir = Get::req('dir', DOTY_MIXED, 'asc');

		$course_list = $this->model->getCartList();

		$result = array(
			'totalRecords' => count($course_list),
			'startIndex' => 0,
			'sort' => $sort,
			'dir' => $dir,
			'rowsPerPage' => count($course_list),
			'results' => count($course_list),
			'records' => $course_list
		);

		echo $this->json->encode($result);
	}

	public function emptyCart()
	{
		$_SESSION['lms_cart'] = array();

		$result['success'] = true;

		echo $this->json->encode($result);
	}

	public function delSelectedElement()
	{
		$del_list = Get::req('elements', DOTY_MIXED, '');
		$del_list = explode(',', $del_list);

		$cart = $_SESSION['lms_cart'];

		foreach($del_list as $id)
		{
			$id_details = explode('_', $id);

			if($id_details[1] != 0)
			{
				unset($cart[$id_details[0]]['classroom'][$id_details[1]]);
				if(empty($cart[$id_details[0]]['classroom']))
					unset($cart[$id_details[0]]);
			}
			elseif($id_details[2] != 0)
			{
				unset($cart[$id_details[0]]['edition'][$id_details[2]]);
				if(empty($cart[$id_details[0]]['edition']))
					unset($cart[$id_details[0]]);
			}
			else
			{
				unset($cart[$id_details[0]]);
			}
		}

		$_SESSION['lms_cart'] = $cart;

		require_once(_lms_.'/lib/lib.cart.php');

		$result = array(	'success' => true,
							'cart_element' => '('.Learning_Cart::cartItemCount().')',
							'price' => $this->model->getTotalPrice());

		echo $this->json->encode($result);
	}

	public function makeOrder()
	{
		$wire = Get::req('wire', DOTY_INT, 0);

		$cart = $_SESSION['lms_cart'];
		require_once(_lms_.'/lib/lib.cart.php');

		if(Learning_Cart::cartItemCount() > 0)
			$id_trans = $this->model->createTransaction();
		else
			$id_trans = false;

		if($id_trans === false)
		{
			$result = array(	'success' => false,
								'message' => UIFeedback::error(Lang::t('_ERROR_CREATE_TRANS', 'catalogue'), true));
		}
		else
		{
			$course_info = $this->model->getCartList(true);
			$total_price = 0;

			foreach($cart as $id_course => $extra)
			{
				$docebo_course = new DoceboCourse($id_course);

				require_once(_lms_.'/admin/models/SubscriptionAlms.php');

				$level_idst =& $docebo_course->getCourseLevel($id_course);

				if(count($level_idst) == 0 || $level_idst[1] == '')
					$level_idst =& $docebo_course->createCourseLevel($id_course);

				$waiting = 1;

				$this->acl_man->addToGroup($level_idst[3], Docebo::user()->getIdSt());

				if(isset($extra['classroom']))
				{
					foreach($extra['classroom'] as $id_date)
					{
						$model = new SubscriptionAlms($id_course, 0, $id_date);
						if(!$model->subscribeUser(Docebo::user()->getIdSt(), 3, $waiting))
							$this->acl_man->removeFromGroup($level_idst[3], Docebo::user()->getIdSt());
						elseif($this->model->addTransactionCourse($id_trans, $id_course, $id_date, 0, $course_info[$id_course.'_'.$id_date.'_0']))
						{
							unset($_SESSION['lms_cart'][$id_course]['classroom'][$id_date]);
							$query =	"UPDATE %lms_courseuser"
										." SET status = '-2'"
										." WHERE idUser = ".Docebo::user()->getIdSt()
										." AND idCourse = ".$id_course;
							
							sql_query($query);

							$total_price += $course_info[$id_course.'_'.$id_date.'_0']['price'];
						}
					}
				}
				elseif(isset($extra['edition']))
				{
					foreach($extra['edition'] as $id_edition)
					{
						$model = new SubscriptionAlms($id_course, $id_edition, 0);
						if(!$model->subscribeUser(Docebo::user()->getIdSt(), 3, $waiting))
							$this->acl_man->removeFromGroup($level_idst[3], Docebo::user()->getIdSt());
						elseif($this->model->addTransactionCourse($id_trans, $id_course, 0, $id_edition, $course_info[$id_course.'_0_'.$id_edition]))
						{
							unset($_SESSION['lms_cart'][$id_course]['edition'][$id_edition]);
							$query =	"UPDATE %lms_courseuser"
										." SET status = '-2'"
										." WHERE idUser = ".Docebo::user()->getIdSt()
										." AND idCourse = ".$id_course;

							sql_query($query);

							$total_price += $course_info[$id_course.'_0_'.$id_edition]['price'];
						}
					}
				}
				else
				{
					$model = new SubscriptionAlms($id_course, 0, 0);
					if(!$model->subscribeUser(Docebo::user()->getIdSt(), 3, $waiting))
						$this->acl_man->removeFromGroup($level_idst[3], Docebo::user()->getIdSt());
					elseif($this->model->addTransactionCourse($id_trans, $id_course, 0, 0, $course_info[$id_course.'_0_0']))
					{
						unset($_SESSION['lms_cart'][$id_course]);
						$query =	"UPDATE %lms_courseuser"
									." SET status = '-2'"
									." WHERE idUser = ".Docebo::user()->getIdSt()
									." AND idCourse = ".$id_course;

						sql_query($query);

						$total_price += $course_info[$id_course.'_0_0']['price'];
					}
				}
			}

			require_once(_lms_.'/lib/lib.cart.php');
			if(Learning_Cart::cartItemCount() == 0)
				$_SESSION['lms_cart'] = array();

			$result = array(	'success' => true,
								'message' => UIFeedback::info(Lang::t('_TRANS_CREATED', 'catalogue'), true),
								'id_transaction' => $id_trans,
								'total_price' => $total_price,
								'link' => Get::sett('url').Get::rel_path('lms').'/index.php?r=cart/show&id_transaction='.$id_trans);
		}

		if($wire)
		{
			if($result['success'])
				Util::jump_to('index.php?r=cart/wireInfo&id_transaction='.$id_trans);
			Util::jump_to('index.php?r=cart/show&error=1');
		}
		else
			echo $this->json->encode($result);
	}

	public function wireInfo()
	{
		require_once(_lms_.'/admin/models/TransactionAlms.php');
		$model = new TransactionAlms();

		$id_trans = Get::req('id_transaction', DOTY_INT, 0);

		$transaction_info = $model->getTransactionInfo($id_trans);

		$total_price = 0;

		foreach($transaction_info['product'] as $product_info)
			$total_price += $product_info['price'];

		if($id_trans != 0)
			UIFeedback::info(Lang::t('_TRANS_CREATED', 'cart'));

		$this->render('wire', array('transaction_info' => $transaction_info, 'total_price' => $total_price));
	}
}
