<?php

namespace App\Controllers;

use App\Models\ProductTypeModel;
use CodeIgniter\Controller;

class ProductType extends Controller {

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

	public function create() {
		$db = \Config\Database::connect();
		$data = array();
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'texts' => 'required'
			];
			$data['new_value'] = [
				'texts' => $this->request->getVar('texts')
			];
			if($this->validate($rules)){
				$productTypeModel = new ProductTypeModel();
				$productTypeModel->set('createdate', 'NOW()', FALSE);
				$productTypeModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('producttype_create',$data);
			}
		}
		return view('producttype_create', $data);
	}
	
	public function edit($producttypeid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM producttype WHERE producttypeid='$producttypeid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['producttype'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'texts' => 'required'
			];
			$data['new_value'] = [
				'texts' => $this->request->getVar('texts')
			];
			if($this->validate($rules)){
				$productTypeModel = new ProductTypeModel();
				$productTypeModel->update($producttypeid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('producttype_edit',$data);
			}
		}
		return view('producttype_edit', $data);
	}
}