<?php

namespace App\Controllers;

use App\Models\VendorsModel;
use CodeIgniter\Controller;

class Vendors extends Controller {

	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM vendors";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['vendors'] = $results;
		return view('vendors_index', $data);
	}

	public function edit($vendorid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM vendors WHERE vendorid='$vendorid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['vendors'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'vendorid' => 'required',
				'vendorname' => 'required',
				'initial' => 'required',
				'principal' => 'required',
			];
			$data['new_value'] = [
				'vendorid' => $this->request->getVar('vendorid'),
				'vendorname' => $this->request->getVar('vendorname'),
				'initial'  => $this->request->getVar('initial'),
				'principal'  => $this->request->getVar('principal'),
				'email_1'  => $this->request->getVar('email_1'),
				'email_2'  => $this->request->getVar('email_2'),
				'phone'  => $this->request->getVar('phone'),
				'website'  => $this->request->getVar('website')
			];
			if($this->validate($rules)){
				$vendorsModel = new VendorsModel();
				$vendorsModel->update($vendorid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('vendors_edit',$data);
			}
		}
		return view('vendors_edit', $data);
	}
	
	public function create() {
		$db = \Config\Database::connect();
		$data = array();
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'vendorname' => 'required',
				'initial' => 'required',
				'principal' => 'required',
			];
			$data['new_value'] = [
				'vendorname' => $this->request->getVar('vendorname'),
				'initial'  => $this->request->getVar('initial'),
				'principal'  => $this->request->getVar('principal'),
				'email_1'  => $this->request->getVar('email_1'),
				'email_2'  => $this->request->getVar('email_2'),
				'phone'  => $this->request->getVar('phone'),
				'website'  => $this->request->getVar('website')
			];
			if($this->validate($rules)){
				$vendorsModel = new VendorsModel();
				$vendorsModel->set('createdate', 'NOW()', FALSE);
				$vendorsModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('vendors_create',$data);
			}
		}
		return view('vendors_create', $data);
	}
	
	public function toggle($vendorid = 0) {
		$db = \Config\Database::connect();
		$sql = "update vendors set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where vendorid='$vendorid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
}