<?php

namespace App\Controllers;

use App\Models\TemplatesModel;
use App\Entities\Template;

use App\Models\InputsModel;

use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Database\Exceptions\DatabaseException;

class Templates extends BaseController
{
    private TemplatesModel $model;
    private InputsModel $inputsmodel;

    public function __construct()
    {
        $this->model = new TemplatesModel;
        $this->inputsmodel = new InputsModel;
    }
    
    public function index(): string
    {
        
        $data = $this->model
        ->select(("templates.*, users.username"))
        ->join("users","users.id = templates.users_id","left")
        ->orderBy('TemplateName','asc')->findAll();

        return view("Templates/index",[
                "templates" => $data
            ]);
    }
 
    public function show($id)
    {

        $template = $this->getTemplateOr404($id);
        $templateinputs = $this->getTemplateInputsOr404($id,1);        
        $inputs = $this->getInputs();
        return view("Templates/show",[
            "template" => $template,
            "templateinputs" => $templateinputs,
            "inputs" => $inputs
        ]);

    }


    public function new()
    {
		if (! auth()->user()->can_edit_by_controller( substr(strrchr(__CLASS__, '\\'), 1) ) ) {
			return redirect()->to( strtolower(substr(strrchr(__CLASS__, '\\'), 1)) );
		}

        return view("Templates/new",[
            "template" => new Template
        ]);
    }

    public function create()
    {

        $template = new Template($this->request->getPost());

        $id = $this->model->insert($template);

        if($id === false){

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

        }

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

    }

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

        $template = $this->getTemplateOr404($id);

        return view("Templates/edit",[
            "template" => $template
        ]);

    }


    public function update($id)
    {

        $template = $this->getTemplateOr404($id);

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

        $template->__unset("_method");

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

        if($this->model->save($template)){
            return redirect()->to("templates/$id")->with("message","Template updated");
        }

        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" );
		}

        $template = $this->getTemplateOr404($id);

        return view("Templates/delete",[
            "template"=>$template
        ]);
    }
    public function delete($id)
    {
        try{
            $this->model->delete($id);

        } catch (DatabaseException $e) {
            return redirect()->back()->with("errors",$this->model->errors())->withInput();
        }
        return redirect()->to("templates")->with("message","Template deleted.");
    }

    private function getTemplateOr404($id): Template
    {
        $template = $this->model->find($id);

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

        return $template;
    }

    private function getTemplateInputsOr404($id): array
    {
        $data = $this->model->query("SELECT templateinputs.TemplateID,
        templateinputs.TemplateInputID,
        templateinputs.Qty,
        inputs.InputTypeID,inputs.InputName, inputs.Cost, 
        certifications.Certification,
        inputtypes.InputType,
        inputtypes.IsCoffee,
        round((inputs.Cost * templateinputs.Qty)/ifnull(inputs.ConversionFactor,1),2) as InputCost
        FROM templateinputs
        LEFT JOIN inputs on templateinputs.InputID=inputs.InputID
        LEFT JOIN inputtypes on inputs.InputTypeID=inputtypes.InputTypeID
        LEFT JOIN certifications on inputs.CertificationID=certifications.CertificationID
        WHERE templateinputs.TemplateID=?
        ORDER By inputtypes.DisplayOrder, inputs.InputName",[$id])->getResult(\App\Entities\RecipeInput::class);

        // if($recipes === null || count($recipes) === 0){
        //     throw new PageNotFoundException("Recipe with id $id not found");
        // }

        return $data;
    }

    private function getInputs(): array
    {
        $inputs = $this->inputsmodel->query("SELECT inputs.InputID, inputs.InputName,
        inputs.InputTypeID, inputtypes.InputType
        FROM inputs
        LEFT JOIN inputtypes on inputs.InputTypeID=inputtypes.InputTypeID
        ORDER By inputs.InputTypeID, inputs.InputName")->getResult(\App\Entities\Input::class);

        return $inputs;
    }

}
