<?php

namespace App\Controllers;

use App\Models\MailgroupsModel;
use CodeIgniter\Controller;

class Mailgroups extends BaseController {
	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM mailgroups";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['mailgroups'] = $results;
		return view('mailgroups_index', $data);
	}
	
	public function edit($mailgroupid=null) {
		$db = \Config\Database::connect();
		$data['emails'] = array();
		if($mailgroupid != 0) {
			$sql = "select * from mailgroups where mailgroupid='$mailgroupid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['mailgroups'] = $results;
		}
		$sql = "SELECT email_1 FROM users WHERE `enddate` IS NULL UNION SELECT email_2 FROM users WHERE `enddate` IS NULL";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		foreach($results as $email) { array_push( $data['emails'], $email['email_1']); }
		$sql = "SELECT email_1 FROM contacts WHERE enddate IS NULL UNION SELECT email_2 FROM contacts WHERE enddate IS NULL;";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		foreach($results as $email) { array_push( $data['emails'], $email['email_1']); }
		$data['emails'] = array_unique($data['emails']);
		$data['emails'] = array_filter($data['emails']);
		//print_r($data['emails']);
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'mailgroupname' => 'required',
				'mailgrouptext' => 'required',
			];
			$mailgrouptext = $this->request->getVar('mailgrouptext');
			$mailgrouptext = implode(",",$mailgrouptext);
			$data['new_value'] = [
				'mailgroupname' => $this->request->getVar('mailgroupname'),
				'mailgrouptext'  => $mailgrouptext,
			];
			if($mailgroupid != 0) {
				if($this->validate($rules)){
					$mailgroupsModel = new MailgroupsModel();
					$mailgroupsModel->update($mailgroupid, $data['new_value']);
					return view('form_success');
					//return view('mailgroups_edit',$data);
				} else {
					$data['validation'] = $this->validator;
					return view('mailgroups_edit',$data);
				}
			} else {
				if($this->validate($rules)){
					$mailgroupsModel= new MailgroupsModel();
					$mailgroupsModel->set('createdate', 'NOW()', FALSE);
					$mailgroupsModel->insert($data['new_value']);
					return view('form_success');
					//return view('mailgroups_edit',$data);
				} else {
					$data['validation'] = $this->validator;
					return view('mailgroups_edit',$data);
				}
			}
		}
		return view('mailgroups_edit', $data);		
	}
}