<?php

namespace App\Controllers;

use App\Models\TemplateInputsModel;
use App\Models\TemplatesModel;
use App\Models\InputsModel;

use App\Entities\TemplateInput;
use App\Entities\Template;
use App\Entities\Input;

use CodeIgniter\Database\Exceptions\DatabaseException;

use CodeIgniter\Exceptions\PageNotFoundException;

class Templateinputs extends BaseController
{
    private TemplateInputsModel $model;
    private TemplatesModel $templatesmodel;
    private InputsModel $inputsmodel;

    public function __construct()
    {
        $this->model = new TemplateInputsModel;
        $this->templatesmodel = new TemplatesModel;
        $this->inputsmodel = new InputsModel;
    }
    
    public function create($templateid)
    {
        $templateinput = new TemplateInput($this->request->getPost());
//        dd($templateinput);
//        $inputid = $templateinput->InputID;
        $templateinput->TemplateID = $templateid;
        // $input = $this->getInputOr404($inputid);
        // $iscoffee = $input->IsCoffee;


        // $qty = $recipeinput->Qty;

        // $recipe = $this->getRecipeOr404($recipeid);
        // $wastepercent = $recipe->WastePercent;
        // $packqty = (int)$recipe->PackQty;

        // $qtys = $this->getQtyTotalOr404($recipeid);
        // $qtytotal = (int)$qtys->QtyTotal;
        // $qtyinc = (int)($packqty * (1+($wastepercent/100)));
        // $qtyleft = (int)($qtyinc  - $qtytotal);

        // if ($iscoffee == 1){
        //     //dd($qty, $qtyleft);
        //     if($qty > $qtyleft){
        //         //$errors = [];
        //         if($qtyleft > 0){
        //         $errors = ["Qty" => "Total exceeds Finished Weight of <b>$qtyinc</b>g taking into account $wastepercent% Production Wastage<br/>
        //         The maximum of this Input you can add is <b>$qtyleft</b>g"];
        //         }else{
        //             $errors = ["Qty" => "Total exceeds Finished Weight of <b>$qtyinc</b>g taking into account $wastepercent% Production Wastage<br/>
        //             The finished weight has already been reached."];
        //         }
        //         // (New Final Weight would be $newqty g - Required Final Weight is $packqty g)<br/>

        //         //dd($errors);
        //         return redirect()->back()->with("errors", $errors)->withInput();
        //     }
        //     $qtytogo = $qtyinc - ($qtytotal + $qty);
        // }
//        dd($templateinput);
        $id = $this->model->insert($templateinput);

        if($id === false){
            return redirect()->back()->with("errors", $this->model->errors())->withInput();
        }

        $tem = $this->getTemplateRecOr404($templateid);
        $tem->users_id = auth()->getUser()->id;
        $this->templatesmodel->save($tem);

        $msg = "Added succesfully."; // - {$qtytogo}g to go";
        
        return redirect()
            ->to("templates/$templateid")
            ->with("inputmessage", $msg);

    }

    public function createWithInputWaste($templateid)
    {
   
        $templateinput = new TemplateInput($this->request->getPost());
        $templateinput->TemplateID = $templateid;
        $qty = $templateinput->Qty;
        $inputid = $templateinput->InputID;
        $input = $this->getInputOr404($inputid);
        $wastepercent = $input->WastePercent;

        // This the proportion of the new input qty that contributes to the final weight (PackQty)
        // 120g with waste of 20% contributes 100g to final weight
        // $qtyfinal = ceil($qty / (1 + ($wastepercent/100)));

        // $row = $this->getQtyLeftOr404($recipeid);
        // $qtytotal = (int)$row->QtyTotal;
        // $packqty = (int)$row->PackQty;
        // $newqty = $qtytotal + $qtyfinal;

        // $qtyleft = (int)(($packqty - $qtytotal) * (1 + ($wastepercent/100)));

        // if($qtytotal + $qtyfinal > $packqty){
        //     //$errors = [];
        //     $errors = ["Qty" => "Total exceeds Finished Weight after taking into account Production Wastage<br/>
        //     The maximum of this Input you can add is <b>$qtyleft</b>g taking into $wastepercent% production wastage"];

        //     // (New Final Weight would be $newqty g - Required Final Weight is $packqty g)<br/>

        //     //dd($errors);
        //     return redirect()->back()->with("errors", $errors)->withInput();
        // }

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

        if($id === false){
            //dd($this->model->errors());
            return redirect()->back()->with("errors", $this->model->errors())->withInput();
        }

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

    }

//     private function getQtyLeftOr404($id): object
//     {

//         $row = $this->model->query("SELECT recipes.PackQty, 
//         SUM(recipeinputs.Qty / (1 + (inputs.WastePercent/100))) AS QtyTotal,
//         SUM(recipeinputs.Qty) as QtySum
//  FROM recipeinputs
//  LEFT JOIN recipes ON recipeinputs.RecipeID=recipes.RecipeID
//  LEFT JOIN inputs ON recipeinputs.InputID=inputs.InputID
//  LEFT JOIN inputtypes ON inputs.InputTypeID=inputtypes.InputTypeID
//  WHERE ifnull(inputtypes.IsCoffee,0) = 1
//  AND recipeinputs.RecipeID=?",[$id])->getRow();

//         if($row === null){
//             throw new PageNotFoundException("Recipe with id $id not found or Qty = null");
//         }
// //dd($row);
// //dd($qtyleft);
//         return $row;
//     }

    private function getInputOr404($inputid): Input
    {
        $input = $this->inputsmodel
        ->select('inputs.*, inputtypes.IsCoffee')
        ->join('inputtypes','inputs.InputTypeID=inputtypes.InputTypeID',"left")
        ->find($inputid);

        if($input === null){
            throw new PageNotFoundException("Input with id $inputid not found");
        }

        return $input;
    }
    
    // private function getRecipeOr404($recipeid): object
    // {
    //     $row = $this->model->query("SELECT recipes.PackQty, 
    //     recipes.WastePercent
    // FROM recipes
    // WHERE recipes.RecipeID=?",[$recipeid])->getRow();

    //     if($row === null){
    //         throw new PageNotFoundException("Recipe with id $recipeid not found or Qty = null");
    //     }

    //     return $row;
    // }

    private function getQtyTotalOr404($templateid): object
    {
        $row = $this->model->query("SELECT
        ifnull(SUM(templateinputs.Qty),0) as QtyTotal
 FROM templateinputs
  LEFT JOIN inputs ON templateinputs.InputID=inputs.InputID
 LEFT JOIN inputtypes ON inputs.InputTypeID=inputtypes.InputTypeID
 WHERE ifnull(inputtypes.IsCoffee,0) = 1
 AND templateinputs.TemplateID=?",[$templateid])->getRow();

        if($row === null){
            throw new PageNotFoundException("Template with id $templateid not found or Qty = null");
        }

        return $row;
    }


    public function delete($templateid, $id)
    {
        try{
            $this->model->delete($id);

            $rec = $this->getTemplateRecOr404($templateid);
            $rec->users_id = auth()->getUser()->id;
            $this->templatesmodel->save($rec);
    
        } catch (DatabaseException $e) {
            return redirect()->back()->with("errors",$this->model->errors())->withInput();
        }
        return redirect()
            ->to("templates/$templateid")
            ->with("inputmessage","Input deleted.");

    }

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

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

        return $template;
    }

}
