<?php namespace NetSTI\System\Controllers;

use PDF;
use Mail;
use Lang;
use Flash;
use Storage;
use BackendMenu;
use Backend\Classes\Controller;
use NetSTI\System\Models\Invoice;
use NetSTI\System\Models\CompanySettings;
use NetSTI\System\Models\PaymentsSettings;

class Invoices extends Controller{
	public $implement = [
		'Backend.Behaviors.FormController',
		'Backend.Behaviors.ListController',
		'Backend.Behaviors.RelationController',
		'Owl.Behaviors.ListDelete.Behavior',
	];

	public $formConfig = 'config_form.yaml';
	public $listConfig = 'config_list.yaml';
	public $relationConfig = 'config_relation.yaml';

	public $requiredPermissions = ['netsti.system.accounting.invoices'];

	public function __construct(){
		parent::__construct();

		BackendMenu::setContext('NetSTI.System', 'accounting', 'invoices');
	}

	public function getDataPrint($id){
		return array(
			"document" => Invoice::find($id),
			"settings" => PaymentsSettings::instance(),
			"company"  => CompanySettings::instance(),
			"currency"  => PaymentsSettings::getCurrencyData(),
			"labels" => [
				"email" => Lang::get("netsti.system::lang.contacts.email"),
				"tel" => Lang::get("netsti.system::lang.contacts.phone"),
				"estimate" => Lang::get("netsti.system::lang.estimates.title"),
				"for" => Lang::get("netsti.system::lang.estimates.for"),
				"to" => Lang::get("netsti.system::lang.estimates.to"),
				"date" => Lang::get("netsti.system::lang.estimates.date"),
				"range" => Lang::get("netsti.system::lang.estimates.range"),
				"date_limit" => Lang::get("netsti.system::lang.estimates.date_limit"),
				"by" => Lang::get("netsti.system::lang.estimates.by"),
				"products" => Lang::get("netsti.system::lang.products.plural"),
				"discount" => Lang::get("netsti.system::lang.estimates.discount"),
				"quantity" => Lang::get("netsti.system::lang.products.quantity"),
				"tax" => Lang::get("netsti.system::lang.estimates.tax"),
				"price" => Lang::get("netsti.system::lang.products.price"),
				"total" => Lang::get("netsti.system::lang.products.total"),
				"note" => Lang::get("netsti.system::lang.estimates.note"),
			]
		);
	}

	public function pdf($id){
		try{
			$pdf = PDF::loadView('netsti.system::pdf.simple_invoice', $this->getDataPrint($id));
			return $pdf->stream();
		} catch (Exception $e){
			Flash::error($e->getMessage());
		}
	}

	public function preview_onMail($id){
		ini_set('max_execution_time', 360);
		if($inv = Invoice::find($id)){
			$data = array(
				'to' => $inv->contact->email,
				'name' => $inv->contact->name,
				'subject' => 'Estimate '.$inv->label_nid
			);

			$pdf = PDF::loadView('netsti.system::pdf.simple_invoice', $this->getDataPrint($id));

			Storage::disk('local')->put('estimate.pdf', $pdf->stream());

			Mail::send('netsti.system::mail.estimate', $this->getDataPrint($id), function($message) use ($data){
				$message->to($data['to'], $data['name']);
				$message->attach(storage_path('app/estimate.pdf'));
			});

			Flash::success(Lang::get('netsti.system::lang.invoices.send_success'));
		}else
			Flash::error(Lang::get('netsti.system::lang.invoices.send_error'));
	}

	public function index(){
		$actualMonth = date('m');
		$lastMonth = date('m')==1 ? 12 : date('m')-1;
		$this->vars['thisMonth'] = Invoice::getMonthAmount($actualMonth);
		$this->vars['lastMonth'] = Invoice::getMonthAmount($lastMonth);

		$this->asExtension('ListController')->index();
	}
	
	public function totalUpdate($id){
		$inv = Invoice::find($id);
		$inv->saveTotal();
		$inv->save();
	}

	public function debitUpdate($id){
		$inv = Invoice::find($id);
		$inv->setPayments();
		$inv->savePaid();

		if($inv->total_paid == $inv->total){
			$inv->status = 2;
			Flash::success(Lang::get('netsti.system::lang.invoices.paid_success'));
		}

		$inv->save();
		return true;
	}

	public function preview_onApprove($id){
		if($inv = Invoice::find($id)){
			$inv->status = 1;
			$inv->save();

			Flash::success(Lang::get('netsti.system::lang.invoices.approved_success'));
		}else
			Flash::error(Lang::get('netsti.system::lang.invoices.approved_error'));
	}

	public function preview_onVoid($id){
		if($inv = Invoice::find($id)){
			$inv->status = 3;
			$inv->save();

			Flash::success(Lang::get('netsti.system::lang.invoices.void_success'));
		}else
			Flash::error(Lang::get('netsti.system::lang.invoices.void_error'));
	}
}
