<?php namespace NetSTI\System\Controllers;

use Lang;
use Flash;
use BackendMenu;
use Backend\Classes\Controller;
use NetSTI\System\Models\Contact;
use NetSTI\System\Models\Inbox as InboxModel;

class Inbox extends Controller{
	public $implement = [
		'Backend.Behaviors.FormController',
		'Backend.Behaviors.ListController',
	];

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

	public $requiredPermissions = ['netsti.system.conections.inbox'];

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

		BackendMenu::setContext('NetSTI.System', 'conections', 'inbox');
	}

	public function index_onArchive(){
		if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

			foreach ($checkedIds as $itemId) {
				if (!$item = InboxModel::find($itemId))
					continue;

				$item->ready = 1;
				$item->save();
			}

			Flash::success(Lang::get('netsti.system::lang.inbox.archive_msj'));
		} else {
			Flash::error(Lang::get('netsti.system::lang.inbox.archive_error'));
		}

		return $this->listRefresh();
	}

	public function index_onConvert(){
		if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

			foreach ($checkedIds as $itemId) {
				if (!$item = InboxModel::find($itemId))
					continue;

				$contact = new Contact();
				$contact->name = $item->name;
				$contact->email = $item->email;
				$contact->phone = $item->phone;
				$contact->company = $item->company;
				$contact->save();

				$item->ready = 1;
				$item->save();
			}

			Flash::success(Lang::get('netsti.system::lang.inbox.convert_msj'));
		} else {
			Flash::error(Lang::get('netsti.system::lang.inbox.convert_error'));
		}

		return $this->listRefresh();
	}
}