<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class Courts extends BaseController
{
    protected $helpers = ['form', 'url', 'date'];
    protected $models = [];

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        $this->db = \Config\Database::connect();
        $this->session = \Config\Services::session();
        $this->validation = \Config\Services::validation();
        $this->upload = \Config\Services::upload();

        $this->models = [
            'category' => new \App\Models\CategoryModel(),
            'article' => new \App\Models\ArticleModel(),
            'lawyers' => new \App\Models\LawyersModel(),
            'bareact' => new \App\Models\BareactModel(),
            'section' => new \App\Models\SectionModel(),
            'judgement' => new \App\Models\JudgementModel(),
            'court' => new \App\Models\CourtModel(),
            'subcourt' => new \App\Models\SubcourtModel(),
        ];

        date_default_timezone_set("Asia/Kolkata");
        error_reporting(0);
    }

    public function index()
    {
        $data = [
            'home' => "courts",
            'courts' => $this->models['court']->getAllParentForSite()
        ];
        return view('courts', $data);
    }

    public function actionView($param)
    {
        if ($param) {
            $data = [
                'home' => "courts",
                'subcourt' => $this->models['subcourt']->getParentByKey($param),
                'subcourts' => $this->models['subcourt']->getAllParentForSite()
            ];
            return view('view_subcourt', $data);
        }
        throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
    }

    private function mGenerateRandomNumber(): string
    {
        return bin2hex(random_bytes(12));
    }

    public function sendEmail($subject, $message, $to)
    {
        $email = \Config\Services::email();
        $email->setFrom('info@vendorglobe.com', '');
        $email->setTo($to);
        $email->setSubject($subject);
        $email->setMessage($message);
        
        try {
            return $email->send() ? 1 : 0;
        } catch (\Exception $e) {
            log_message('error', $e->getMessage());
            return 0;
        }
    }

    public function actionLogout()
    {
        $this->session->destroy();
        return redirect()->to('home');
    }
}