<?php

namespace App\Controllers\Departments;

use App\Controllers\BaseController;

class DepartmentController extends BaseController
{
    
   public function departments()
    {
        $session = session();

        $data['page_title'] = "Departments || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['departments'] = $apiResponse['data'] ?? [];
            } else {
                $data['departments'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch department list';
            }

        } catch (\Exception $e) {
            log_message('error', 'Department API Call Failed: ' . $e->getMessage());
            $data['departments'] = [];
            $data['error'] = 'Something went wrong while fetching departments.';
        }

        return view('departments/departments', $data);
    }
    
    public function addDepartment()
    {
        $session = session();
        $userId = $session->get('user_id');
        
        if (!$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }
        
        try {
            // Use model directly
            $courseModel = model('App\Models\CoursesModel');
            $courses = $courseModel->where('row_status', 1)->findAll();
            
            $data['courses'] = $courses;
            $data['page_title'] = "Department || " . COMPANY_SHORT_NAME;
            $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content="School Management System,' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';
            
            return view('departments/add_department', $data);
            
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error: ' . $e->getMessage());
        }
    }

    public function deleteDepartment($id)
    {
       
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-department', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

           

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/departments'))->with('success', $apiResponse['message'] ?? 'Department deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete department.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function editDepartment($id)
    {
        $session = session();
        $userId = $session->get('user_id');
        
        if (!$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }
        
        try {
            // Use models directly
            $departmentModel = model('App\Models\DepartmentModel');
            $courseModel = model('App\Models\CoursesModel');
            
            $department = $departmentModel->find($id);
            
            if (!$department) {
                return redirect()->back()->with('error', 'Department not found.');
            }
            
            $courses = $courseModel->where('row_status', 1)->findAll();
            
            $data = [
                'department' => $department,
                'courses'    => $courses,
            ];
            
            return view('departments/edit_department', $data);
            
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error: ' . $e->getMessage());
        }
    }

    public function publications($id)
    {
        
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-publications', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);

         


            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['publications'] = $apiResponse['data'];
                $data['department_id'] = $id;
                return view('departments/publications', $data);
            } else {
                return redirect()->back()->with('error', 'Publications not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
     public function addPublication($department_id){
        
        $session = session();
        $data['department_id'] = $department_id;
        $data['page_title'] = "Department Publication || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/add_publication', $data);
        
    }

    public function deletePublication($id,$department_id)
    {
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-publication', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

          

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/dept-publications/'.$department_id))->with('success', $apiResponse['message'] ?? 'Publication deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete department.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function editPublication($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-publication-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['publication'] = $apiResponse['data'];
                return view('departments/edit_publication', $data);
            } else {
                return redirect()->back()->with('error', 'Publication not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }


     public function news($id)
    {
        
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-news', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);

         


            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['news'] = $apiResponse['data'];
                $data['department_id'] = $id;
                return view('departments/news', $data);
            } else {
                return redirect()->back()->with('error', 'News not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
     public function addNews($department_id){
        
        $session = session();
        $data['department_id'] = $department_id;
        $data['page_title'] = "Department News || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/add_news', $data);
        
    }

    public function deleteNews($id,$department_id)
    {

        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-news', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

          

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/dept-news/'.$department_id))->with('success', $apiResponse['message'] ?? 'News deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete news.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function editNews($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-news-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['news'] = $apiResponse['data'];
                return view('departments/edit_news', $data);
            } else {
                return redirect()->back()->with('error', 'News not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function faculty_details()
    {
        $session = session();

        $data['page_title'] = "Faculty Details || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-faculty-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['faculty'] = $apiResponse['data'] ?? [];
            } else {
                $data['faculty'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch department list';
            }

        } catch (\Exception $e) {
            log_message('error', 'Department API Call Failed: ' . $e->getMessage());
            $data['faculty'] = [];
            $data['error'] = 'Something went wrong while fetching faculty.';
        }

        return view('departments/faculty', $data);
    }
    public function addFaculty(){
        
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['departments'] = $apiResponse['data'] ?? [];
            } else {
                $data['departments'] = [];
            }
        
        $data['page_title'] = "faculty || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/add_faculty', $data);
        
    }

    public function editFaculty($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {

           


            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-faculty-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);


             $response2 = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse2 = json_decode($response2->getBody(), true);

            if (isset($apiResponse2['status']) && $apiResponse2['status'] == 200) {
                $data['departments'] = $apiResponse2['data'] ?? [];
            } else {
                $data['departments'] = [];
            }

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['faculty'] = $apiResponse['data'];
                return view('departments/edit_faculty', $data);
            } else {
                return redirect()->back()->with('error', 'Faculty not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function deleteFaculty($id)
    {

        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-faculty', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

          

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/faculty-details'))->with('success', $apiResponse['message'] ?? 'faculty deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete faculty.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    public function residents_details()
    {
        $session = session();

        $data['page_title'] = "Residents Details || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-residents-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['residents'] = $apiResponse['data'] ?? [];
            } else {
                $data['residents'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch department list';
            }

        } catch (\Exception $e) {
            log_message('error', 'Department API Call Failed: ' . $e->getMessage());
            $data['residents'] = [];
            $data['error'] = 'Something went wrong while fetching residents.';
        }

        return view('departments/residents', $data);
    }
    public function addResidents(){
        
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['departments'] = $apiResponse['data'] ?? [];
            } else {
                $data['departments'] = [];
            }
        
        $data['page_title'] = "faculty || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/add_residents', $data);
        
    }

    public function editResidents($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {

           


            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-residents-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);
           


             $response2 = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse2 = json_decode($response2->getBody(), true);

            if (isset($apiResponse2['status']) && $apiResponse2['status'] == 200) {
                $data['departments'] = $apiResponse2['data'] ?? [];
            } else {
                $data['departments'] = [];
            }

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['residents'] = $apiResponse['data'];
               
                return view('departments/edit_residents', $data);
            } else {
                return redirect()->back()->with('error', 'Faculty not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }

    public function deleteResidents($id)
    {

        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-residents', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

          

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/residents-details'))->with('success', $apiResponse['message'] ?? 'residents deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete residents.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function gallery_details()
    {
        $session = session();

        $data['page_title'] = "Gallery Details || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-gallery-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['gallery'] = $apiResponse['data'] ?? [];
            } else {
                $data['gallery'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch gallery list';
            }

        } catch (\Exception $e) {
            log_message('error', 'Department API Call Failed: ' . $e->getMessage());
            $data['gallery'] = [];
            $data['error'] = 'Something went wrong while fetching gallery.';
        }

        return view('departments/gallery', $data);
    }
    public function addGallery(){
        
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['departments'] = $apiResponse['data'] ?? [];
            } else {
                $data['departments'] = [];
            }
        
        $data['page_title'] = "gallery || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/add_gallery', $data);
        
    }

    public function editGallery($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {

           


            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-gallery-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $apiResponse = json_decode($response->getBody(), true);


             $response2 = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse2 = json_decode($response2->getBody(), true);

            if (isset($apiResponse2['status']) && $apiResponse2['status'] == 200) {
                $data['departments'] = $apiResponse2['data'] ?? [];
            } else {
                $data['departments'] = [];
            }

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $data['gallery'] = $apiResponse['data'];
                return view('departments/edit_gallery', $data);
            } else {
                return redirect()->back()->with('error', 'gallery not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function deletegallery($id)
    {
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/remove-gallery', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);
        
            $apiResponse = json_decode($response->getBody(), true);

           

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/gallery-details'))->with('success', $apiResponse['message'] ?? 'gallery deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete gallery.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }


    public function posts_details()
    {
        
        $session = session();

        $data['page_title'] = "post Details || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-posts-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['posts'] = $apiResponse['data'] ?? [];
            } else {
                $data['posts'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch posts list';
            }

        } catch (\Exception $e) {
            log_message('error', 'posts API Call Failed: ' . $e->getMessage());
            $data['gallery'] = [];
            $data['error'] = 'Something went wrong while fetching posts.';
        }

        return view('departments/posts/index', $data);
    }
     public function addPosts(){
        
        $session = session();
        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/departments/get-department-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['departments'] = $apiResponse['data'] ?? [];
            } else {
                $data['departments'] = [];
            }
        $data['page_title'] = "Add Posts || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('departments/posts/add', $data);
        
    }

    public function deletePosts($id)
    {
        $session = session();

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url().'api/departments/delete-posts', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // for local SSL
            ]);

            $apiResponse = json_decode($response->getBody(), true);

          

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/departments/posts/'))->with('success', $apiResponse['message'] ?? 'Posts deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete Posts.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function editPosts($id)
    {
        $session  = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        $client = \Config\Services::curlrequest();

        try {
            // Fetch department list
            $deptResponse = $client->get(base_url('api/departments/get-department-list'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false
            ]);

            $deptData = json_decode($deptResponse->getBody(), true);
            $data['departments'] = $deptData['data'] ?? [];

            // Fetch post by ID
            $postResponse = $client->get(base_url('api/departments/get-posts-by-id'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $postData = json_decode($postResponse->getBody(), true);

            if (!isset($postData['status']) || $postData['status'] !== true || empty($postData['data'])) {
                return redirect()->back()->with('error', 'Post not found or invalid ID.');
            }

            $data['post'] = $postData['data'];

            return view('departments/posts/edit', $data);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }




}
