<?php

namespace App\Controllers;

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

class Search 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->email = \Config\Services::email();

        $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(),
            'news' => new \App\Models\NewsModel(),
        ];

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

    public function index()
    {
        $data['home'] = "search";
        return view('search', $data);
    }

    public function results()
    {
        $data['home'] = "search";
        $mInput = $this->request->getPost('search');

        if ($mInput) {
            $mSearchResults = [];

            $mArticles = $this->models['article']->getAllParentByTitle($mInput);
            $mJudgements = $this->models['judgement']->getAllParentByTitle($mInput);
            $mNews = $this->models['news']->getAllParentByTitle($mInput);

            foreach ($mArticles as $mArticle) {
                $mSearchResults[] = [
                    "search_key" => $mArticle['article_key'],
                    "search_img" => $mArticle['article_image'],
                    "search_title" => $mArticle['article_title'],
                    "type" => "1",
                    "date" => $mArticle['article_date_added']
                ];
            }

            foreach ($mJudgements as $mJudgement) {
                $mSearchResults[] = [
                    "search_key" => $mJudgement['judgement_key'],
                    "search_img" => $mJudgement['judgement_img'],
                    "search_title" => $mJudgement['judgement_title'],
                    "type" => "2",
                    "date" => $mJudgement['judgement_date_added']
                ];
            }

            foreach ($mNews as $mNew) {
                $mSearchResults[] = [
                    "search_key" => $mNew['news_key'],
                    "search_img" => $mNew['news_image'],
                    "search_title" => $mNew['news_title'],
                    "type" => "3",
                    "date" => $mNew['news_date_added']
                ];
            }

            usort($mSearchResults, fn($a, $b) => strtotime($b['date']) - strtotime($a['date']));

            $data['results'] = $mSearchResults;
        }

        return view('search', $data);
    }

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

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

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