<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\SubcourtModel;
use App\Models\CourtModel;

class Subcourts extends BaseController
{
    protected $adminModel;
    protected $subcourtModel;
    protected $courtModel;
    protected $session;
    protected $validation;

    public function __construct()
    {
        $this->adminModel = new AdminModel();
        $this->subcourtModel = new SubcourtModel();
        $this->courtModel = new CourtModel();
        $this->session = \Config\Services::session();
        $this->validation = \Config\Services::validation();

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

    public function index()
    {
        $data['sidebar'] = "subcourts";
        $mAdminId = $this->session->get('login_admin_id');
        if ($mAdminId) {
            $data['courts'] = $this->courtModel->findAll();
            $data['subcourts'] = $this->subcourtModel->select('subcourts.*, courts.court_name')
            ->join('courts', 'courts.court_key = subcourts.subcourt_court_key')
            ->findAll();
            return view('admin/subcourts', $data);
        } else {
            return view('admin/signin', $data);
        }
    }

    public function add()
    {
        $mAdminId = $this->session->get('login_admin_id');
        if ($mAdminId) {
            $data['sidebar'] = "subcourts";
            $data['courts'] = $this->courtModel->findAll();
            $data['subcourts'] = $this->subcourtModel->findAll();
            return view('admin/add_subcourt', $data);
        } else {
            return view('admin/login');
        }
    }

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

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

                $mTitle = $this->request->getPost('title');
                $mCourt = $this->request->getPost('court');
                $mDesc = $this->request->getPost('description');
                $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                $pic = $this->request->getFile('image');
                $mToUploadProductPic = $this->articleFileUpload('image', $pic);

                $mKey = $this->mGenerateRandomNumber();
                $data = [
                    'subcourt_key' => $mKey,
                    'subcourt_court_key' => $mCourt,
                    'subcourt_name' => $mTitle,
                    'subcourt_desc' => $mDesc,
                    'subcourt_image' => $mToUploadProductPic,
                    'subcourt_date_added' => date('Y-m-d H:i:s'),
                    'subcourt_date_updated' => date('Y-m-d H:i:s')
                ];
                
                $result = $this->subcourtModel->insert($data);
                if ($result) {
                    return redirect()->to('admin/subcourts')->with('success', 'Sub Court added.');
                } else {
                    return redirect()->to('admin/subcourts/add')->with('error', 'Failed. Something went wrong.')->withInput();
                }
            } else {
                return redirect()->to('admin/subcourts/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'] = "subcourts";
            $data['courts'] = $this->courtModel->findAll();
            $data['subcourts'] = $this->subcourtModel->findAll();
            if ($param) {
                $getCategory = $this->subcourtModel->where('subcourt_key', $param)->first();
                if (!empty($getCategory)) {
                    $data['subcourt'] = $getCategory;
                    return view('admin/edit_subcourt', $data);
                } else {
                    return redirect()->to('admin/subcourts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/subcourts')->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'] = "subcourts";
            if ($param) {
                $getCategory = $this->subcourtModel->where('subcourt_key', $param)->first();
                if (!empty($getCategory)) {
                    $data = [
                        'subcourt_status' => 1,
                    ];
                    $result = $this->subcourtModel->update($getCategory['subcourt_id'], $data);
                    if ($result) {
                        return redirect()->to('admin/subcourts')->with('success', 'Sub court Enabled.');
                    } else {
                        return redirect()->to('admin/subcourts')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/subcourts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/subcourts')->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'] = "subcourts";
            if ($param) {
                $getCategory = $this->subcourtModel->where('subcourt_key', $param)->first();
                if (!empty($getCategory)) {
                    $data = [
                        'subcourt_status' => 0,
                    ];
                    $result = $this->subcourtModel->update($getCategory['subcourt_id'], $data);
                    if ($result) {
                        return redirect()->to('admin/subcourts')->with('success', 'Sub court Disabled.');
                    } else {
                        return redirect()->to('admin/subcourts')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/subcourts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/subcourts')->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'] = "subcourts";
            if ($param) {
                $getCategory = $this->subcourtModel->where('subcourt_key', $param)->first();
                if (!empty($getCategory)) {
                    if ($this->request->getMethod() === 'POST') {
                        $rules = [
                            'title' => 'required',
                        ];

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

                        $mTitle = $this->request->getPost('title');
                        $mCourt = $this->request->getPost('court');
                        $mDesc = $this->request->getPost('description');
                        $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                        $pic = $this->request->getFile('image');
                        $mToUploadProductPic = $this->articleFileUpload('image', $pic);
                        
                        $changedImage = !empty($mToUploadProductPic) ? $mToUploadProductPic : $getCategory['subcourt_image'];
                        
                        $data = [
                            'subcourt_court_key' => $mCourt,
                            'subcourt_name' => $mTitle,
                            'subcourt_desc' => $mDesc,
                            'subcourt_image' => $changedImage,
                            'subcourt_date_updated' => date('Y-m-d H:i:s')
                        ];
                        
                        $result = $this->subcourtModel->update($getCategory['subcourt_id'], $data);
                        if ($result) {
                            return redirect()->to('admin/subcourts/actionEdit/' . $param)->with('success', 'Sub Court updated.');
                        } else {
                            return redirect()->to('admin/subcourts/actionEdit/' . $param)->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->to('admin/subcourts/actionEdit/' . $param)->with('error', 'Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/subcourts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/subcourts')->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'] = "subcourts";
            if ($param) {
                $getCategory = $this->subcourtModel->where('subcourt_key', $param)->first();
                if (!empty($getCategory)) {
                    $deleteCategory = $this->subcourtModel->delete($getCategory['subcourt_id']);
                    if ($deleteCategory) {
                        return redirect()->to('admin/subcourts')->with('success', 'Sub Court deleted.');
                    } else {
                        return redirect()->to('admin/subcourts')->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/subcourts')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/subcourts')->with('error', 'Something went wrong.');
            }
        } else {
            return view('admin/login');
        }
    }

    public function getSubcatByCat()
    {
        $categoryKey = $this->request->getPost('value');
        $subs = $this->subcategoryModel->where('category_key', $categoryKey)->findAll();
        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(['status' => 'success', 'data' => $result]);
        } else {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No Sub Categories']);
        }
    }

    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/courts', $newName);
            return $newName;
        }
        return '';
    }
}