<?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 NewLawyers 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(),
            'new_lawyers' => new \App\Models\NewLawyersModel(),
            'district' => new \App\Models\DistrictModel(),
        ];

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

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

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

    public function actionAdd()
{
    $mUserId = $this->session->get('login_admin_id');
    if (!$mUserId) {
        return redirect()->to('admin/home');
    }

    $data['sidebar'] = "new_lawyers";
    if ($this->request->getMethod() === 'POST') {
        $rules = [
            'title' => 'required',
            'district' => 'required',
            // Add other required fields here
        ];

        if (!$this->validate($rules)) {
            return redirect()->to('admin/newlawyers/add')->withInput()->with('error', $this->validator->listErrors());
        }

        $mKey = $this->mGenerateRandomString();
        $data = [
            'new_lawyers_key' => $mKey,
            'new_lawyers_district_key' => $this->request->getPost('district'),
            'new_lawyers_name' => $this->request->getPost('title'),
            'new_lawyers_phone' => $this->request->getPost('phone'),
            'new_lawyers_exp' => $this->request->getPost('exp'),
            'new_lawyers_are_p' => $this->request->getPost('area_of_practice'),
            'new_lawyers_office' => $this->request->getPost('description'),
            'new_lawyers_desc' => nl2br(htmlentities($this->request->getPost('description'), ENT_QUOTES, 'UTF-8')),
            'new_lawyers_image' => $this->articleFileUpload('image', $this->request->getPost('image')),
        ];

        try {
            $result = $this->models['new_lawyers']->addParent($data);
            if ($result) {
                return redirect()->to('admin/newlawyers')->with('success', 'New lawyer added.');
            } else {
                log_message('error', 'Failed to add new lawyer. Data: ' . json_encode($data));
                return redirect()->to('admin/newlawyers/add')->withInput()->with('error', 'Failed to add new lawyer. Please try again.');
            }
        } catch (\Exception $e) {
            log_message('error', 'Exception when adding new lawyer: ' . $e->getMessage());
            return redirect()->to('admin/newlawyers/add')->withInput()->with('error', 'An error occurred. Please try again.');
        }
    }

    return view('admin/newlawyers/add', $data);
}

    public function actionEdit($param = null)
    {
        $mUserId = $this->session->get('login_admin_id');
        if ($mUserId) {
            $data['active'] = "new_lawyers";
            $data['district'] = $this->models['district']->getAllParent();
            $data['new_lawyers'] = $this->models['new_lawyers']->getAllParent();
            if ($param) {
                $getCategory = $this->models['new_lawyers']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data['new_lawyers'] = $getCategory;
                    return view('admin/edit_newlawyers', $data);
                } else {
                    return redirect()->to('admin/newlawyers')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/newlawyers')->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'] = "new_lawyers";
            if ($param) {
                $getCategory = $this->models['new_lawyers']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'new_lawyers_status' => 1,
                    ];
                    $result = $this->models['new_lawyers']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/newlawyers')->with('success', 'New Lawyer Enabled.');
                    } else {
                        return redirect()->to('admin/newlawyers')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/newlawyers')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/newlawyers')->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'] = "new_lawyers";
            if ($param) {
                $getCategory = $this->models['new_lawyers']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $data = [
                        'new_lawyers_status' => 0,
                    ];
                    $result = $this->models['new_lawyers']->updateParentByKey($param, $data);
                    if ($result) {
                        return redirect()->to('admin/newlawyers')->with('success', 'New lawyers Disabled.');
                    } else {
                        return redirect()->to('admin/newlawyers')->with('error', 'Failed. Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/newlawyers')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/newlawyers')->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'] = "new_lawyers";
            if ($param) {
                $getCategory = $this->models['new_lawyers']->getParentByKey($param);
                if (!empty($getCategory)) {
                    if ($this->request->getMethod() === 'POST') {
                        $rules = [
                            'title' => 'required',
                        ];

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

                        $mTitle = $this->request->getPost('title');
                        $mPhone = $this->request->getPost('phone');
                        $mExp = $this->request->getPost('exp');
                        $mArea = $this->request->getPost('area_of_practice');
                        $mCourt = $this->request->getPost('district');
                        $mDesc = $this->request->getPost('description');
                        $mDesc = nl2br(htmlentities($mDesc, ENT_QUOTES, 'UTF-8'));
                        $pic = $this->request->getPost('image');
                        $mToUploadProductPic = $this->articleFileUpload('image', $pic);

                        $changedImage = !empty($mToUploadProductPic) ? $mToUploadProductPic : $getCategory['subcourt_image'];

                        $data = [
                            'new_lawyers_district_key' => $mCourt,
                            'new_lawyers_name' => $mTitle,
                            'new_lawyers_phone' => $mPhone,
                            'new_lawyers_exp' => $mExp,
                            'new_lawyers_are_p' => $mArea,
                            'new_lawyers_desc' => $mDesc,
                            'new_lawyers_image' => $changedImage,
                        ];

                        $result = $this->models['new_lawyers']->updateParentByKey($param, $data);
                        if ($result) {
                            return redirect()->to('admin/newlawyers/actionEdit/' . $param)->with('success', 'New lawyer updated.');
                        } else {
                            return redirect()->to('admin/newlawyers/actionEdit/' . $param)->with('error', 'Failed. Something went wrong.');
                        }
                    } else {
                        return redirect()->to('admin/newlawyers/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'] = "new_lawyers";
            if ($param) {
                $getCategory = $this->models['new_lawyers']->getParentByKey($param);
                if (!empty($getCategory)) {
                    $deleteCategory = $this->models['new_lawyers']->deleteParentByKey($param);
                    if ($deleteCategory) {
                        return redirect()->to('admin/newlawyers')->with('success', 'New lawyer deleted.');
                    } else {
                        return redirect()->to('admin/newlawyers')->with('error', 'Failed, Something went wrong.');
                    }
                } else {
                    return redirect()->to('admin/newlawyers')->with('error', 'Record not found.');
                }
            } else {
                return redirect()->to('admin/newlawyers')->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(['status' => 'success', 'data' => $result]);
        } else {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No Sub Categories']);
        }
    }

    private function mGenerateRandomString(int $length = 25): string
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    private function articleFileUpload($mId, $mFile)
    {
        $validationRule = [
            $mId => [
                'label' => 'Image File',
                'rules' => [
                    'uploaded[' . $mId . ']',
                    'is_image[' . $mId . ']',
                    'mime_in[' . $mId . ',image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                    'max_size[' . $mId . ',100]',
                    'max_dims[' . $mId . ',1024,768]',
                ],
            ],
        ];

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

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

        if ($img->isValid() && !$img->hasMoved()) {
            $newName = $img->getRandomName();
            $img->move(FCPATH . 'uploads/courts', $newName);
            return $newName;
        }

        return '';
    }
}