<?php

namespace App\Controllers;

use App\Models\InputTypesModel;
use App\Entities\InputType;
use App\Entities\Category;


class Home extends BaseController
{
    private InputTypesModel $model;

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

    public function index()
    {
        //$this->sendTestEmail();

        if(session("magicLogin")) {
            return redirect()->to("set-password")->with("message","please update your password");
        }
        $inputtypes = $this->getInputTypesOr404();
        $categories = $this->getCategories();
        return view("Home/index",
            [
                "inputtypes"=>$inputtypes,
                "categories"=>$categories,
            ]);

    }

    private function getCategories()
    {
        $sql = "SELECT DISTINCT categories.CategoryID, categories.Category
        FROM categories
        LEFT JOIN recipes on categories.CategoryID=recipes.CategoryID
        GROUP BY categories.CategoryID, categories.Category
        HAVING COUNT(recipes.RecipeID) > 0
        ORDER BY Category";

        $db = db_connect();
        $data = $db->query($sql)->getResult('App\Entities\Category');
        return $data;
    }

    private function getInputTypesOr404()
    {
        $data = $this->model->orderBy('DisplayOrder')->findAll();
        return $data;
    }

    private function sendTestEmail()
    {
        $email = \Config\Services::email();

        $email->setTo("tim@tycs.co.uk");
        $email->setSubject("Test Email");
        $email->setMessage("Hello from <i>CodeIgniter</i>");

        if($email->send()){
            echo "Email sent";
        }else{
            echo "Email not sent";
        }
    }
}
