<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\SeminarModel;
use App\Models\SubcategoryModel;

class Seminars extends BaseController
{
    protected $adminModel;
    protected $seminarModel;
    protected $subcategoryModel;

    public function __construct()
    {
        $this->adminModel = new AdminModel();
        $this->seminarModel = new SeminarModel();
        // $this->subcategoryModel = new CategoryModel();

        helper(['form', 'url', 'date']);
        date_default_timezone_set("Asia/Kolkata");
    }

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

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

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

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

                $mTitle = $this->request->getPost('title');
                $mLink = $this->request->getPost('link');
                $mKey = $this->mGenerateRandomNumber();
                $data = [
                    'seminar_key' => $mKey,
                    'seminar_title' => $mTitle,
                    'seminar_link' => $mLink,
                    'seminar_date_added' => date('Y-m-d H:i:s'),
                    'seminar_date_updated' => date('Y-m-d H:i:s')
                ];
                $result = $this->seminarModel->addParent($data);
                if ($result) {
                    return redirect()->to('admin/seminars')->with('success', 'Seminar added.');
                } else {
                    return redirect()->to('admin/seminars/add')->with('error', 'Failed. Something went wrong.');
                }
            } else {
                return redirect()->to('admin/seminars/add')->with('error', 'Something went wrong.');
            }
        } else {
            return redirect()->to('admin/home');
        }
    }

    public function actionEdit($param = null)
    {
        $mUserId = session()->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "seminars";
            if ($param) {
                $getCategory = $this->seminarModel->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data['seminar'] = $getCategory;
                    return view('admin/edit_seminar', $data);
                } else {
                    return redirect()->to('admin/seminars')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/seminars')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

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

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

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

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

                        $mTitle = $this->request->getPost('title');
                        $mLink = $this->request->getPost('link');
                        $data = [
                            'seminar_title' => $mTitle,
                            'seminar_link' => $mLink,
                            'seminar_date_updated' => date('Y-m-d H:i:s')
                        ];
                        $result = $this->seminarModel->updateParentByKey($param, $data);
                        if ($result) {
                            return redirect()->to('admin/seminars/actionEdit/' . $param)->with('success', 'Seminar updated.');
                        } else {
                            return redirect()->to('admin/seminars/actionEdit/' . $param)->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->to('admin/seminars/actionEdit/' . $param)->with('error', 'Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/seminars')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/seminars')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

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

    public function getSubcatByCat()
    {
        $categoryKey = $this->request->getPost('value');
        $subs = $this->subcategoryModel->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()
    {
        return bin2hex(random_bytes(12));
    }

    public function articleFileUpload($mId, $mFile)
    {
        $validationRule = [
            $mId => [
                'label' => 'File',
                'rules' => [
                    'uploaded[' . $mId . ']',
                    'mime_in[' . $mId . ',image/jpg,image/jpeg,image/gif,image/png,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,audio/mpeg,audio/x-m4a,audio/ogg,audio/wav,video/mp4,video/x-m4v,video/quicktime,video/x-ms-wmv,video/mpeg]',
                    'max_size[' . $mId . ',10240]',
                ],
            ],
        ];

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

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

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

        return '';
    }
}