<?php

namespace App\Controllers;

use App\Entities\GreenCoffeeEntity;
use App\Models\GreenCoffeesModel;

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

class GreenCoffees extends BaseController
{
    private GreenCoffeesModel $model;

    public function __construct()
    {
        $this->model = new GreenCoffeesModel;
    }

    public function index(): string
    {
        $sql = "select greencoffees.*, users.username from greencoffees left join users on greencoffees.users_id=users.id where ifnull(greencoffees.deleted,0)=0";
        $data = $this->model->query($sql)->getResult('\App\Entities\GreenCoffeeEntity');
        return view("GreenCoffees/index", [
            "greencoffees" => $data
        ]);
    }

    function new()
    {
        $greencoffee = new GreenCoffeeEntity;
        $greencoffee->delivery_date = date('Y-m-d');
        $approved_by = "<div id='approved_by_div' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                            <a id='btn_approved_by' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='approved_by_click();'>Click to Approve</a>
                        </div>
                    </div>";
        $coffees = $this->getCoffees();

        return view("GreenCoffees/new", [
            "greencoffee" => $greencoffee,
            "coffees" => $coffees,
            "approved_by" => $approved_by,
        ]);
    }

    public function create()
    {
        $greencoffee = new GreenCoffeeEntity($this->request->getPost());

        $greencoffee->users_id = esc(auth()->user()->username);

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

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

        return redirect()->to("greencoffees")->with("message", "Green Coffee Inspection saved.");
    }

    public function edit($id)
    {
        $greencoffee = $this->getGreenCoffeeOr404($id);

        $greencoffee->users_id = esc(auth()->user()->username);

        if (null == $greencoffee->approved_by || empty($greencoffee->approved_by)) {
            $approved_by = "<div id='approved_by_div' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;z-index:1;'>
                            <a id='btn_approved_by' class='button v-small' style='width:-webkit-fill-available; color:white;' href='#' onclick='approved_by_click();'>Click to Approve</a>
                        </div>
                    </div>";
        }else{
            $approved_by = "<div id='approved_by_div' style='display:grid; gap:0; grid-template-columns: 70% 20% 10%;'>
                        <div style='grid-column:1; grid-row:1; padding:0; margin:0;'>
                            <input type='hidden' name='approved_by' id='approved_by'
                            value='".esc($greencoffee->approved_by)."' >
                            <input type='text' name='approved_by_display' id='approved_by_display'
                            class='grid-column:1; grid-cell' style='padding:0; margin:0;height:100%;border-style:solid; border-color:dimgray;text-align:center;'
                            value='".esc($greencoffee->approved_by)."' disabled>
                        </div>
                        <div style='grid-column:2; grid-row:1; padding:0; margin:0;'>
                            <a id='cancel_approved_by'
                            href='#'
                            class='disableifapproved'
                            onclick='cancel_approved_by();'
                            style='align-content:center; justify-self:center; text-align:center; width:100%; height:100%; border-style: solid; border-radius:5px; background-color:dimgrey; color:white; display:block;'
                            >x</a>
                        </div>
                    </div>";
        }
        $coffees = $this->getCoffees();

        return view("GreenCoffees/edit", [
            "greencoffee" => $greencoffee,
            "approved_by" => $approved_by,
            "coffees" => $coffees,
        ]);
    }


    public function update($id)
    {

        $greencoffee = $this->getGreenCoffeeOr404($id);

        $posted = $this->request->getPost();
        $greencoffee->fill($posted);
        $greencoffee->users_id = auth()->user()->id;
        $greencoffee->__unset("_method");
//dd($greencoffee);
        if (!$greencoffee->hasChanged()) {
            return redirect()->to("greencoffees")->with("message", "Nothing changed.");
        }

        if (!$this->model->save($greencoffee)) {
            return redirect()->back()->with("errors", $this->model->errors())->withInput();
        }

        return redirect()->to("greencoffees")->with("message", "Green Coffee Inspection updated");
    }


