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

use App\Models\EnquiryformModel;
use App\Models\FeedbackformModel;
use App\Models\EmergencyContactsModel;
use App\Models\KeyPersonnelModel;
use App\Models\PatientServicesModel;
use App\Models\AdministrativeOfficesModel;
use CodeIgniter\RESTful\ResourceController;

class ContactController extends BaseApiController
{
    public function submitEnquiryForm(){
        helper(['form']); // Load form helper

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

        $data = [
            'name'    => $this->request->getPost('name'),
            'email'        => $this->request->getPost('email'),
            'mobile'     => $this->request->getPost('mobile'),
            'enquiry_type'          => $this->request->getPost('enquiry_type'),
            'subject'          => $this->request->getPost('subject'),
            'message'         => $this->request->getPost('message'),
        ];

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

    public function submitFeedbackForm(){
         helper(['form']); // Load form helper

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

        $data = [
            'category'    => $this->request->getPost('category'),
            'name'        => $this->request->getPost('name'),
            'email'     => $this->request->getPost('email'),
            'mobile'          => $this->request->getPost('mobile'),
            'feedback_type'          => $this->request->getPost('feedback_type'),
            'subject'         => $this->request->getPost('subject'),
            'description'         => $this->request->getPost('description'),
        ];

        if ($formModel->insert($data)) {
            return $this->response->setJSON(['status' => 'success', 'message' => 'Feedback form submitted successfully.']);
        } else {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Failed to submit Feedback form.']);
        }
    }
    public function getEnquiryFormList()
    {
        $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 EnquiryformModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'enquiry form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getFeedbackFormList()
    {
        $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 FeedbackformModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->orderBy('created_at', 'DESC')
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'feedback form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getEmergencyContactsList()
    {
        $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 EmergencyContactsModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'feedback form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addEmergencyContact(){
        $rules = [
            'heading' => 'required',
            'mobile' => 'required',
            'time' => 'required',
            'description' => 'required',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => false,
                'message' => $this->validator->getErrors()
            ]);
        }

        $model = new EmergencyContactsModel();

        $data = [
            'heading' => $this->request->getPost('heading'),
            'mobile' => $this->request->getPost('mobile'),
            'time' => $this->request->getPost('time'),
            'description' => $this->request->getPost('description'),
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => session()->get('user_id') ?? 0,
            'row_status' => 1,
        ];

        $model->save($data);

        return $this->response->setJSON([
            'status' => true,
            'message' => 'Emergency contact added successfully'
        ]);
    }
    public function getEmergencyContactById()
    {
        $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.');
            }

            $emergencyContactsModel = new \App\Models\EmergencyContactsModel();
            $contacts = $emergencyContactsModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateEmergencyContact()
    {
        $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.');
            }

            // Get and validate ID
            $id = $this->request->getPost('id');
            if (!$id || !is_numeric($id)) {
                return $this->failValidationErrors('Invalid emergency contact ID.');
            }

            // Load model and check if the contact exists
            $emergencyContactsModel = new \App\Models\EmergencyContactsModel();
            $existing = $emergencyContactsModel->find($id);
            if (!$existing) {
                return $this->failNotFound('Emergency contact not found.');
            }

            // Validate and collect form inputs
            $heading     = trim($this->request->getPost('heading'));
            $mobile      = trim($this->request->getPost('mobile'));
            $time        = trim($this->request->getPost('time'));
            $description = trim($this->request->getPost('description'));

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

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

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

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deleteEmergencyContact()
    {
        $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->failValidationErrors('Invalid or missing emergency contact ID.');
            }

            $emergencyModel = new \App\Models\EmergencyContactsModel();
            $existing = $emergencyModel->find($id);

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

            // Soft delete by updating row_status
            $emergencyModel->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Emergency Contact Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function getKeyPersonnelList()
    {
        $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 KeyPersonnelModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'feedback form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addKeyPersonnel()
    {
        $rules = [
            'name'        => 'required',
            'designation' => 'required',
            'faculty'     => 'required',
            'mobile'      => 'required',
            'email'       => 'required|valid_email',
            'time'        => 'required',
            'address'     => 'required',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status'  => false,
                'message' => $this->validator->getErrors()
            ]);
        }

        $model = new \App\Models\KeyPersonnelModel();

        // Handle optional image upload
        $imageFile = $this->request->getFile('image');
        $imagePath = null;

        if ($imageFile && $imageFile->isValid() && !$imageFile->hasMoved()) {
            $newName = $imageFile->getRandomName();
            $imageFile->move(ROOTPATH . 'public/uploads/key_personnel/', $newName);
            $imagePath = 'uploads/key_personnel/' . $newName;
        }

        $data = [
            'name'        => $this->request->getPost('name'),
            'designation' => $this->request->getPost('designation'),
            'faculty'     => $this->request->getPost('faculty'),
            'mobile'      => $this->request->getPost('mobile'),
            'email'       => $this->request->getPost('email'),
            'time'        => $this->request->getPost('time'),
            'address'     => $this->request->getPost('address'),
            'image'       => $imagePath,
            'created_at'  => date('Y-m-d H:i:s'),
            'created_by'  => session()->get('user_id') ?? 0,
            'row_status'  => 1,
        ];

        $model->save($data);

        return $this->response->setJSON([
            'status'  => true,
            'message' => 'Key personnel added successfully.'
        ]);
    }

