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

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

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

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

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

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

                $mCategory = $this->request->getPost('category');
                $mTitle = $this->request->getPost('title');
                $mDate = $this->request->getPost('date');
                $mAuthor = $this->request->getPost('author');
                $mDesc = $this->request->getPost('description');
                $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                $pic = $this->request->getFile('image');
                $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                
                $attach = $this->request->getFile('attachment');
                $mToUploadAttachment = $this->articleFileUpload('attachment', $attach);
                
                $mKey = $this->mGenerateRandomNumber();
                $data = [
                    'news_key' => $mKey,
                    'category_key' => $mCategory,
                    'news_author' => $mAuthor,
                    'news_date' => $mDate,
                    'news_title' => $mTitle,
                    'news_description' => $mDesc,
                    'news_image' => $mToUploadProductPic,
                    'news_attachment' => $mToUploadAttachment,
                    'news_date_added' => date('Y-m-d H:i:s'),
                    'news_date_updated' => date('Y-m-d H:i:s')
                ];
                $result = $this->models['news']->addParent($data);
                if ($result) {
                    return redirect()->to('admin/news')->with('success', 'News added.');
                } else {
                    return redirect()->to('admin/news/add')->with('error', 'Failed. Something went wrong.');
                }
            } else {
                return redirect()->to('admin/news/add')->with('error', 'Something went wrong.');
            }
        } else {
            return redirect()->to('admin/home');
        }
    }

    public function actionEdit($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "articles";
            $data['categories'] = $this->models['category']->getAllParent();
            $data['authors'] = $this->models['author']->getAllParent();
            if ($param) {
                $getCategory = $this->models['news']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data['article'] = $getCategory;
                    return view('admin/edit_news', $data);
                } else {
                    return redirect()->to('admin/news')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/news')->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['active'] = "articles";
            if ($param) {
                $getCategory = $this->models['news']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'news_status' => 1,
                    ];
                    $result = $this->models['news']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/news')->with('success', 'Articles updated.');
                    } else {
                        return redirect()->to('admin/news')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/news')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/news')->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['active'] = "articles";
            if ($param) {
                $getCategory = $this->models['news']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'news_status' => 0,
                    ];
                    $result = $this->models['news']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/news')->with('success', 'Article updated.');
                    } else {
                        return redirect()->to('admin/news')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/news')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/news')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionUpdate($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "articles";
            if ($param) {
                $getCategory = $this->models['news']->getParentByKey($param);
                if (!empty($getCategory)) {
                    if ($this->request->getMethod() === 'POST') {
                        $rules = [
                            'category' => 'required',
                            'title' => 'required',
                            'description' => 'required',
                        ];

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

                        $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');
                        $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                        $pic = $this->request->getFile('image');
                        $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                        if (!empty($mToUploadProductPic)) {
                            $changedImage = $mToUploadProductPic;
                        } else {
                            $changedImage = $getCategory['news_image'];
                        }
                        $attach = $this->request->getFile('attachment');
                        $mToUploadAttachment = $this->articleFileUpload('attachment', $attach);
                        if (!empty($mToUploadAttachment)) {
                            $changedAttach = $mToUploadAttachment;
                        } else {
                            $changedAttach = $getCategory['news_attachment'];
                        }
                        $data = [
                            'category_key' => $mCategory,
                            'news_author' => $mAuthor,
                            'news_date' => $mDate,
                            'news_title' => $mTitle,
                            'news_description' => $mDesc,
                            'news_image' => $changedImage,
                            'news_attachment' => $changedAttach,
                            'news_date_updated' => date('Y-m-d H:i:s')
                        ];
                        $result = $this->models['news']->updateParentByKey($param, $data);
                        if ($result) {
                            return redirect()->to('admin/news/actionEdit/' . $param)->with('success', 'News updated.');
                        } else {
                            return redirect()->to('admin/news/actionEdit/' . $param)->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->to('admin/news/actionEdit/' . $param)->with('error', 'Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/news')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/news')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function actionDelete($param)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "articles";
            if ($param) {
                $getCategory = $this->models['news']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $deleteCategory = $this->models['news']->deleteParentByKey($param);
                    if ($deleteCategory) {
                        return redirect()->to('admin/news')->with('success', 'Article deleted.');
                    } else {
                        return redirect()->to('admin/news')->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/news')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/news')->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(['subcategories' => $result]);
        } else {
            return $this->response->setJSON(['subcategories' => "<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/articles', $newName);
            return $newName;
        }
        return '';
    }
}