<?php

namespace App\Controllers;

use App\Models\CountriesModel;
use App\Entities\Country;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Database\Exceptions\DatabaseException;

class Countries extends BaseController
{
    private CountriesModel $model;

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

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

        $country = $this->getCountryOr404($id);
		$sql = "SELECT inputs.InputID, inputs.InputName FROM inputs WHERE inputs.CountryID=$id";
		$db = db_connect();
		$inputs = $db->query($sql)->getResult('App\Entities\Input');

        return view("Countries/show",[
            "country" => $country,
            "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("Countries/new",[
            "country" => new Country
        ]);
    }

    public function create()
    {

        $country = new Country($this->request->getPost());

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

        if($id === false){

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

        }

        return redirect()->to("countries/$id")->with("message","Country 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" );
		}

        $country = $this->getCountryOr404($id);

        return view("Countries/edit",[
            "country" => $country
        ]);

    }


    public function update($id)
    {

        $country = $this->getCountryOr404($id);

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

        $country->__unset("_method");

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

        if($this->model->save($country)){
            return redirect()->to("countries/$id")->with("message","Country 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" );
		}

        $country = $this->getCountryOr404($id);

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

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

        // $country = $this->getCountryOr404($id);

        // $this->model->delete($id);

        // return redirect()->to("countries")->with("message","Country deleted.");
    }

    private function getCountryOr404($id): Country
    {
        $country = $this->model->find($id);

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

        return $country;
    }
}
