<?php

class FormEdit_Admin extends Controller {
	
	protected $model_formedit;
		
	public function __construct() {
		parent::__construct(dirname(__DIR__));
		hook_add('form.field.list', [ $this, 'CustomFields' ]);
		$this->model_formedit = $this->LoadModel('formedit_model');
	}
	
	public function __Register() {
		$this->RegisterView(__CLASS__ .'::forms', ['formedit_view' => ['formedit_selection', 'formedit_detail', 'formedit_general', 'formedit_fields', 'formedit_preview', 'formedit_notification']]);
	}
	
	public function CustomFields($rep) {
		
		$rep->pagesize(25)
			->AutoWidth(FALSE);

		$col = $rep->AddColumn();
		$col->name('id')
			->caption('ID')
			->Width(80)
			->Source(function($item) {
				[ $category, $id ] = explode(':', $item->cfg_hash);
				return $id;
			});

		$col = $rep->AddColumn();
		$col->name('title')
			->caption('Title')
			->Source(function($item) {
				$payload = unserialize($item->cfg_text);
				return $payload['title'] ?? '(untitled)';
			})
			->Render(function($value, $item) {
				[ $category, $id ] = explode(':', $item->cfg_hash);
				$auth = hook_execute('nonce.create', FALSE, 'formedit', $id, 1800);
				$dvalue = htmlspecialchars($value);
				return "<a href=\"/admin/forms/{$id}?auth={$auth}\">$dvalue</a>";
			});

	}
	
	
	/** staff */
	public function forms($action = '', $id = '') {		// this cannot be called "form"
		$res = $this->DefaultResult(__METHOD__);
		$addCSS = FALSE;
		
		switch($action) {
			
			case 'general':
				$res['auth'] = hook_execute('nonce.create', FALSE, 'formedit', $id, 1800);
				$res['template'] = 'formedit_general';
				$res['fieldlist'] = [
					[
						'name' => 'title',
						'type' => 'string',
						'caption' => 'Title',
					], [
						'name' => 'redirect',
						'type' => 'string',
						'caption' => 'Redirect URL',
					], [
						'name' => 'focus',
						'type' => 'boolean',
						'caption' => 'Set focus to first field',
					],
				];
				if ($id != 'new') {
					$this->model_formedit->FormId($id);
					$res['title'] = $this->model_formedit->Title();
					$res['redirect'] = $this->model_formedit->Redirect();
					$res['focus'] = $this->model_formedit->Focus();
				}
				
				break;
			case 'fields':
				$res['auth'] = hook_execute('nonce.create', FALSE, 'formedit', $id, 1800);
				$res['template'] = 'formedit_fields';
				$this->model_formedit->FormId($id);
				$res['available'] = $this->model_formedit->fieldsAvailable();
				$res['used'] = $this->model_formedit->fieldsUsed();
				break;
			case 'preview':
				$res['auth'] = hook_execute('nonce.create', FALSE, 'formedit', $id, 1800);
				$res['template'] = 'formedit_preview';
				break;
			case 'notification':
				$res['auth'] = hook_execute('nonce.create', FALSE, 'formedit', $id, 1800);
				$res['template'] = 'formedit_notification';
				$res['fieldlist'] = [
					[
						'name' => 'sender',
						'type' => 'string',
						'caption' => 'Sender',
					], [
						'name' => 'recipient',
						'type' => 'string',
						'caption' => 'Recipient(s)',
					], [
						'name' => 'subject',
						'type' => 'string',
						'caption' => 'Subject',
					], [
						'name' => 'emailbody',			// 'body' is reserved
						'type' => 'text',
						'caption' => 'Body',
						'class'	  => 'body-field',
					],
				];
				$this->model_formedit->FormId($id);
				$res['sender'] = $this->model_formedit->Sender();
				$res['recipient'] = $this->model_formedit->Recipient();
				$res['subject'] = $this->model_formedit->Subject();
				$res['emailbody'] = $this->model_formedit->Body();
				break;
			case 'responses':
				$res['body'] = 'responses';
				break;
					
			case 'list':
				$rep = new ReportObject;
				hook_execute('form.field.list', $rep);
				return $this->model_formedit->formsList($rep);
				
			case '':
				$auth = hook_execute('nonce.create', FALSE, 'formedit', 'new', 1800);
				$res['newauth'] = $auth;
				$res['template'] = 'formedit_selection';
				$rep = new ReportObject;
				hook_execute('form.field.list', $rep);
				$rep->asDataTablesDefinition($res);
				break;
			
			case 'new':
				$addCSS = TRUE;
				$res['template'] = 'formedit_detail';
				$res['page_title'] = 'Form — New';
				break;
			
			default:
				$id = $action;
				$addCSS = TRUE;
				$this->model_formedit->FormId($id);
				$res['template'] = 'formedit_detail';
				$res['page_title'] = 'Form — ' . $this->model_formedit->Title();
				break;

		}
		if ($addCSS) {
			$base = $this->StaticUriModule(__DIR__);
			$this->IncludeFile("$base/formedit.js")
					->Depends('jquery');
			$this->IncludeFile("$base/formedit.css");
		}

		return $res;
	}

/** staff */
	public function forms_POST() {
		$id = hook_execute( 'nonce.verify', FALSE, 'formedit', FALSE, $this->post('auth', '') );
		if ($id === FALSE) {
			return [
				'result' => 6682,
				'message' => 'You are not permitted to access this function',
			];
		}
		$action = $this->post('action', '');
		switch($action) {
			case 'set-general':
				// save
				$this->model_formedit
					->FormId($id)
					->Title($this->post('title', ''))
					->Redirect($this->post('redirect', ''))
					->Focus((int) $this->post('focus', '0'))
					->SaveRecord();
				
				if ($id == 'new') {
					$id = $this->model_formedit->FormId();
					$res['redirect'] = '/admin/forms/' . $id . '#general';
				} else {
					$res = [
						'result'	=> -9999,
						'message'	=> 'Form updated.',
					];
				}
				break;
				
			case 'set-fields':
 				$this->model_formedit
					->FormId($id)
					->Fields(trim($this->post('fields', '')))
					->SaveRecord();
				$res = [
					'result'	=> -9999,
					'message'	=> 'Form updated.',
				];
				break;

			case 'get-default':
				$this->__loadView('formedit_view');
 				$this->model_formedit
					->FormId($id);
				$param = [
					'present_general' => $this->post('present_general', '0'),
					'present_fields'  => $this->post('present_fields', '0'),
					'title' 		  => $this->post('title', ''),
					'fields' 		  => trim($this->post('fields', '')),
				];
				if ($param['present_fields'])   $this->model_formedit->Fields($param['fields']);		// not saved
				if ($param['present_general'])  $this->model_formedit->Title($param['title']);		// not saved
				$html = $this->model_formedit->AsPreview();
				die($html);

			case 'set-preview':
 				$this->model_formedit
					->FormId($id)
					->setDefaultValues($_POST)
					->SaveRecord();
				$res = [
					'result'	=> -9999,
					'message'	=> 'Default values for this form have been set.',
				];
				break;
				
			case 'set-notification':
 				$this->model_formedit
					->FormId($id)
					->Sender(trim($this->post('sender', '')))
					->Recipient(trim($this->post('recipient', '')))
					->Subject(trim($this->post('subject', '')))
					->Body(trim($this->post('emailbody', '')))
					->SaveRecord();
				$res = [
					'result'	=> -9999,
					'message'	=> 'Form updated.',
				];
				break;
				
			default:
				$res = [
					'result' => 59822,
					'message' => 'Unsupported form function',
				];
				break;
 		}
		return $res;
	}

}