    public function getKeyPersonnelById()
    {
        $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.');
            }

            $emergencyContactsModel = new \App\Models\KeyPersonnelModel();
            $contacts = $emergencyContactsModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateKeyPersonnel()
    {
        $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.');
            }

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

            $model = new \App\Models\KeyPersonnelModel();
            $existing = $model->find($id);

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

            // Validate required fields
            $rules = [
                'name'        => 'required',
                'designation' => 'required',
                'faculty'     => 'required',
                'mobile'      => 'required',
                'email'       => 'required|valid_email',
                'time'        => 'required',
                'address'     => 'required',
            ];

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

            // Collect data
            $data = [
                'name'        => $this->request->getPost('name'),
                'designation' => $this->request->getPost('designation'),
                'faculty'     => $this->request->getPost('faculty'),
                'mobile'      => $this->request->getPost('mobile'),
                'email'       => $this->request->getPost('email'),
                'time'        => $this->request->getPost('time'),
                'address'     => $this->request->getPost('address'),
                'updated_at'  => date('Y-m-d H:i:s'),
                'updated_by'  => $userId,
            ];

            // Handle optional image upload
            $imageFile = $this->request->getFile('image');
            if ($imageFile && $imageFile->isValid() && !$imageFile->hasMoved()) {
                $newName = $imageFile->getRandomName();
                $uploadPath = WRITEPATH . 'uploads/key_personnel/';

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

                $imageFile->move($uploadPath, $newName);
                $data['image'] = 'writable/uploads/key_personnel/' . $newName;
            }

