<?php

namespace App\Controllers;

use App\Models\ProductAliasModel;
use CodeIgniter\Controller;

class ProductAlias extends Controller {

	public function index() {
		$db = \Config\Database::connect();
		$data = array();
		if ($this->request->getMethod() === 'POST') {
			$productaliastext = $this->request->getVar('productaliastext');
			$sql = "SELECT * FROM productalias where lower(productaliastext) like '%$productaliastext%'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['productalias'] = $results;
		}
		return view('productalias_index', $data);
	}

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