<?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_2 as emails FROM users WHERE enddate IS NULL
				UNION SELECT email FROM emails WHERE email IS NOT NULL AND email != '' AND enddate IS NULL
				UNION SELECT email_1 FROM contacts WHERE email_1 IS NOT NULL AND email_1 != ''
				UNION SELECT email_2 FROM contacts WHERE email_2 IS NOT NULL AND email_2 != ''";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['emails'] = array_column($results, '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);		
	}
}