<?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 Bareacts 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(),
            'bareact' => new \App\Models\BareactModel(),
            'section' => new \App\Models\SectionModel(),
            // 'subcategory' => new \App\Models\SubcategoryModel(),
        ];

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

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

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

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

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

                $mTitle = $this->request->getPost('title');
                $mDate = $this->request->getPost('docdate');
                $doc = $this->request->getFile('image');
                $mToUploadDoc = $this->articleFileUpload('image', $doc);

                $mKey = $this->mGenerateRandomNumber();
                $data = [
                    'ba_key' => $mKey,
                    'ba_title' => $mTitle,
                    'ba_date' => $mDate,
                    'ba_document' => $mToUploadDoc,
                    'ba_date_added' => date('Y-m-d H:i:s'),
                    'ba_date_updated' => date('Y-m-d H:i:s')
                ];

                $result = $this->models['bareact']->addParent($data);
                if ($result) {
                    return redirect()->to('admin/bareacts')->with('success', $mTitle . ' added.');
                } else {
                    return redirect()->to('admin/bareacts/addBareact')->withInput()->with('error', 'Failed. Something went wrong.');
                }
            } else {
                return redirect()->to('admin/bareacts/addBareact')->with('error', 'Something went wrong.');
            }
        } else {
            return redirect()->to('admin/home');
        }
    }

    public function actionEditBareact($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "bareacts";
            
            if ($param) {
                $getParent = $this->models['bareact']->getParentByKey($param);

                if (!empty($getParent)) {
                    $getChild = $this->models['section']->getAllParentByChildKey($param);
                    $data['parent'] = $getParent;
                    $data['child'] = $getChild;
                    log_message('debug', 'Value child: ' . ($getChild ?? 'not set'));

                    return view('admin/edit_bareact', $data);
                } else {
                    return redirect()->to('admin/bareacts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/bareacts')->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'] = "bareacts";
            if ($param) {
                $getCategory = $this->models['bareact']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'ba_status' => 1,
                    ];
                    $result = $this->models['bareact']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/bareacts')->with('success', 'Bare Act updated.');
                    } else {
                        return redirect()->to('admin/bareacts')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/bareacts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/bareacts')->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'] = "bareacts";
            if ($param) {
                $getCategory = $this->models['bareact']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'ba_status' => 0,
                    ];
                    $result = $this->models['bareact']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/bareacts')->with('success', 'Bare Act updated.');
                    } else {
                        return redirect()->to('admin/bareacts')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/bareacts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/bareacts')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

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

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

                        $mTitle = $this->request->getPost('title');
                        $mDate = $this->request->getPost('docdate');
                        $doc = $this->request->getFile('image');
                        $mToUploadDoc = $this->articleFileUpload('image', $doc);

                        if (!empty($mToUploadDoc)) {
                            $mToUploadDoc = $mToUploadDoc;
                        } else {
                            $mToUploadDoc = $getCategory['ba_document'];
                        }

                        $data = [
                            'ba_title' => $mTitle,
                            'ba_date' => $mDate,
                            'ba_document' => $mToUploadDoc,
                            'ba_date_updated' => date('Y-m-d H:i:s')
                        ];

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

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

    public function actionDeleteSection($sec, $bare)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "bareacts";
            if ($sec && $bare) {
                $getCategory = $this->models['section']->getParentByKey($sec);
                if (!empty($getCategory)) {
                    $deleteCategory = $this->models['section']->deleteParentByKey($sec);
                    if ($deleteCategory) {
                        return redirect()->to('admin/bareacts/actionEditBareact/' . $bare)->with('success', 'Section deleted.');
                    } else {
                        return redirect()->to('admin/bareacts/actionEditBareact/' . $bare)->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/bareacts/actionEditBareact/' . $bare)->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/bareacts')->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(['result' => $result]);
        } else {
            return $this->response->setJSON(['result' => "<option>No Sub Categories</option>"]);
        }
    }

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

    private function articleFileUpload($mId, $mFile)
    {
        if (!$mFile->isValid()) {
            return '';
        }

        $newName = $mFile->getRandomName();
        $mFile->move(FCPATH . 'uploads/bareacts', $newName);

        return $newName;
    }
}