<?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 Home 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(),
            'seminar' => new \App\Models\SeminarModel(),
            'news' => new \App\Models\NewsModel(),
            'users' => new \App\Models\UsersModel(),
        ];

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

    public function index()
    {
        $data = [
            'home' => "home",
            'news' => $this->models['news']->getAllParentForSite(),
            'articles' => $this->models['article']->getAllParentForSite(),
            'judgements' => $this->models['judgement']->getAllParentForSite(),
            'seminars' => $this->models['seminar']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];
        return view('index', $data);
    }

    public function lawyerProfile()
    {
        $mSessionMobile = $this->session->get('session_mobile');
        $data['profile'] = $this->models['lawyers']->getParentByMobile($mSessionMobile);
        return view('lawyer_profile', $data);
    }   

    public function sendMessage()
    {
        if ($this->request->getMethod() === 'post') {
            $rules = [
                'name' => 'required',
                'mail' => 'required|valid_email',
                'website' => 'required',
                'comment' => 'required',
            ];

            if (!$this->validate($rules)) {
                return redirect()->back()->with('error', 'Validation Error')->withInput();
            }

            $mName = $this->request->getPost('name');
            $mEmail = $this->request->getPost('mail');
            $mWeb = $this->request->getPost('website');
            $mComment = $this->request->getPost('comment');

            $message = "
            <html>
            <head>
            </head>
            <body>
            <h3>From : $mName,</h3><br>
            <h3>Email : $mEmail,</h3><br>
            <h3>Website : $mWeb,</h3><br>    
            <p>Message : $mComment</p>
            </body>
            </html>";

            $mSend = $this->sendEmail('Contact Us Queries', $message, 'info@dakshalegal.com');

            if ($mSend == "1") {
                return redirect()->to('home/contactus')->with('success', 'Message sent successfully.');
            } else {
                return redirect()->to('home/contactus')->with('error', 'Something went wrong.');
            }
        }

        return redirect()->to('home/contactus')->with('error', 'Something went wrong.');
    }

    public function actionLawyerProfile($mLid = null)
    {
        $mSessionMobile = $this->session->get('session_mobile');
        $data['profile'] = $this->models['lawyers']->getParentByMobile($mSessionMobile);

        if ($this->request->getMethod() === 'post') {
            $rules = [
                'email' => 'required|valid_email',
            ];

            if (!$this->validate($rules)) {
                return redirect()->back()->with('error', 'Validation Error')->withInput();
            }

            $mName = $this->request->getPost('name');
            $mEmail = $this->request->getPost('email');
            $mMobile = $this->request->getPost('mobile');
            $mExperience = $this->request->getPost('experience');
            $mPractice = $this->request->getPost('practice');
            $mAddress = $this->request->getPost('address');
            $pic = $this->request->getPost('image');

            $mToUploadProductPic = $this->lawyerFileUpload('image', $pic);

            $data = [
                'Lawyer_Name' => $mName,
                'Email_Id' => $mEmail,
                'Phone_Number' => $mMobile,
                'Experience' => $mExperience,
                'Practice_Areas' => $mPractice,
                'Address' => $mAddress,
                'Image' => $mToUploadProductPic,
                'Timestamp' => date('Y-m-d H:i:s'),
            ];

            if ($mLid) {
                $mUpdate = $this->models['lawyers']->updateParentByKey($mLid, $data);
                if ($mUpdate) {
                    return redirect()->to('home/lawyerProfile')->with('success', 'Lawyer data updated successfully.');
                }
            } else {
                $data['Status'] = 0;
                $mAdd = $this->models['lawyers']->addParent($data);
                if ($mAdd) {
                    return redirect()->to('home/lawyerProfile')->with('success', 'Lawyer data added successfully and sent for admin approval.');
                }
            }

            return redirect()->to('home/lawyerProfile')->with('error', 'Something went wrong.');
        }

        return redirect()->to('home/lawyerProfile')->with('error', 'Something went wrong.');
    }

    public function judgements()
    {
        $data = [
            'home' => "judgements",
            'judgements' => $this->models['judgement']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];
        return view('judgements', $data);
    }

    public function articles()
    {
        $data = [
            'home' => "articles",
            'articles' => $this->models['article']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];
        return view('articles', $data);
    }

    public function contactus()
    {
        $data = [
            'home' => "contactus",
            'articles' => $this->models['article']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];
        return view('contactus', $data);
    }

    public function bareacts()
    {
        $data = [
            'home' => "bareacts",
            'bareacts' => $this->models['bareact']->getAllParentForSite(),
        ];
        return view('bare_acts', $data);
    }

    public function seminars()
    {
        $data = [
            'home' => "seminars",
            'bareacts' => $this->models['bareact']->getAllParentForSite(),
        ];
        return view('seminars', $data);
    }

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

    public function viewBareact($param)
    {
        if ($param) {
            $data = [
                'home' => "bareacts",
                'bareact' => $this->models['bareact']->getParentByKey($param),
                'sections' => $this->models['section']->getAllParentByChildKey($param),
            ];
            return view('bare_act_sections', $data);
        } else {
            return redirect()->to('home');
        }
    }

    public function lawyers($sort = null)
    {
        $data = [
            'home' => "lawyers",
            'articles' => $this->models['article']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];

        if ($sort) {
            $data['sort'] = "Sort by newly added";
            $data['lawyers'] = $this->models['lawyers']->getAllParentBySorting();
        } else {
            $data['sort'] = "Sort Alphabetically";
            $data['lawyers'] = $this->models['lawyers']->getAllParent();
        }

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

    public function signin()
    {
        $data = [
            'home' => "signin",
            'articles' => $this->models['article']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
            'lawyers' => $this->models['lawyers']->getAllParent(),
        ];
        return view('signin', $data);
    }

    public function view($param)
    {
        $data = [
            'home' => "home",
            'articles' => $this->models['article']->getAllParentForSite(),
            'tags' => $this->models['category']->getAllParentForSite(),
        ];

        if ($param) {
            $data['article'] = $this->models['article']->getParentByKey($param);
            return view('view', $data);
        } else {
            return view('index', $data);
        }
    }

    public function actionDowloadBareact($id)
    {
        if (!empty($id)) {
            $bareact = $this->models['bareact']->getParentByKey($id);
            $siteaddressAPI = site_url("home/bareactPdf/$id");
            $html = file_get_contents($siteaddressAPI);

            $dompdf = new \Dompdf\Dompdf();
            $dompdf->set_option('isRemoteEnabled', TRUE);
            $dompdf->set_option("isPhpEnabled", true);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('legal', 'portrait');
            $dompdf->render();

            $name = $bareact['ba_title'] . ".pdf";
            return $dompdf->stream($name, ["Attachment" => 1]);
        } else {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
    }

    public function bareactPdf($id)
    {
        if (!empty($id)) {
            $data = [
                'home' => "bareacts",
                'bareact' => $this->models['bareact']->getParentByKey($id),
                'sections' => $this->models['section']->getAllParentByChildKey($id),
            ];
            return view('bareact_pdf', $data);
        } else {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
    }

    public function mGenerateRandomNumber()
    {
        $key = '';
        $keys = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
        for ($i = 0; $i < 25; $i++) {
            $key .= $keys[array_rand($keys)];
        }
        return $key;
    }

    public function lawyerFileUpload($mId, $mFile)
    {
        $validationRule = [
            $mId => [
                'label' => 'Image File',
                'rules' => [
                    'uploaded[' . $mId . ']',
                    'is_image[' . $mId . ']',
                    'mime_in[' . $mId . ',image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[' . $mId . ',100]',
                    'max_dims[' . $mId . ',1024,768]',
                ],
            ],
        ];

        if (! $this->validate($validationRule)) {
            return '';
        }

        $img = $this->request->getFile($mId);

        if (! $img->hasMoved()) {
            $filepath = FCPATH . 'uploads/lawyers/';
            $filename = $img->store('lawyers/', $img->getRandomName());
            return $filename;
        }

        return '';
    }

    public function sendEmail($subject, $message, $to)
    {
        $this->email->setFrom('info@dakshalegal.com', '');
        $this->email->setTo($to);
        $this->email->setSubject($subject);
        $this->email->setMessage($message);

        if ($this->email->send()) {
            return 1;
        }
        return 0;
    }

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

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

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

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