<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use App\Models\LibraryInfoModel;
use App\Models\RequisitionModel;
use App\Models\LibraryCollectionModel;
use App\Models\LibraryGalleryModel;
use App\Models\LibraryTeamModel;
use App\Models\MembershipFormModel;
use App\Models\CoursesModel;
use CodeIgniter\RESTful\ResourceController;

class LibraryController extends BaseApiController
{
    public function test()
    {
        return $this->respond(['status' => true, 'message' => 'Test method called']);
    }
    public function getLibraryData(){
        $rowStatus = $this->request->getGet('row_status') ?? 1;

        $libraryModel = new \App\Models\LibraryInfoModel();
        $collectionModel = new LibraryCollectionModel();
        $library = $libraryModel->where('row_status', $rowStatus)->first();
        $collection = $collectionModel->where('row_status', $rowStatus)->findAll();
        $galleryModel = new LibraryGalleryModel();
        $galleryList = $galleryModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
        $teamModel = new LibraryTeamModel();
        $teamList = $teamModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
        $courseModel = new CoursesModel();
        $courses = $courseModel->where('row_status', 1)->findAll();
        return $this->response->setJSON([
           'status' => true,
           'message' => 'Contact page data fetched successfully.',
           'data' => [
               'library' => $library,
               'collection' => $collection,
               'gallery' => $galleryList,
               'teams' => $teamList,
               'courses' => $courses
           ]
        ]);
    }
    public function getLibraryInfo()
    {
        
        $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.');
            }

