<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\DepartmentModel;
use App\Models\PublicationModel;
use App\Models\NewsModel;
use App\Models\FacultyModel;
use App\Models\ResidentsModel;
use App\Models\GalleryModel;
use App\Models\PostsModel;
use CodeIgniter\RESTful\ResourceController;

class DepartmentController extends BaseApiController
{
    
    public function getDepartmentList()
    {
        // $authHeader = $this->request->getHeaderLine('Authorization');

        // if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
        //     return $this->failUnauthorized('Authorization token missing.');
        // }

        // $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            // $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            // $userId = $decoded->user_id ?? null;

            // if (!$userId) {
            //     return $this->failUnauthorized('Invalid token payload.');
            // }

            // Optionally verify user exists if needed
            // $userModel = new \App\Models\UserModel();
            // $user = $userModel->where('user_id', $userId)->first();
            // if (!$user) {
            //     return $this->failNotFound('User not found.');
            // }

            // Fetch departments
            $departmentModel = new DepartmentModel();
            $departments = $departmentModel->where('row_status', 1)->findAll();

            return $this->respond([
                'status' => 200,
                'message' => 'Departments fetched successfully.',
                'data' => $departments
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    
    public function addDepartment()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        // Validation rules
        $this->validate([
            'department_name'     => 'required|min_length[2]|max_length[255]',
            'department_info'     => 'required',
            'department_mobile'   => 'required|numeric|min_length[10]|max_length[15]',
            'department_email'    => 'required|valid_email',
            'hod_name'            => 'required',
            'hod_designation'     => 'required',
            'hod_photo'           => 'uploaded[hod_photo]|max_size[hod_photo,2048]|is_image[hod_photo]',
            'department_vision'   => 'required',
            'infrastructure'      => 'required',
            'equipment'           => 'required',
            'library_resources'   => 'required',
        ]);

        // JWT Auth check
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            // HOD image upload
            $hodImage = $this->request->getFile('hod_photo');
            $hodImageName = null;

            if ($hodImage && $hodImage->isValid() && !$hodImage->hasMoved()) {
                $uploadPath = 'uploads/department/hod/';
                if (!is_dir(FCPATH . $uploadPath)) {
                    mkdir(FCPATH . $uploadPath, 0755, true);
                }

                $hodImageName = $hodImage->getRandomName();
                $hodImage->move(FCPATH . $uploadPath, $hodImageName);
            }

            // Get and implode selected course IDs
            // $coursesArray = $this->request->getPost('courses') ?? [];
            // $coursesCsv = implode(',', $coursesArray); // This is your comma-separated string
            $coursesCsv = json_encode($this->request->getPost('courses'));
            // Prepare insert data
            $departmentModel = new DepartmentModel();
            $insertData = [
                'department_name'     => $this->request->getPost('department_name'),
                'department_info'     => $this->request->getPost('department_info'),
                'department_mobile'   => $this->request->getPost('department_mobile'),
                'department_email'    => $this->request->getPost('department_email'),
                'hod_name'            => $this->request->getPost('hod_name'),
                'hod_designation'     => $this->request->getPost('hod_designation'),
                'hod_photo'           => $hodImageName,
                'department_vision'   => $this->request->getPost('department_vision'),
                'infrastructure'      => $this->request->getPost('infrastructure'),
                'equipment'           => $this->request->getPost('equipment'),
                'library_resources'   => $this->request->getPost('library_resources'),
                'courses'          => $coursesCsv,
                'created_by'          => $userId,
                'row_status'          => 1
            ];

            if ($departmentModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Department added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert department.');
            }

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode/Add Department Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }


    public function deleteDepartment()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');

            if (!$id || !is_numeric($id)) {
                return $this->fail('Invalid department ID.');
            }

            $departmentModel = new DepartmentModel();
            $existing = $departmentModel->find($id);
            if (!$existing) {
                return $this->failNotFound('Department not found.');
            }

            // Soft delete (recommended)
            $departmentModel->update($id, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'Department deleted successfully.'
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Delete Department Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getDepartmentById()
    {
        // $authHeader = $this->request->getHeaderLine('Authorization');

        // if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
        //     return $this->failUnauthorized('Token missing');
        // }

        // $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            // $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            // $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $departmentModel = new \App\Models\DepartmentModel();
            $department = $departmentModel->find($id);

            if (!$department) {
                return $this->failNotFound('Department not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $department
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateDepartment()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');
            if (!$id || !is_numeric($id)) {
                return $this->failValidationErrors('Invalid department ID.');
            }

            $departmentModel = new \App\Models\DepartmentModel();
            $existing = $departmentModel->find($id);
            if (!$existing) {
                return $this->failNotFound('Department not found.');
            }

            // Collect posted data
            $updateData = [
                'department_name'   => $this->request->getPost('department_name'),
                'department_info'   => $this->request->getPost('department_info'),
                'department_mobile' => $this->request->getPost('department_mobile'),
                'department_email'  => $this->request->getPost('department_email'),
                'hod_name'         => $this->request->getPost('hod_name'),
                'hod_designation'  => $this->request->getPost('hod_designation'),
                'department_vision' => $this->request->getPost('department_vision'),
                'infrastructure'    => $this->request->getPost('infrastructure'),
                'equipment'         => $this->request->getPost('equipment'),
                'library_resources' => $this->request->getPost('library_resources'),
            ];

            // Handle courses array (assuming you store as JSON or related table)
            $courses = $this->request->getPost('courses');
            if ($courses && is_array($courses)) {
                // For example, store as JSON string if you don't have relational table
                $updateData['courses'] = json_encode($courses);
                // Or you can update a pivot table depending on your schema
            }

            // Handle HOD photo upload
           $file = $this->request->getFile('hod_photo');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $uploadPath = FCPATH . 'uploads/department/hod/';

                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0755, true); // ensure directory exists
                }

                $file->move($uploadPath, $newName);

                // Delete old photo
                if (!empty($existing['hod_photo'])) {
                    $oldFilePath = $uploadPath . $existing['hod_photo'];
                    if (file_exists($oldFilePath)) {
                        unlink($oldFilePath);
                    }
                }

                $updateData['hod_photo'] = $newName;
            }

            $departmentModel->update($id, $updateData);

            return $this->respond([
                'status' => true,
                'message' => 'Department updated successfully.'
            ]);

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }


    public function getDepartmentPublications()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $dept_id = $this->request->getGet('id');
             
            if (!$dept_id) {
                return $this->failValidationErrors('Department ID is required.');
            }
           
            $publicationModel = new PublicationModel();
            $publications = $publicationModel
            ->where('department_id', $dept_id)
            ->where('row_status', 1)
            ->findAll();
            
    
            // print_r($publications);
            // die;

            return $this->respond([
                'status' => true,
                'data'   => $publications
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function addPublication()
    {
        
        helper(['form']);
        $this->validate([
            'title'            => 'required',
            'description'  => 'required',
        ]);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $publicationModel = new \App\Models\PublicationModel();

            $insertData = [
                'department_id'=>$this->request->getPost('department_id'),
                'title'     => $this->request->getPost('title'),
                'description'     => $this->request->getPost('description'),
                'created_by' => $userId,
                'row_status' => 1,
            ];

            if ($publicationModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Publication added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert department.');
            }

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode/Add Department Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getPublicationById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $publicationModel = new \App\Models\PublicationModel();
            $publication = $publicationModel->find($id);

            if (!$publication) {
                return $this->failNotFound('Department not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $publication
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updatePublication()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');
            if (!$id || !is_numeric($id)) {
                return $this->failValidationErrors('Invalid department ID.');
            }

            $publicationModel = new \App\Models\PublicationModel();
            $existing = $publicationModel->find($id);
            if (!$existing) {
                return $this->failNotFound('Department not found.');
            }

            $updateData = [
                'title'   => $this->request->getPost('title'),
                'description'   => $this->request->getPost('description'),
            ];

            $publicationModel->update($id, $updateData);

            return $this->respond([
                'status' => true,
                'message' => 'Publication updated successfully.'
            ]);

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
     public function deletePublication()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $pubid = $this->request->getPost('id');


            $publicationModel = new \App\Models\PublicationModel();
            $existing = $publicationModel->find($pubid);
           

            // Soft delete (recommended)
            $publicationModel->update($pubid, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'Publication deleted successfully.'
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Delete Publication Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function getDepartmentNews()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $dept_id = $this->request->getGet('id');
             
            if (!$dept_id) {
                return $this->failValidationErrors('Department ID is required.');
            }
           
            $newsModel = new NewsModel();
            $news = $newsModel
            ->where('department_id', $dept_id)
            ->where('row_status', 1)
            ->findAll();
            
    
            // print_r($publications);
            // die;

            return $this->respond([
                'status' => true,
                'data'   => $news
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function addNews()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'title' => 'required',
            'description' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $newsModel = new \App\Models\NewsModel();

            $insertData = [
                'department_id' => $this->request->getPost('department_id'),
                'title'         => esc($this->request->getPost('title')),
                'description'   => esc($this->request->getPost('description')),
                'created_by'    => $userId,
                'row_status'    => 1,
            ];

            // Handle image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/news/', $newName);
                $insertData['image'] = 'uploads/news/' . $newName;
            } else {
                return $this->fail('Invalid or missing image.');
            }

            if ($newsModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'News added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert news.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Add News Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function getNewsById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $newsModel = new \App\Models\NewsModel();
            $news = $newsModel->find($id);

            if (!$news) {
                return $this->failNotFound('News not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $news
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateNews()
    {
        helper(['form', 'filesystem']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $newsId = $this->request->getPost('id');
            $title = $this->request->getPost('title');
            $description = $this->request->getPost('description');

            if (!$newsId || !$title || !$description) {
                return $this->failValidationErrors('All fields are required.');
            }

            $newsModel = new \App\Models\NewsModel();
            $existing = $newsModel->find($newsId);

            if (!$existing) {
                return $this->failNotFound('News not found.');
            }

            // Handle optional image upload
            $image = $this->request->getFile('image');
            $imageName = $existing['image'] ?? null;

            if ($image && $image->isValid() && !$image->hasMoved()) {
                // Optionally delete old image
                if (!empty($imageName) && file_exists(FCPATH . 'uploads/news/' . $imageName)) {
                    unlink(FCPATH . 'uploads/news/' . $imageName);
                }

                $newName = $image->getRandomName();
                $image->move(FCPATH . 'uploads/news', $newName);
                $imageName = $newName;
            }

            $updateData = [
                'title'       => esc($title),
                'description' => esc($description),
                'updated_by'  => $userId,
            ];

            if ($imageName !== null) {
                $updateData['image'] = 'uploads/news/'.$imageName;
            }

            if ($newsModel->update($newsId, $updateData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'News updated successfully.'
                ]);
            } else {
                return $this->fail('Failed to update news.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Update News Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function deleteNews()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

           $pubid = $this->request->getPost('id');

            if (!$pubid || !is_numeric($pubid)) {
                return $this->fail('Invalid or missing news ID.');
            }

            $newsModel = new \App\Models\NewsModel();
            $existing = $newsModel->find($pubid);

            if (!$existing) {
                return $this->failNotFound('News not found.');
            }

            $newsModel->update($pubid, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'News deleted successfully.'
            ]);


        } catch (\Exception $e) {
            log_message('error', 'Delete News Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getFacultyList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token payload.');
            }


            // Fetch departments
            $facultyModel = new FacultyModel();
            $faculty = $facultyModel->getFacultyWithDepartment();
            return $this->respond([
                'status' => 200,
                'message' => 'faculty fetched successfully.',
                'data' => $faculty
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addFaculty()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'name' => 'required',
            'designation' => 'required',
            'registration_no' => 'required',
            'email' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $facultyModel = new \App\Models\FacultyModel();

            $insertData = [
                'department_id' => $this->request->getPost('department_id'),
                'name'         => esc($this->request->getPost('name')),
                'designation'   => esc($this->request->getPost('designation')),
                'registration_no'   => esc($this->request->getPost('registration_no')),
                'email'   => esc($this->request->getPost('email')),
                'type' => $this->request->getPost('type'),
                'created_by'    => $userId,
                'row_status'    => 1,
            ];

            // Handle image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/faculty/', $newName1);
                $insertData['image'] = 'uploads/faculty/' . $newName1;
            } else {
                return $this->fail('Invalid or missing image.');
            }
            $publication = $this->request->getFile('publication');
            if ($publication && $publication->isValid() && !$publication->hasMoved()) {
                $newName = $publication->getRandomName();
                $publication->move(ROOTPATH . 'public/uploads/faculty/publication/', $newName);
                $insertData['publication'] = 'uploads/faculty/publication/' . $newName;
            } else {
                return $this->fail('Invalid or missing image.');
            }
            $services = $this->request->getFile('services');
            if ($services && $services->isValid() && !$services->hasMoved()) {
                $newName2 = $services->getRandomName();
                $services->move(ROOTPATH . 'public/uploads/faculty/services/', $newName2);
                $insertData['services'] = 'uploads/faculty/services/' . $newName2;
            } else {
                return $this->fail('Invalid or missing image.');
            }

            if ($facultyModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'faculty added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert news.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Add News Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getFacultyById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $facultyModel = new \App\Models\FacultyModel();
            $faculty = $facultyModel->find($id);

            if (!$faculty) {
                return $this->failNotFound('faculty not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $faculty
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateFaculty()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        // Basic validation
        if (!$this->validate([
            'id' => 'required|integer',
            'name' => 'required',
            'designation' => 'required',
            'registration_no' => 'required',
            'email' => 'required|valid_email',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $facultyModel = new \App\Models\FacultyModel();
            $facultyId = $this->request->getPost('id');

            // Check if faculty exists
            $faculty = $facultyModel->find($facultyId);
            if (!$faculty) {
                return $this->failNotFound('Faculty not found.');
            }

            $updateData = [
                'department_id' => $this->request->getPost('department_id'),
                'name'          => esc($this->request->getPost('name')),
                'designation'   => esc($this->request->getPost('designation')),
                'registration_no' => esc($this->request->getPost('registration_no')),
                'email'         => esc($this->request->getPost('email')),
                'type' => $this->request->getPost('type'),
                'updated_by'    => $userId,
                'updated_at'    => date('Y-m-d H:i:s'),
            ];

            // Handle publication file
            $publication = $this->request->getFile('publication');
            if ($publication && $publication->isValid() && !$publication->hasMoved()) {
                $newName = $publication->getRandomName();
                $publication->move(ROOTPATH . 'public/uploads/faculty/publication/', $newName);
                $updateData['publication'] = 'uploads/faculty/publication/' . $newName;

                // Optional: delete old file
                if (!empty($faculty['publication']) && file_exists(ROOTPATH . 'public/' . $faculty['publication'])) {
                    unlink(ROOTPATH . 'public/' . $faculty['publication']);
                }
            }

            // Handle services file
            $services = $this->request->getFile('services');
            if ($services && $services->isValid() && !$services->hasMoved()) {
                $newName2 = $services->getRandomName();
                $services->move(ROOTPATH . 'public/uploads/faculty/services/', $newName2);
                $updateData['services'] = 'uploads/faculty/services/' . $newName2;

                if (!empty($faculty['services']) && file_exists(ROOTPATH . 'public/' . $faculty['services'])) {
                    unlink(ROOTPATH . 'public/' . $faculty['services']);
                }
            }

            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/faculty/', $newName1);
                $updateData['image'] = 'uploads/faculty/' . $newName1;

                // Optional: delete old file
                if (!empty($faculty['image']) && file_exists(ROOTPATH . 'public/' . $faculty['image'])) {
                    unlink(ROOTPATH . 'public/' . $faculty['image']);
                }
            }

            if ($facultyModel->update($facultyId, $updateData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Faculty updated successfully.',
                ]);
            } else {
                return $this->fail('Failed to update faculty.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Update Faculty Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function deletefaculty()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

           $pubid = $this->request->getPost('id');

            if (!$pubid || !is_numeric($pubid)) {
                return $this->fail('Invalid or missing news ID.');
            }

            $facultyModel = new \App\Models\FacultyModel();
            $existing = $facultyModel->find($pubid);

            if (!$existing) {
                return $this->failNotFound('faculty not found.');
            }

            $facultyModel->update($pubid, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'faculty deleted successfully.'
            ]);


        } catch (\Exception $e) {
            log_message('error', 'Delete faculty Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getResidentsList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token payload.');
            }


            // Fetch departments
            $residentsModel = new ResidentsModel();
            $residents = $residentsModel->getResidentsWithDepartment();
            return $this->respond([
                'status' => 200,
                'message' => 'residents fetched successfully.',
                'data' => $residents
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addResidents()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'name' => 'required',
            'position' => 'required',
            'registration_no' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $residentsModel = new \App\Models\ResidentsModel();

            $insertData = [
                'department_id' => $this->request->getPost('department_id'),
                'name'         => esc($this->request->getPost('name')),
                'position'   => esc($this->request->getPost('position')),
                'registration_no'   => esc($this->request->getPost('registration_no')),
                'created_by'    => $userId,
                'row_status'    => 1,
            ];

            // Handle image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/residents/', $newName1);
                $insertData['image'] = 'uploads/residents/' . $newName1;
            } else {
                return $this->fail('Invalid or missing image.');
            }
            $publication = $this->request->getFile('publication');
            if ($publication && $publication->isValid() && !$publication->hasMoved()) {
                $newName = $publication->getRandomName();
                $publication->move(ROOTPATH . 'public/uploads/residents/publication/', $newName);
                $insertData['publication'] = 'uploads/residents/publication/' . $newName;
            } else {
                return $this->fail('Invalid or missing image.');
            }
            $services = $this->request->getFile('services');
            if ($services && $services->isValid() && !$services->hasMoved()) {
                $newName2 = $services->getRandomName();
                $services->move(ROOTPATH . 'public/uploads/residents/services/', $newName2);
                $insertData['services'] = 'uploads/residents/services/' . $newName2;
            } else {
                return $this->fail('Invalid or missing image.');
            }

            if ($residentsModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'residents added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert news.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Add News Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getResidentsById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $residentsModel = new \App\Models\ResidentsModel();
            $residents = $residentsModel->find($id);

            if (!$residents) {
                return $this->failNotFound('faculty not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $residents
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateResidents()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        // Basic validation
        if (!$this->validate([
            'id' => 'required|integer',
            'name' => 'required',
            'position' => 'required',
            'registration_no' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $residentsModel = new \App\Models\ResidentsModel();
            $residentsId = $this->request->getPost('id');

            // Check if faculty exists
            $residents = $residentsModel->find($residentsId);
            if (!$residents) {
                return $this->failNotFound('Faculty not found.');
            }

            $updateData = [
                'department_id' => $this->request->getPost('department_id'),
                'name'          => esc($this->request->getPost('name')),
                'position'   => esc($this->request->getPost('position')),
                'registration_no' => esc($this->request->getPost('registration_no')),
                'updated_by'    => $userId,
                'updated_at'    => date('Y-m-d H:i:s'),
            ];

            // Handle publication file
            $publication = $this->request->getFile('publication');
            if ($publication && $publication->isValid() && !$publication->hasMoved()) {
                $newName = $publication->getRandomName();
                $publication->move(ROOTPATH . 'public/uploads/residents/publication/', $newName);
                $updateData['publication'] = 'uploads/residents/publication/' . $newName;

                // Optional: delete old file
                if (!empty($residents['publication']) && file_exists(ROOTPATH . 'public/' . $residents['publication'])) {
                    unlink(ROOTPATH . 'public/' . $residents['publication']);
                }
            }

            // Handle services file
            $services = $this->request->getFile('services');
            if ($services && $services->isValid() && !$services->hasMoved()) {
                $newName2 = $services->getRandomName();
                $services->move(ROOTPATH . 'public/uploads/residents/services/', $newName2);
                $updateData['services'] = 'uploads/residents/services/' . $newName2;

                if (!empty($residents['services']) && file_exists(ROOTPATH . 'public/' . $residents['services'])) {
                    unlink(ROOTPATH . 'public/' . $residents['services']);
                }
            }

            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/residents/', $newName1);
                $updateData['image'] = 'uploads/residents/' . $newName1;

                // Optional: delete old file
                if (!empty($residents['image']) && file_exists(ROOTPATH . 'public/' . $residents['image'])) {
                    unlink(ROOTPATH . 'public/' . $residents['image']);
                }
            }

            if ($residentsModel->update($residentsId, $updateData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'residents updated successfully.',
                ]);
            } else {
                return $this->fail('Failed to update faculty.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Update Faculty Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
     public function deleteResidents()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

           $pubid = $this->request->getPost('id');

            if (!$pubid || !is_numeric($pubid)) {
                return $this->fail('Invalid or missing news ID.');
            }

            $facultyModel = new \App\Models\ResidentsModel();
            $existing = $facultyModel->find($pubid);

            if (!$existing) {
                return $this->failNotFound('residents not found.');
            }

            $facultyModel->update($pubid, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'Residents deleted successfully.'
            ]);


        } catch (\Exception $e) {
            log_message('error', 'Delete Residents Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getGalleryList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token payload.');
            }


            // Fetch departments
            $galleryModel = new GalleryModel();
            $gallery = $galleryModel->getGalleryWithDepartment();
            return $this->respond([
                'status' => 200,
                'message' => 'gallery fetched successfully.',
                'data' => $gallery
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addgallery()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'type' => 'required',
         
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $galleryModel = new \App\Models\GalleryModel();

            $insertData = [
                'department_id' => $this->request->getPost('department_id'),
                'type'         => esc($this->request->getPost('type')),
                'created_by'    => $userId,
                'row_status'    => 1,
            ];

            // Handle image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/gallery/', $newName1);
                $insertData['file'] = 'uploads/gallery/' . $newName1;
            } else {
                return $this->fail('Invalid or missing image.');
            }
            

            if ($galleryModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'gallery added successfully.',
                ]);
            } else {
                return $this->fail('gallery to insert news.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Add News Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getgalleryById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $galleryModel = new \App\Models\GalleryModel();
            $gallery = $galleryModel->find($id);

            if (!$gallery) {
                return $this->failNotFound('gallery not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $gallery
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateGallery()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        // Basic validation
        if (!$this->validate([
            'id' => 'required|integer',
            'type' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $galleryModel = new \App\Models\GalleryModel();
            $galleryId = $this->request->getPost('id');

            // Check if faculty exists
            $gallery = $galleryModel->find($galleryId);
            if (!$gallery) {
                return $this->failNotFound('Gallery not found.');
            }

            $updateData = [
                'department_id' => $this->request->getPost('department_id'),
                'type'         => esc($this->request->getPost('type')),
                'updated_by'    => $userId,
                'updated_at'    => date('Y-m-d H:i:s'),
            ];

           

            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName1 = $image->getRandomName();
                $image->move(ROOTPATH . 'public/uploads/gallery/', $newName1);
                $updateData['file'] = 'uploads/gallery/' . $newName1;

                // Optional: delete old file
                if (!empty($gallery['file']) && file_exists(ROOTPATH . 'public/' . $gallery['file'])) {
                    unlink(ROOTPATH . 'public/' . $gallery['file']);
                }
            }

            if ($galleryModel->update($galleryId, $updateData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'gallery updated successfully.',
                ]);
            } else {
                return $this->fail('Failed to update gallery.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Update gallery Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function deleteGallery()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
    

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');
            

            if (!$id || !is_numeric($id)) {
                return $this->fail('Invalid gallery ID.');
            }

            $galleryModel = new GalleryModel();
            $existing = $galleryModel->find($id);
            if (!$existing) {
                return $this->failNotFound('gallery not found.');
            }

            // Soft delete (recommended)
            $galleryModel->update($id, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'Gallery deleted successfully.'
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Delete Gallery Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function getPostsList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token payload.');
            }


            // Fetch departments
            $postsModel = new PostsModel();
            $posts = $postsModel->getPostsWithDepartment();
            return $this->respond([
                'status' => 200,
                'message' => 'posts fetched successfully.',
                'data' => $posts
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addPosts()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'type'    => 'required',
            'heading' => 'required',
            'description' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        // Check Authorization
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $postModel = new \App\Models\PostsModel(); // Adjust model name as needed

            $insertData = [
                'department_id' => $this->request->getPost('department_id'),
                'type'          => esc($this->request->getPost('type')),
                'heading'       => esc($this->request->getPost('heading')),
                'description'   => $this->request->getPost('description'), // Accept raw HTML from CKEditor
                'created_by'    => $userId,
                'row_status'    => 1,
            ];

            // Optional image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName = $image->getRandomName();
                $uploadPath = ROOTPATH . 'public/uploads/department/posts/';

                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0755, true);
                }

                $image->move($uploadPath, $newName);
                $insertData['file'] = 'uploads/department/posts/' . $newName;
            }

            if ($postModel->insert($insertData)) {
                return $this->respond([
                    'status'  => true,
                    'message' => 'Post added successfully.',
                ]);
            } else {
                return $this->fail('Failed to add post.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Add Post Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function deletePosts()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

           $pubid = $this->request->getPost('id');

            if (!$pubid || !is_numeric($pubid)) {
                return $this->fail('Invalid or missing news ID.');
            }

            $PostsModel = new \App\Models\PostsModel();
            $existing = $PostsModel->find($pubid);

            if (!$existing) {
                return $this->failNotFound('posts not found.');
            }

            $PostsModel->update($pubid, ['row_status' => 0]);

            return $this->respond([
                'status' => true,
                'message' => 'Posts deleted successfully.'
            ]);


        } catch (\Exception $e) {
            log_message('error', 'Delete Posts Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getPostsById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $PostsModel = new \App\Models\PostsModel();
            $posts = $PostsModel->find($id);

            if (!$posts) {
                return $this->failNotFound('posts not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $posts
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updatePosts()
    {
        helper(['form']);

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        if (!$this->validate([
            'type'        => 'required',
            'heading'     => 'required',
            'description' => 'required',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        // Check Authorization
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId  = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }
            $id = $this->request->getPost('id');
            $postModel = new \App\Models\PostsModel();
            $existingPost = $postModel->find($id);

            if (!$existingPost) {
                return $this->failNotFound('Post not found.');
            }

            $updateData = [
                'department_id' => $this->request->getPost('department_id'),
                'type'          => esc($this->request->getPost('type')),
                'heading'       => esc($this->request->getPost('heading')),
                'description'   => $this->request->getPost('description'), // Allow raw HTML
                'updated_by'    => $userId,
            ];

            // Optional image upload
            $image = $this->request->getFile('image');
            if ($image && $image->isValid() && !$image->hasMoved()) {
                $newName = $image->getRandomName();
                $uploadPath = ROOTPATH . 'public/uploads/department/posts/';

                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0755, true);
                }

                $image->move($uploadPath, $newName);
                $updateData['image'] = 'uploads/department/posts/' . $newName;

                // Optionally delete the old file if it exists
                if (!empty($existingPost['file']) && file_exists(ROOTPATH . 'public/' . $existingPost['file'])) {
                    @unlink(ROOTPATH . 'public/' . $existingPost['file']);
                }
            }

            if ($postModel->update($id, $updateData)) {
                return $this->respond([
                    'status'  => true,
                    'message' => 'Post updated successfully.',
                ]);
            } else {
                return $this->fail('Failed to update post.');
            }

        } catch (\Exception $e) {
            log_message('error', 'Update Post Exception: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getDepartmentAllDetailsById()
    {
        // Get row_status from GET param, default is 1
        $id = $this->request->getGet('id') ?? 1;

        // Load Models
        $departmentModel = new \App\Models\DepartmentModel();
        $facultyModel = new \App\Models\FacultyModel();
        $postModel = new \App\Models\PostsModel();
        $galleryModel = new \App\Models\GalleryModel();

        // Fetch Data
        $departments = $departmentModel->find($id);
        $faculty = $facultyModel
                ->where('department_id', $id)
                ->where('type', 'Faculty')
                ->findAll();
        $projects = $postModel
                ->where('department_id', $id)
                ->where('type', 'Research Projects')
                ->findAll();
        $publications = $postModel
                ->where('department_id', $id)
                ->where('type', 'Recent Publications')
                ->findAll();
        $clinical_services = $postModel
                ->where('department_id', $id)
                ->where('type', 'Clinical Services')
                ->findAll();
        $community_programs = $postModel
                ->where('department_id', $id)
                ->where('type', 'Community Programs')
                ->findAll();
        $events = $postModel
                ->where('department_id', $id)
                ->where('type', 'Recent Events')
                ->findAll();
        $gallery = $galleryModel
                ->where('department_id', $id)
                ->where('type', 'Department Gallery')
                ->findAll();

        // Return response as JSON
        return $this->response->setJSON([
            'status' => true,
            'message' => 'Departments data fetched successfully.',
            'data' => [
                'departments' => $departments,
                'faculty' => $faculty,
                'projects' => $projects,
                'publications' => $publications,
                'clinical_services' => $clinical_services,
                'community_programs' => $community_programs,
                'events' => $events,
                'gallery' => $gallery
            ]
        ]);
    }






}
