<?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 Kannada 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->models = [
            'admin' => new \App\Models\AdminModel(),
            'category' => new \App\Models\CategoryModel(),
            'kannada' => new \App\Models\KannadaModel(),
            // 'subcategory' => new \App\Models\SubcategoryModel(),
        ];

        

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

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

    public function add()
    {
        $mAdminId = $this->session->get('login_admin_id');
        if ($mAdminId) {
            $data['sidebar'] = "kannada";
            return view('admin/add_kannada', $data);
        } else {
            return view('admin/login');
        }
    }

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

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

                $mCategory = $this->request->getPost('category');
                $mTitle = $this->request->getPost('title');
                $mDate = $this->request->getPost('date');
                $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 = [
                    'kannada_key' => $mKey,
                    'kannada_date' => $mDate,
                    'kannada_title' => $mTitle,
                    'kannada_data' => $mDesc,
                    'kannada_image' => $mToUploadProductPic,
                    'kannada_attachment' => $mToUploadAttachment,
                    'kannada_date_added' => date('Y-m-d H:i:s'),
                    'kannada_date_updated' => date('Y-m-d H:i:s')
                ];

                $result = $this->models['kannada']->addParent($data);
                if ($result) {
                    return redirect()->to('admin/kannada')->with('success', 'Article added.');
                } else {
                    return redirect()->back()->withInput()->with('error', 'Failed. Something went wrong.');
                }
            } else {
                return redirect()->back()->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'] = "kannada";
            if ($param) {
                $getCategory = $this->models['kannada']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data['article'] = $getCategory;
                    return view('admin/edit_kannada', $data);
                } else {
                    return redirect()->to('admin/kannada')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/kannada')->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'] = "kannada";
            if ($param) {
                $getCategory = $this->models['kannada']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'kannada_status' => 1,
                    ];
                    $result = $this->models['kannada']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/kannada')->with('success', 'Article updated.');
                    } else {
                        return redirect()->to('admin/kannada')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/kannada')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/kannada')->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'] = "kannada";
            if ($param) {
                $getCategory = $this->models['kannada']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'kannada_status' => 0,
                    ];
                    $result = $this->models['kannada']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/kannada')->with('success', 'Article updated.');
                    } else {
                        return redirect()->to('admin/kannada')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/kannada')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/kannada')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

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

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

                        $mCategory = $this->request->getPost('category');
                        $mTitle = $this->request->getPost('title');
                        $mDesc = $this->request->getPost('description');
                        $mDate = $this->request->getPost('date');
                        $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                        
                        $pic = $this->request->getFile('image');
                        $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                        $changedImage = !empty($mToUploadProductPic) ? $mToUploadProductPic : $getCategory['kannada_image'];

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

                        $data = [
                            'kannada_title' => $mTitle,
                            'kannada_date' => $mDate,
                            'kannada_data' => $mDesc,
                            'kannada_image' => $changedImage,
                            'kannada_attachment' => $changedAttach,
                            'kannada_date_updated' => date('Y-m-d H:i:s')
                        ];

                        $result = $this->models['kannada']->updateParentByKey($param, $data);
                        if ($result) {
                            return redirect()->to('admin/kannada/actionEdit/' . $param)->with('success', 'Article updated.');
                        } else {
                            return redirect()->back()->withInput()->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->back()->with('error', 'Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/kannada')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/kannada')->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'] = "kannada";
            if ($param) {
                $getCategory = $this->models['kannada']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $deleteCategory = $this->models['kannada']->deleteParentByKey($param);
                    if ($deleteCategory) {
                        return redirect()->to('admin/kannada')->with('success', 'Article deleted.');
                    } else {
                        return redirect()->to('admin/kannada')->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/kannada')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/kannada')->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/kannada', $newName);
            return $newName;
        }
        return '';
    }
}