    public function getgreencoffees()
    {
        //$recipe = urldecode($recipename);
        $request = $this->request->getPost();
        $recipe = $request['coffeename'];

        //$recipe = "Amico Classico";

        $sql = "select recipes.WastePercent, recipes.RecipeCode, recipes.RoastColourID, roastcolours.FromNumber, roastcolours.ToNumber from recipes left join roastcolours on recipes.RoastColourID=roastcolours.RoastColourID where recipes.RecipeName = ?";
        $db = db_connect();
        $recipeinfo = $db->query($sql, [$recipe])->getRow();

        $coffees = $this->getCoffees();
        $certificates = $this->getCertificationsRecipe($recipe);
        //dd($certificates);

        $recipecoffees = $this->getCoffeesRecipe($recipe);

        $num = 1;
        $selects = array();
        $qtys = [];
        foreach ($recipecoffees as $data) {
            //dd($data);
            $recipecoffee = $data->input;
            $qty = $data->qty;
            $qtys[$recipecoffee] = $qty;
            //dd($recipecoffee);
            //$cert = $data->certcheck;
            //dd($cert);
            $select = "<select class='s3 grid-cell inputchange' name='green_coffee$num' id='green_coffee$num' onchange=\"getCertsForCoffee('green_coffee$num')\">";
            foreach ($coffees as $coffee) {
                $select .= "<option value='$coffee->InputName'";
                $select .= $coffee->InputName == $recipecoffee ? ' selected' : '';
                $select .= ">";
                $select .= "$coffee->InputName";
                $select .= "</option>";
            }
            $select .= "</select>";
            $selects = [...$selects, (object) ["green_coffee$num" => $select]];
            $num++;
        }
        for ($i = $num; $i < 6; $i++) {
            $select = "<select class='s3 grid-cell' name='green_coffee$i' id='green_coffee$i'>";
            foreach ($coffees as $coffee) {
                $select .= "<option value='$coffee->InputName'>";
                //    $select .= $coffee->InputName == $recipecoffee->InputName ? ' selected' : '';
                //    $select .= ">";
                $select .= "$coffee->InputName";
                $select .= "</option>";
            }
            $select .= "</select>";
            $selects = [...$selects, (object) ["green_coffee$i" => $select]];
        }

        $certcheck = array();
        $num = 2;
        foreach ($recipecoffees as $data) {
            $cert = $data->certcheck; // ['certcheckbox']; //  $data->certcheck;
            // $certcheck = [...$certcheck, (object) ["cert-row$num" => $cert]];
            //array_push($certcheck,(object) ["cert-row$num" => $cert]);
            $certcheck["cert-row$num"] = $cert;
            $num++;
        }
        //dd($qtys);
        $csrf = csrf_hash();

        $data = ['selects' => $selects, 'certifications' => $certificates, 'certchecks' => $certcheck, 'qty' => $qtys, 'recipeinfo' => $recipeinfo, 'token' => $csrf];
        //        $data = ['selects'=> $selects, 'certifications' => $certificates];

        //dd($data);

        return json_encode($data);
    }

    public function delete()
    {
        $request = $this->request->getPost();
        $greencoffeeid = $request['GreenCoffeeID'];
        $sql = "update greencoffees set deleted=1 where GreenCoffeeID=$greencoffeeid";
        $data = array();
        $data['token'] = csrf_hash();
        $db = db_connect();
        if ($db->simpleQuery($sql)) {
            // Read new token and assign in $data['token']
            $data['success'] = 1;
        } else {
            $data['success'] = 0;
        }
        return $this->response->setJSON($data);
    }

    private function getGreenCoffeeOr404($id): GreenCoffeeEntity
    {
        $data = $this->model->find($id);

        if ($data === null) {
            throw new PageNotFoundException("Green Coffee with id $id not found");
        }

        return $data;
    }

    private function getCoffees(): array
    {
        $db = db_connect();

        $data = $db->query('Select inputs.InputName From inputs Left Join inputtypes On inputs.InputTypeID=inputtypes.InputTypeID Where ifnull(inputtypes.IsCoffee,0)<>0 order by inputs.Inputname')->getResult();
        $data = [(object) ['InputName' => ''], ...$data];
        return $data;
    }

}
