<?php

class ControllerExtensionModuleAffClassicCommissionToCredits extends Controller {
	public function index() {
		if (!$this->customer->isLogged()) {
			$this->session->data['redirect'] = $this->url->link('account/account', '', true);
			$this->response->redirect($this->url->link('account/login', '', true));
		}
		
		if(!$this->config->get('module_aff_classic_status') || !$this->config->get('module_aff_classic_commission_to_credits') || $this->config->get('module_aff_classic_commission_to_credits') > 0 || !isset($this->request->post['amount'])) $this->response->redirect($this->url->link('error/not_found', '', true));
		
		$this->load->language('affiliate/aff_classic');
		$customer_id = $this->customer->isLogged();
		
		$amount = str_replace(',', '.', preg_replace("/[\n\r\s]+/", '', trim($this->request->post['amount'])));	
		if(preg_match("/^\d+(?:\.\d+)?$/", $this->request->post['amount'])) {
			if($this->session->data['currency'] != $this->config->get('config_currency')) $amount = $this->currency->convert($amount, $this->session->data['currency'], $this->config->get('config_currency'));
			$this->load->model('extension/aff_classic');
			$balance = $this->model_extension_aff_classic->getTransactionTotal($customer_id);
			if(($amount - $balance) < 0.01) {
				if(abs($amount - $balance) < 0.01) $amount = $balance;
				$aff_amount = round(floatval($amount) * 10000) * 0.0001;
				if($this->model_extension_aff_classic->transferToCredits($customer_id, $aff_amount)) $this->session->data['funds_transfer_success'] = $this->language->get('text_funds_transfer_success');
			}
		}
		if(!isset($this->session->data['funds_transfer_success'])) $this->session->data['funds_transfer_error'] = $this->language->get('error_invalid_transfer_amount');
		$this->response->redirect($this->url->link('account/transaction', '', true));
	}
	
}