<?php

namespace App\Controllers;

use App\Models\CategoriesModel;
use App\Entities\Category;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Database\Exceptions\DatabaseException;

class Categories extends BaseController
{
    private CategoriesModel $model;

    public function __construct()
    {
        $this->model = new CategoriesModel;
    }
    
    public function index(): string
    {
        
        $data = $this->model
        ->select(("categories.*, users.username"))
        ->join("users","users.id = categories.users_id","left")
        ->findAll();

        return view("Categories/index",[
                "categories" => $data
            ]);
    }
 
    public function show($id)
    {
		$sql = "SELECT recipes.RecipeID, recipes.RecipeName FROM recipes WHERE recipes.CategoryID=$id";
		$db = db_connect();
		$recipes = $db->query($sql)->getResult('App\Entities\Input');

        $category = $this->getCategoryOr404($id);
        return view("Categories/show",[
            "category" => $category,
            "recipes" => $recipes
        ]);

    }

    public function new()
    {
		if (! auth()->user()->can_edit_by_controller( substr(strrchr(__CLASS__, '\\'), 1) ) ) {
			return redirect()->to( strtolower(substr(strrchr(__CLASS__, '\\'), 1)) );
		}
        $category = new Category;
        $category->HeaderColour = '#5B9BD5';
        $category->BodyColour = '#DDEBF7';
        $category->FooterColour = '#B4C6E7';

        return view("Categories/new",[
            "category" => $category
        ]);
    }

    public function create()
    {

        $category = new Category($this->request->getPost());
//dd($certification);
        $id = $this->model->insert($category);

        if($id === false){

            return redirect()->back()->with("errors", $this->model->errors())->withInput();

        }

        return redirect()->to("categories/$id")->with("message","Category saved.");

    }

    public function edit($id,$returnto = null)
    {

		if (! auth()->user()->can_edit_by_controller( substr(strrchr(__CLASS__, '\\'), 1) ) ) {
			return redirect()->to( strtolower(substr(strrchr(__CLASS__, '\\'), 1))."/$id" );
		}

        $category = $this->getCategoryOr404($id);
    
        if($returnto == null || empty($returnto)){
            $ret = previous_url();
        }else{
            $ret = $returnto;
        }

        return view("Categories/edit",[
            "category" => $category,
            "returnto" => $ret
        ]);

    }

    public function update($id,$returnto)
    {

        $category = $this->getCategoryOr404($id);

        $category->fill($this->request->getPost());

        $category->__unset("_method");

        if(!$category->hasChanged()){
            return redirect()->back()->with("message","Nothing to update.");
        }

        if($this->model->save($category)){
            if($returnto == '0'){
                return redirect()->to("categories/$id")->with("message","Category updated");
            }else{
                if($returnto == '1'){
                    return redirect()->to("pricelist/0");
                }else{
                    return redirect()->to("pricelist/1");
                }
            }
        }

        return redirect()->back()->with("errors",$this->model->errors())->withInput();
    }

    public function confirmDelete($id)
    {
		if (! auth()->user()->can_edit_by_controller( substr(strrchr(__CLASS__, '\\'), 1) ) ) {
			return redirect()->to( strtolower(substr(strrchr(__CLASS__, '\\'), 1))."/$id" );
		}

		
        $category = $this->getCategoryOr404($id);

        return view("Categories/delete",[
            "category"=>$category
        ]);
    }
    public function delete($id)
    {
        try{
			if (! auth()->user()->can_edit_by_controller( substr(strrchr(__CLASS__, '\\'), 1) ) ) {
				return redirect()->to( strtolower(substr(strrchr(__CLASS__, '\\'), 1))."/$id" );
			}
			$category = $this->getCategoryOr404($id);
            $this->model->delete($id);

        } catch (DatabaseException $e) {
            //$error = $db->error();
            return redirect()->back()->with("errors",$this->model->errors())->withInput();
        }
        return redirect()->to("categories")->with("message","Category deleted.");
    }

    private function getCategoryOr404($id): Category
    {
        $category = $this->model->find($id);

        if($category === null){
            throw new PageNotFoundException("Category with id $id not found");
        }

        return $category;
    }
}