            $model->update($id, $data);

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

        } catch (\Exception $e) {
            log_message('error', 'Update Key Personnel Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

   public function deleteKeyPersonnel()
    {
        $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->failValidationErrors('Invalid or missing personnel ID.');
            }

            $model = new \App\Models\KeyPersonnelModel();
            $existing = $model->find($id);

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

            // Soft delete
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Key Personnel Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function getPatinetServicesList()
    {
        $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 PatientServicesModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'feedback form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addPatientServices()
    {
        $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 \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Validation rules
            $rules = [
                'heading'     => 'required',
                'description' => 'required',
                'mobile'      => 'required',
                'email'       => 'required|valid_email',
                'address'     => 'required',
                'time'        => 'required'
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status' => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new PatientServicesModel();

            $data = [
                'heading'     => $this->request->getPost('heading'),
                'description' => $this->request->getPost('description'),
                'mobile'      => $this->request->getPost('mobile'),
                'email'       => $this->request->getPost('email'),
                'address'     => $this->request->getPost('address'),
                'time'        => $this->request->getPost('time'),
                'created_at'  => date('Y-m-d H:i:s'),
                'created_by'  => $userId,
                'row_status'  => 1
            ];

            $model->save($data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getPatientServicesById()
    {
        $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.');
            }

            $emergencyContactsModel = new \App\Models\PatientServicesModel();
            $contacts = $emergencyContactsModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updatePatientServices()
    {
        $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 \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Validation rules
            $rules = [
                'id'          => 'required|is_natural_no_zero',
                'heading'     => 'required',
                'description' => 'required',
                'mobile'      => 'required',
                'email'       => 'required|valid_email',
                'address'     => 'required',
                'time'        => 'required'
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status' => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

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

            $model = new PatientServicesModel();
            $existing = $model->find($id);

            if (!$existing) {
                return $this->respond([
                    'status' => false,
                    'message' => 'Patient service not found.'
                ], 404);
            }

            $data = [
                'heading'     => $this->request->getPost('heading'),
                'description' => $this->request->getPost('description'),
                'mobile'      => $this->request->getPost('mobile'),
                'email'       => $this->request->getPost('email'),
                'address'     => $this->request->getPost('address'),
                'time'        => $this->request->getPost('time'),
                'updated_at'  => date('Y-m-d H:i:s'),
                'updated_by'  => $userId
            ];

            $model->update($id, $data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deletePatientServices()
    {
        $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 \Firebase\JWT\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 or missing patient service ID.');
            }

            $model = new \App\Models\PatientServicesModel();
            $existing = $model->find($id);

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

            // Soft delete
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Patient Service Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function getAdminOfficesList()
    {
        $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 AdministrativeOfficesModel();
            $formList = $formModel
                ->where('row_status', 1)
                ->findAll();
            
            return $this->respond([
                'status' => 200,
                'data'   => $formList,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'feedback form Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addAdministrativeOffices()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Validation rules
            $rules = [
                'title'      => 'required',
                'head_name'  => 'required',
                'mobile'     => 'required',
                'email'      => 'required|valid_email',
                'address'    => 'required',
                'time'       => 'required',
                'services'   => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\AdministrativeOfficesModel();

            $data = [
                'title'      => $this->request->getPost('title'),
                'head_name'  => $this->request->getPost('head_name'),
                'mobile'     => $this->request->getPost('mobile'),
                'email'      => $this->request->getPost('email'),
                'address'    => $this->request->getPost('address'),
                'time'       => $this->request->getPost('time'),
                'services'   => $this->request->getPost('services'),
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => $userId,
                'row_status' => 1
            ];

            $model->save($data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getAdminOfficesById()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            $officeModel = new \App\Models\AdministrativeOfficesModel();
            $office = $officeModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateAdministrativeOffices()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

            // Validation rules
            $rules = [
                'title'      => 'required',
                'head_name'  => 'required',
                'mobile'     => 'required',
                'email'      => 'required|valid_email',
                'address'    => 'required',
                'time'       => 'required',
                'services'   => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\AdministrativeOfficesModel();

            // Check if the record exists
            $existing = $model->find($id);
            if (!$existing) {
                return $this->failNotFound('Administrative office not found.');
            }

            // Prepare updated data
            $data = [
                'title'      => $this->request->getPost('title'),
                'head_name'  => $this->request->getPost('head_name'),
                'mobile'     => $this->request->getPost('mobile'),
                'email'      => $this->request->getPost('email'),
                'address'    => $this->request->getPost('address'),
                'time'       => $this->request->getPost('time'),
                'services'   => $this->request->getPost('services'),
                'created_by' => $userId, // Optional: update creator if needed
                'row_status' => 1
            ];

            $model->update($id, $data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deleteAdministrativeOffices()
    {
        $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 \Firebase\JWT\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 or missing administrative office ID.');
            }

            $model = new \App\Models\AdministrativeOfficesModel();
            $existing = $model->find($id);

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

            // Soft delete
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Administrative Office Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function getOfficeHoursList()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

            $model = new \App\Models\OfficeHoursModel();
            $result = $model
                ->where('row_status', $rowStatus)
                ->findAll();

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

        } catch (\Exception $e) {
            log_message('error', 'Office Hours API Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function addOfficeHours()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Validation rules
            $rules = [
                'title' => 'required',
                'text1' => 'required'
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\OfficeHoursModel();

            $data = [
                'title'      => $this->request->getPost('title'),
                'text1'      => $this->request->getPost('text1'),
                'text2'      => $this->request->getPost('text2'),
                'text3'      => $this->request->getPost('text3'),
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => $userId,
                'row_status' => 1
            ];

            $model->save($data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getOfficeHoursById()
    {
        $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 = \Firebase\JWT\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.');
            }

            $officeHoursModel = new \App\Models\OfficeHoursModel();
            $officeHour = $officeHoursModel->find($id);

            if (!$officeHour || $officeHour['row_status'] != 1) {
                return $this->failNotFound('Office hour not found.');
            }

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateOfficeHours()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\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('Valid ID is required.');
            }

            // Validation rules
            $rules = [
                'title' => 'required',
                'text1' => 'required',
                'text2' => 'permit_empty',
                'text3' => 'permit_empty',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\OfficeHoursModel();

            $existing = $model->find($id);
            if (!$existing) {
                return $this->failNotFound('Office hour record not found.');
            }

            $data = [
                'title'      => $this->request->getPost('title'),
                'text1'      => $this->request->getPost('text1'),
                'text2'      => $this->request->getPost('text2'),
                'text3'      => $this->request->getPost('text3'),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => $userId,
                'row_status' => 1
            ];

            $model->update($id, $data);

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

        } catch (\Exception $e) {
            log_message('error', 'Update Office Hours Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deleteOfficeHours()
    {
        $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 \Firebase\JWT\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 or missing office hour ID.');
            }

            $model = new \App\Models\OfficeHoursModel();
            $existing = $model->find($id);

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

            // Soft delete
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Office Hour Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getCampusLocationsList()
    {
        $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;

            $campusModel = new \App\Models\CampusLocationsModel();
            $locations = $campusModel
                ->where('row_status', $rowStatus)
                ->findAll();

            return $this->respond([
                'status' => 200,
                'data'   => $locations,
            ]);
            
        } catch (\Exception $e) {
            log_message('error', 'Campus Locations API Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function addCampusLocation()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Validation rules
            $rules = [
                'title'       => 'required',
                'floor'       => 'required',
                'access'      => 'required',
                'parking'     => 'required',
                'departments' => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\CampusLocationsModel();

            $data = [
                'title'       => $this->request->getPost('title'),
                'floor'       => $this->request->getPost('floor'),
                'access'      => $this->request->getPost('access'),
                'parking'     => $this->request->getPost('parking'),
                'departments' => $this->request->getPost('departments'), // CSV string of departments
                'created_at'  => date('Y-m-d H:i:s'),
                'created_by'  => $userId,
                'row_status'  => 1
            ];

            $model->save($data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function getCampusLocationById()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            $campusLocationModel = new \App\Models\CampusLocationsModel();
            $campusLocation = $campusLocationModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateCampusLocation()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

            // Validation rules
            $rules = [
                'title'       => 'required',
                'floor'       => 'required',
                'access'      => 'required',
                'parking'     => 'required',
                'departments' => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\CampusLocationsModel();

            // Check if record exists
            $existing = $model->find($id);
            if (!$existing) {
                return $this->failNotFound('Campus location not found.');
            }

            // Prepare updated data
            $data = [
                'title'       => $this->request->getPost('title'),
                'floor'       => $this->request->getPost('floor'),
                'access'      => $this->request->getPost('access'),
                'parking'     => $this->request->getPost('parking'),
                'departments' => $this->request->getPost('departments'),
                'updated_by'  => $userId,
                'updated_at'  => date('Y-m-d H:i:s'),
                'row_status'  => 1
            ];

            $model->update($id, $data);

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deleteCampusLocation()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\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 or missing campus location ID.');
            }

            $model = new \App\Models\CampusLocationsModel();  // Adjust model namespace if different
            $existing = $model->find($id);

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

            // Soft delete by updating row_status to 0
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Campus Location Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    
    public function getAddressById()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $addressModel = new \App\Models\AddressModel();

            $address = $addressModel
                        ->where('row_status', 1) // optional: only active records
                        ->orderBy('id', 'DESC')
                        ->first();

            return $this->respond([
                'status' => true,
                'data'   => $address ?? [] // return blank array if null
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateAddress()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            if (!$id) {
                return $this->failValidationErrors('Address ID is required');
            }
            if (!$description) {
                return $this->failValidationErrors('Description is required');
            }

            $addressModel = new \App\Models\AddressModel();
            $address = $addressModel->find($id);

            if (!$address || $address['row_status'] != 1) {
                return $this->failNotFound('Address not found');
            }

            // Update data
            $addressModel->update($id, [
                'description' => $description,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function createAddress()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $description = $this->request->getPost('description');
            if (!$description) {
                return $this->failValidationErrors('Description is required');
            }

            $addressModel = new \App\Models\AddressModel();

            $newId = $addressModel->insert([
                'description' => $description,
                'row_status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            if (!$newId) {
                return $this->failServerError('Failed to create address');
            }

            return $this->respond([
                'status' => true,
                'message' => 'Address created successfully',
                'data' => ['id' => $newId],
            ]);

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

    public function getConnectById()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $addressModel = new \App\Models\ConnectModel();

            $address = $addressModel
                        ->where('row_status', 1) // optional: only active records
                        ->orderBy('id', 'DESC')
                        ->first();

            return $this->respond([
                'status' => true,
                'data'   => $address ?? [] // return blank array if null
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateConnect()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getPost('id');
            $facebook_link = $this->request->getPost('facebook_link');
            $twiter_link = $this->request->getPost('twiter_link');
            $youtube_link = $this->request->getPost('youtube_link');
            $linkedin_link = $this->request->getPost('linkedin_link');

            if (!$id) {
                return $this->failValidationErrors('Connect ID is required');
            }
            // Optional: you can add validations for links if needed

            $connectModel = new \App\Models\ConnectModel();
            $connect = $connectModel->find($id);

            if (!$connect || $connect['row_status'] != 1) {
                return $this->failNotFound('Connect record not found');
            }

            // Update data
            $connectModel->update($id, [
                'facebook_link' => $facebook_link,
                'twiter_link' => $twiter_link,
                'youtube_link' => $youtube_link,
                'linkedin_link' => $linkedin_link,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => $userId,
            ]);

            return $this->respond([
                'status' => true,
                'message' => 'Social media links updated successfully',
            ]);
        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }

    public function createConnect()
    {
        $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 = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $facebook_link = $this->request->getPost('facebook_link');
            $twiter_link = $this->request->getPost('twiter_link');
            $youtube_link = $this->request->getPost('youtube_link');
            $linkedin_link = $this->request->getPost('linkedin_link');

            // You can add validation here if needed

            $connectModel = new \App\Models\ConnectModel();

            $newId = $connectModel->insert([
                'facebook_link' => $facebook_link,
                'twiter_link' => $twiter_link,
                'youtube_link' => $youtube_link,
                'linkedin_link' => $linkedin_link,
                'row_status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => $userId,
            ]);

            if (!$newId) {
                return $this->failServerError('Failed to create social media links');
            }

            return $this->respond([
                'status' => true,
                'message' => 'Social media links created successfully',
                'data' => ['id' => $newId],
            ]);
        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }

    public function getContactPageData()
    {
        // Get row_status from GET param, default is 1
        $rowStatus = $this->request->getGet('row_status') ?? 1;

        // Load Models
        $emergencyModel = new \App\Models\EmergencyContactsModel();
        $personnelModel = new \App\Models\KeyPersonnelModel();
        $officesModel = new \App\Models\AdministrativeOfficesModel();
        $departmentModel = new \App\Models\DepartmentModel();
        $paitentsModel = new \App\Models\PatientServicesModel();
        $officeHoursModel = new \App\Models\OfficeHoursModel();
        $campusLocationModel = new \App\Models\CampusLocationsModel();
        $addressModel = new \App\Models\AddressModel();
        $connectModel = new \App\Models\ConnectModel();

        // Fetch Data
        $emergencyContacts = $emergencyModel->where('row_status', $rowStatus)->findAll();
        $keyPersonnel = $personnelModel->where('row_status', $rowStatus)->findAll();
        $adminOffices = $officesModel->where('row_status', $rowStatus)->findAll();
        $departments = $departmentModel->where('row_status', $rowStatus)->findAll();
        $paitent_services = $paitentsModel->where('row_status', $rowStatus)->findAll();
        $office_hours = $officeHoursModel->where('row_status', $rowStatus)->findAll();
        $campus_locations = $campusLocationModel->where('row_status', $rowStatus)->findAll();
        $address = $addressModel->where('row_status', $rowStatus)->findAll();
        $connect = $connectModel->where('row_status', $rowStatus)->findAll();

        // Return response as JSON
        return $this->response->setJSON([
            'status' => true,
            'message' => 'Contact page data fetched successfully.',
            'data' => [
                'emergency_contacts' => $emergencyContacts,
                'keypersonnel' => $keyPersonnel,
                'admin_offices' => $adminOffices,
                "departments" => $departments,
                "paitent_services" => $paitent_services,
                "office_hours" => $office_hours,
                "campus_locations" => $campus_locations,
                "address" => $address,
                "connect" => $connect
            ]
        ]);
    }
























}