<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Emails extends Controller {

	protected $helper = ['form'];
	
	public function index() {
		$db = \Config\Database::connect();
		$sql = "select emailid, email, enddate from emails";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['emails'] = $results;
		return view('emails_index', $data);
	}

	public function edit($emailid = null) {
		$db = \Config\Database::connect();
		$data = array();
		if($emailid != 0) {
			$sql = "select * from emails where emailid='$emailid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['emails'] = $results;
		}
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'emailid' => 'required',
				'email' => 'required'
			];
			$emailid = $this->request->getVar('emailid');
			$email = $this->request->getVar('email');
			if($this->validate($rules)){
				if($emailid == 0) {
					$sql = "insert into emails(email, enddate) values ('$email', null)";
					if($db->query($sql)) { return view('form_success'); } 
					else { return view('form_fail'); }
				} else {
					$sql = "update emails set email='$email' where emailid='$emailid'";
					if($db->query($sql)) { return view('form_success', $data); } 
					else { return view('form_fail'); }
				}
			} else {
				$data['validation'] = $this->validator;
				return view('emails_editor',$data);
			}
		}
		return view('emails_editor', $data);
	}
	
	public function toggle($emailid = null) {
		$db = \Config\Database::connect();
		$sql = "update emails set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where emailid='$emailid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
}