<?php
require_once 'UI/Page/UISelectProductTypePage.php';

class Resellers_ResellerProfileController extends Billing_Zend_Controller_Action_AdminController
{
	
	public function indexAction()
	{
		// if customer is reseller, it means that he want to edit own profile
		$isReseller = getCurrentSession()->isReseller();
		
		$resellerId = $this->getRequest()->getParam('id');

		require_once("object_managers/ClientManager.php");
		if(!$resellerId && ClientManager::reachedCustomerAccountsNumberLimit()) {
			$this->_redirectWithMessage(
				$this->view->actionUrl('resellers', 'ShowResellers'),
				$this->view->translate("TRANS_YOUR_LICENSE_NOT_ALLOW_MORE_CUSTOMERS_OR_RESELLERS", array("NUMBER" => licMaxClients)),
				Billing_Zend_Controller_Action_Status::STATUS_ERROR
			);
		}
		$reseller = $resellerId ? Factory()->Reseller($resellerId) : Factory()->Reseller();
		$form = new Billing_Zend_Form_Final_ResellerProfileForm(
			$reseller,
			array(
				'cancelUrl' => getCurrentSession()->isReseller() ? $this->view->actionUrl('dashboard', 'ShowDashboard') : ($resellerId ? $this->view->actionUrl('clients', 'ShowClientDetails', array('clientID' => $resellerId)) : $this->view->actionUrl('resellers', 'ShowResellers')),
				'submitUrl' => $this->view->adminActionUrl('resellers', 'reseller-profile', 'index', $reseller ? array('id' => $reseller->id) : array()),
				'isReseller' => $isReseller
			)
		);

		if ($resellerId) {
			$this->view->placeholder('pageTitle')->set($this->view->translate('TRANS_RESELLER_EDIT_PROFILE', array('NAME' => billing_safetyhtml($reseller->fullName))));
		} else {
			$this->view->placeholder('pageTitle')->set($this->view->translate('TRANS_RESELLER_CREATE'));
		}
		
		if ($this->_request->isPost()) {
			try {
				if (!$form->isValid($this->_request->getPost())) {
					throw new ProductException(ProductException::E_FAIL_OPERATION, $this->_translator->translate('TRANS_RESELLER_PROFILE_INVALID'));
				}
				$form->process();
				if ($isReseller) {
					$message = 'TRANS_RESELLER_EDIT_PROFILE_OWN_SUCCESS';
				} else {
					$message = $resellerId ? 'TRANS_RESELLER_EDIT_PROFILE_SUCCESS' : 'TRANS_RESELLER_CREATE_SUCCESS';
				}
				$this->_redirectWithMessage(
					$isReseller ? $this->view->actionUrl('dashboard', 'ShowDashboard') : $this->view->actionUrl('resellers', 'ShowResellers'),
					$this->view->translate($message, array('NAME' => $reseller->fullName))
				);
			} catch (ProductException $exception) {
				$this->_status->addError($exception->getMessage());
			}
		}
		
		$this->view->form = $form;
	}
	
}