<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class Judgements 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 = [
            'admin' => new \App\Models\AdminModel(),
            'category' => new \App\Models\CategoryModel(),
            'judgement' => new \App\Models\JudgementModel(),
            'author' => new \App\Models\AuthorModel(),
            'category' => new \App\Models\CategoryModel(),
        ];

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

    public function index()
    {
        $data['sidebar'] = "judgements";
        $mAdminId = $this->session->get('login_admin_id');
        if ($mAdminId) {
            $data['judgements'] = $this->models['judgement']->getAllParent();
            return view('admin/judgements', $data);
        } else {
            return view('admin/signin', $data);
        }
    }

    public function addJudgement()
    {
        $mAdminId = $this->session->get('login_admin_id');
        if ($mAdminId) {
            $data['sidebar'] = "judgements";
            $data['authors'] = $this->models['author']->getAllParent();
            $data['categories'] = $this->models['category']->getAllParent();
            return view('admin/add_judgement', $data);
        } else {
            return view('admin/login');
        }
    }

    public function actionAddJudgement()
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            if ($this->request->getMethod() === 'POST') {
                $rules = [
                    'category' => 'required',
                    'title' => 'required',
                    'description' => 'required',
                    'author' => 'required',
                    'date' => 'required',
                ];

                if (!$this->validate($rules)) {
                    return redirect()->to('admin/judgements/addJudgement')->with('error', 'Validation Error.')->withInput();
                }

                $mCategory = $this->request->getPost('category');
                $mTitle = $this->request->getPost('title');
                $mDesc = $this->request->getPost('description');
                $pic = $this->request->getFile('image');
                $mDate = $this->request->getPost('date');
                $mAuthor = $this->request->getPost('author');
                $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                
                $attach = $this->request->getFile('attachment');
                $mToUploadAttachment = $this->articleFileUpload('attachment', $attach);
                
                $mKey = $this->mGenerateRandomNumber();
                $data = [
                    'judgement_key' => $mKey,
                    'judgement_category_key' => $mCategory,
                    'judgement_author' => $mAuthor,
                    'judgement_date' => $mDate,
                    'judgement_title' => $mTitle,
                    'judgement_desc' => $mDesc,
                    'judgement_img' => $mToUploadProductPic,
                    'judgement_attachment' => $mToUploadAttachment,
                    'judgement_date_added' => date('Y-m-d H:i:s'),
                    'judgement_date_updated' => date('Y-m-d H:i:s')
                ];

                $result = $this->models['judgement']->addParent($data);
                log_message('debug', 'Value: ' . ($result ?? 'not set'));
                log_message('debug', 'mEmail value: ' . (is_array($data) ? print_r($data, true) : ($result ?? 'not set')));

                if ($result) {
                    return redirect()->to('admin/judgements')->with('success', 'Judgement added.');
                } else {
                    return redirect()->to('admin/judgements/addJudgement')->with('error', 'Failed. Something went wrong.');
                }
            } else {
                return redirect()->to('admin/judgements/addJudgement')->with('error', 'Something went wrong.');
            }
        } else {
            return redirect()->to('admin/home');
        }
    }

    public function actionEditJudgement($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            $data['categories'] = $this->models['category']->getAllParent();
            $data['authors'] = $this->models['author']->getAllParent();
            if ($param) {
                $getCategory = $this->models['judgement']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data['article'] = $getCategory;
                    return view('admin/edit_judgement', $data);
                } else {
                    return redirect()->to('admin/judgements')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/judgements')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionEnable($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            if ($param) {
                $getCategory = $this->models['judgement']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'judgement_status' => 1,
                    ];
                    $result = $this->models['judgement']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/judgements')->with('success', 'Judgement updated.');
                    } else {
                        return redirect()->to('admin/judgements')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/judgements')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/judgements')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionDisable($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            if ($param) {
                $getCategory = $this->models['judgement']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'judgement_status' => 0,
                    ];
                    $result = $this->models['judgement']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/judgements')->with('success', 'Judgement updated.');
                    } else {
                        return redirect()->to('admin/judgements')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/judgements')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/judgements')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionUpdateJudgement($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            if ($param) {
                $getCategory = $this->models['judgement']->getParentByKey($param);
                if (!empty($getCategory)) {
                    if ($this->request->getMethod() === 'POST') {
                        $rules = [
                            'category' => 'required',
                            'title' => 'required',
                            'description' => 'required',
                            'author' => 'required',
                            'date' => 'required',
                        ];

                        if (!$this->validate($rules)) {
                            return redirect()->to('admin/judgements/actionEditJudgement/' . $param)->with('error', 'Validation Error.')->withInput();
                        }

                        $mCategory = $this->request->getPost('category');
                        $mTitle = $this->request->getPost('title');
                        $mDesc = $this->request->getPost('description');
                        $mDate = $this->request->getPost('date');
                        $mAuthor = $this->request->getPost('author');
                        $pic = $this->request->getFile('image');
                        $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                        $changedImage = !empty($mToUploadProductPic) ? $mToUploadProductPic : $getCategory['judgement_img'];

                        $attach = $this->request->getFile('attachment');
                        $mToUploadAttachment = $this->articleFileUpload('attachment', $attach);
                        $changedAttach = !empty($mToUploadAttachment) ? $mToUploadAttachment : $getCategory['judgement_attachment'];

                        $data = [
                            'judgement_author' => $mAuthor,
                            'judgement_date' => $mDate,
                            'judgement_category_key' => $mCategory,
                            'judgement_title' => $mTitle,
                            'judgement_desc' => $mDesc,
                            'judgement_img' => $changedImage,
                            'judgement_attachment' => $changedAttach,
                            'judgement_date_updated' => date('Y-m-d H:i:s')
                        ];

                        $result = $this->models['judgement']->updateParentByKey($param, $data);
                        if ($result) {
                            return redirect()->to('admin/judgements/actionEditJudgement/' . $param)->with('success', 'Judgement updated.');
                        } else {
                            return redirect()->to('admin/judgements/actionEditJudgement/' . $param)->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->to('admin/judgements/actionEditJudgement/' . $param)->with('error', 'Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/judgements')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/judgements')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionDeleteJudgement($param)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['sidebar'] = "judgements";
            if ($param) {
                $getCategory = $this->models['judgement']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $deleteCategory = $this->models['judgement']->deleteParentByKey($param);
                    if ($deleteCategory) {
                        return redirect()->to('admin/judgements')->with('success', 'Judgement deleted.');
                    } else {
                        return redirect()->to('admin/judgements')->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/judgements')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/judgements')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function getSubcatByCat()
    {
        $categoryKey = $this->request->getPost('value');
        $subs = $this->models['subcategory']->getSubCatByCat($categoryKey);
        if (!empty($subs)) {
            $result = '<option disabled="" selected="">Select Sub-Category</option>';
            foreach ($subs as $sub) {
                $result .= "<option value='" . $sub['subcategory_key'] . "'>" . $sub['subcategory'] . "</option>" . PHP_EOL;
            }
            return $this->response->setJSON(['html' => $result]);
        } else {
            return $this->response->setJSON(['html' => "<option>No Sub Categories</option>"]);
        }
    }

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

    private function articleFileUpload($mId, $mFile)
    {
        if ($mFile->isValid() && !$mFile->hasMoved()) {
            $newName = $mFile->getRandomName();
            $mFile->move(FCPATH . 'uploads/judgements', $newName);
            return $newName;
        }
        return '';
    }
}