            $libraryModel = new \App\Models\LibraryInfoModel();
            $library = $libraryModel->find($id);


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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateLibrary()
    {
        $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');
            $libraryModel = new \App\Models\LibraryInfoModel();
            $existing = $id && is_numeric($id) ? $libraryModel->find($id) : null;

            // Common form data
            $updateData = [
                'heading'             => $this->request->getPost('heading'),
                'head_name'           => $this->request->getPost('head_name'),
                'designation'         => $this->request->getPost('designation'),
                'description'         => $this->request->getPost('description'),
                'vision'              => $this->request->getPost('vision'),
                'featured_databases'  => $this->request->getPost('featured_databases'),
                'special_notes'       => $this->request->getPost('special_notes'),
                'contact_information' => $this->request->getPost('contact_information'),
                'updated_by'          => $userId,
            ];

            // Image upload logic
            $file = $this->request->getFile('image');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $uploadPath = FCPATH . 'uploads/library/';

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

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

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

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

            if ($existing) {
                // Update existing record
                $libraryModel->update($id, $updateData);
                $message = 'Library updated successfully.';
            } else {
                // Insert new record
                $updateData['created_by'] = $userId;
                $libraryModel->insert($updateData);
                $message = 'Library created successfully.';
            }

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getLibraryCollection()
    {
        $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
            $collectionModel = new LibraryCollectionModel();
            $collection = $collectionModel->where('row_status', 1)->findAll();

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

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

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

        if (!$this->validate([
            'type'    => '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\LibraryCollectionModel(); // Adjust model name as needed

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

           

            if ($postModel->insert($insertData)) {
                return $this->respond([
                    'status'  => true,
                    'message' => 'Collection 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 deleteCollection()
    {
        $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\LibraryCollectionModel();
            $existing = $PostsModel->find($pubid);

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

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

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


        } catch (\Exception $e) {
            log_message('error', 'Delete Collection Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getLibraryCollectionById()
    {
        $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\LibraryCollectionModel();
            $posts = $PostsModel->find($id);

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

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

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

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

        // 2. Validate inputs
        if (!$this->validate([
            'type'        => 'required|string',
            'description' => 'required|string',
        ])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $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.');
            }

            // 4. Load Model
            $model = new \App\Models\LibraryCollectionModel();

            $id = $this->request->getPost('id'); // If empty, insert

            $data = [
                'type'        => esc($this->request->getPost('type')),
                'description' => $this->request->getPost('description'), // CKEditor content
                'updated_by'  => $userId,
                'updated_at'  => date('Y-m-d H:i:s'),
            ];

           
            if ($id && is_numeric($id)) {
                // 6. Update
                $existing = $model->find($id);
                if (!$existing) {
                    return $this->failNotFound('Collection not found.');
                }

                $model->update($id, $data);
                $msg = 'Collection updated successfully.';
            } else {
                // 7. Insert
                $data['created_by'] = $userId;
                $data['created_at'] = date('Y-m-d H:i:s');
                $model->insert($data);
                $msg = 'Collection added successfully.';
            }

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

        } catch (\Exception $e) {
            log_message('error', 'Library update 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 or invalid.');
        }

        $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.');
            }

            $rowStatus = $this->request->getGet('row_status') ?? 1;

            $galleryModel = new LibraryGalleryModel();
            $galleryList = $galleryModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $galleryList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Gallery List 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);
        }

        // 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.');
            }

            // Validate form data
            if (!$this->validate([
                'description' => 'required',
                'image'       => 'uploaded[image]|is_image[image]|max_size[image,2048]', // Max 2MB
            ])) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

            $imageFile = $this->request->getFile('image');
            $newName = $imageFile->getRandomName();
            $uploadPath = ROOTPATH . 'public/uploads/library/gallery/';

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

            $imageFile->move($uploadPath, $newName);
            $imagePath = 'uploads/library/gallery/' . $newName;

            // Save to DB
            $galleryModel = new LibraryGalleryModel();
            $galleryModel->save([
                'image'       => $imagePath,
                'description' => $this->request->getPost('description'),
                'created_by'  => $userId,
                'created_at'  => date('Y-m-d H:i:s'),
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Gallery Add Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function deleteGallery()
    {
        // Ensure POST request
        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method.', 405);
        }

        // JWT Authentication
        $auth = $this->request->getHeaderLine('Authorization');
        if (!$auth || !str_starts_with($auth, 'Bearer ')) {
            return $this->failUnauthorized('Missing Authorization token.');
        }
        $token = trim(str_replace('Bearer', '', $auth));
        
        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;
            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }
        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }

        // Get ID from POST
        $id = $this->request->getPost('id');
        if (!$id || !is_numeric($id)) {
            return $this->failValidationErrors('Invalid gallery ID.');
        }

        $model = new LibraryGalleryModel();
        $item = $model->find($id);

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

        // Delete image file
        if (!empty($item['image'])) {
            $filePath = WRITEPATH . '../public/' . $item['image'];
            if (file_exists($filePath)) {
                @unlink($filePath);
            }
        }
        $model->update($id, ['row_status' => 0]);
        // Remove DB record
    
            return $this->respond([
                'status'  => true,
                'message' => 'Gallery item deleted successfully.'
            ]);
        

        return $this->fail('Failed to delete gallery item.');
    }
    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 \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

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

            // Optional: Check if this user owns the gallery
            // if ($gallery['user_id'] !== $userId) {
            //     return $this->failForbidden('You do not have permission to access this gallery.');
            // }

            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);
        }

        // 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 \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            $galleryId = $this->request->getPost('id');
            if (!$galleryId || !is_numeric($galleryId)) {
                return $this->failValidationErrors('Valid gallery ID is required.');
            }

            // Load model and existing gallery
            $galleryModel = new \App\Models\LibraryGalleryModel();
            $existingGallery = $galleryModel->find($galleryId);

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

            // Validate form data (image is optional)
            $validationRules = [
                'description' => 'required',
            ];

            if ($this->request->getFile('image')->isValid()) {
                $validationRules['image'] = 'uploaded[image]|is_image[image]|max_size[image,2048]';
            }

            if (!$this->validate($validationRules)) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

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

            // If image is uploaded, handle upload and replace old image
            $imageFile = $this->request->getFile('image');

            if ($imageFile && $imageFile->isValid()) {
                $newImageName = $imageFile->getRandomName();
                $uploadPath = ROOTPATH . 'public/uploads/library/gallery/';

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

                $imageFile->move($uploadPath, $newImageName);
                $newImagePath = 'uploads/library/gallery/' . $newImageName;

                // Optional: delete old image file
                if (!empty($existingGallery['image'])) {
                    $oldPath = ROOTPATH . 'public/' . $existingGallery['image'];
                    if (is_file($oldPath)) {
                        unlink($oldPath);
                    }
                }

                $updateData['image'] = $newImagePath;
            }

            // Update the gallery
            $galleryModel->update($galleryId, $updateData);

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

        } catch (\Exception $e) {
            log_message('error', 'Gallery Update Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getTeamList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing or invalid.');
        }

        $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.');
            }

            $rowStatus = $this->request->getGet('row_status') ?? 1;

            $galleryModel = new LibraryTeamModel();
            $galleryList = $galleryModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $galleryList,
            ]);

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

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

        // 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.');
            }

            // Validate form data
            if (!$this->validate([
                'name'              => 'required|string|max_length[255]',
                'designation'       => 'required|string|max_length[255]',
                'email'             => 'required|valid_email|max_length[255]',
                'small_description' => 'permit_empty|string',
                'image'             => 'uploaded[image]|is_image[image]|max_size[image,2048]' // 2MB max
            ])) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

            // Handle image upload
            $imageFile = $this->request->getFile('image');
            $newName   = $imageFile->getRandomName();
            $uploadPath = ROOTPATH . 'public/uploads/library/team/';

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

            $imageFile->move($uploadPath, $newName);
            $imagePath = 'uploads/library/team/' . $newName;

            // Save to DB
            $teamModel = new \App\Models\LibraryTeamModel();
            $teamModel->save([
                'name'              => $this->request->getPost('name'),
                'designation'       => $this->request->getPost('designation'),
                'email'             => $this->request->getPost('email'),
                'small_description' => $this->request->getPost('small_description'),
                'image'             => $imagePath,
                'row_status'        => 1,
                'created_at'        => date('Y-m-d H:i:s'),
                'updated_at'        => date('Y-m-d H:i:s'),
            ]);

            return $this->respond([
                'status'  => true,
                'message' => 'Team member added successfully.',
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Team Add Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function deleteTeam()
    {
        // Ensure POST request
        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method.', 405);
        }

        // JWT Authentication
        $auth = $this->request->getHeaderLine('Authorization');
        if (!$auth || !str_starts_with($auth, 'Bearer ')) {
            return $this->failUnauthorized('Missing Authorization token.');
        }
        $token = trim(str_replace('Bearer', '', $auth));
        
        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;
            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }
        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }

        // Get ID from POST
        $id = $this->request->getPost('id');
        if (!$id || !is_numeric($id)) {
            return $this->failValidationErrors('Invalid team ID.');
        }

        $model = new LibraryTeamModel();
        $item = $model->find($id);

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

        // Delete image file
        if (!empty($item['image'])) {
            $filePath = WRITEPATH . '../public/' . $item['image'];
            if (file_exists($filePath)) {
                @unlink($filePath);
            }
        }
        $model->update($id, ['row_status' => 0]);
        // Remove DB record
    
            return $this->respond([
                'status'  => true,
                'message' => 'team item deleted successfully.'
            ]);
        

        return $this->fail('Failed to delete gallery item.');
    }
    public function getTeamById()
    {
        $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 \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

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

            // Optional: Check if this user owns the gallery
            // if ($gallery['user_id'] !== $userId) {
            //     return $this->failForbidden('You do not have permission to access this gallery.');
            // }

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

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

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

        // 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.');
            }

            // Validate input
            if (!$this->validate([
                'id'                => 'required|numeric',
                'name'              => 'required|string|max_length[255]',
                'designation'       => 'required|string|max_length[255]',
                'email'             => 'required|valid_email|max_length[255]',
                'small_description' => 'permit_empty|string',
                'image'             => 'permit_empty|is_image[image]|max_size[image,2048]'
            ])) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

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

            $teamModel = new \App\Models\LibraryTeamModel();
            $existingTeam = $teamModel->find($teamId);

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

            // Handle image upload if new image provided
            $imagePath = $existingTeam['image']; // default to existing
            $imageFile = $this->request->getFile('image');

            if ($imageFile && $imageFile->isValid() && !$imageFile->hasMoved()) {
                $newName    = $imageFile->getRandomName();
                $uploadPath = ROOTPATH . 'public/uploads/library/team/';

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

                $imageFile->move($uploadPath, $newName);
                $imagePath = 'uploads/library/team/' . $newName;

                // Optionally delete old image (if needed)
                if (!empty($existingTeam['image']) && file_exists(ROOTPATH . 'public/' . $existingTeam['image'])) {
                    @unlink(ROOTPATH . 'public/' . $existingTeam['image']);
                }
            }

            // Update DB
            $teamModel->update($teamId, [
                'name'              => $this->request->getPost('name'),
                'designation'       => $this->request->getPost('designation'),
                'email'             => $this->request->getPost('email'),
                'small_description' => $this->request->getPost('small_description'),
                'image'             => $imagePath,
                'updated_at'        => date('Y-m-d H:i:s'),
            ]);

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

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

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

        $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.');
            }

            $rowStatus = $this->request->getGet('row_status') ?? 1;

            $formModel = new RequisitionModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Gallery List Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getMembershipFormList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing or invalid.');
        }

        $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.');
            }

            $rowStatus = $this->request->getGet('row_status') ?? 1;

            $formModel = new MembershipFormModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

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

    public function submitRequisitionForm()
    {
        helper(['form']);
        $json = $this->request->getBody();
        $input = json_decode($json, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Invalid JSON input.'
            ]);
        }
        if (
            empty($input['book_title']) ||
            empty($input['author']) ||
            empty($input['email'])
        ) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Missing required fields.'
            ]);
        }

        $formModel = new \App\Models\RequisitionModel();

        $data = [
            'book_title'    => $input['book_title'],
            'author'        => $input['author'],
            'publisher'     => $input['publisher'] ?? null,
            'isbn'          => $input['isbn'] ?? null,
            'name'          => $input['name'] ?? null,
            'email'         => $input['email'],
            'course'        => $input['course'] ?? null,
            'justification' => $input['justification'] ?? null,
            'created_by'    => 1, 
        ];

        if ($formModel->insert($data)) {
            return $this->response->setJSON([
                'status'  => 'success',
                'message' => 'Requisition submitted successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Failed to submit requisition.',
                'errors'  => $formModel->errors()
            ]);
        }
    }

    public function submitMembershipForm()
    {
        helper(['form']);

        $json = $this->request->getBody();
        $input = json_decode($json, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Invalid JSON input.'
            ]);
        }

        if (empty($input['full_name']) || empty($input['user_type']) || empty($input['email']) || empty($input['phone_no'])) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Missing required fields.'
            ]);
        }

        $formModel = new \App\Models\MembershipFormModel();

        $data = [
            'full_name'   => $input['full_name'],
            'user_type'   => $input['user_type'],
            'employee_id' => $input['employee_id'] ?? null,
            'email'       => $input['email'],
            'phone_no'    => $input['phone_no'],
            'department'  => $input['department'] ?? null,
            'created_by'  => 1,
        ];

        if ($formModel->insert($data)) {
            return $this->response->setJSON([
                'status'  => 'success',
                'message' => 'Membership form submitted successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Failed to submit Membership form.',
                'errors'  => $formModel->errors()
            ]);
        }
    }






    





}
?>