<?php

namespace App\Controllers\Library;

use App\Controllers\BaseController;

class LibraryController extends BaseController
{
    public function editLibrary()
    {
        $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();

            // 1. Get department data by ID
            $responseDept = $client->get(base_url('api/library/get-library-info'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => 1
                ],
                'verify' => false
            ]);
          
            $deptData = json_decode($responseDept->getBody(), true);
            



            $data = [
                'library' => $deptData['data'] ?? [], 
            ];
            
           
            return view('library/edit_library', $data);

        
    }
    public function collection_details()
    {
        $session = session();

        $data['page_title'] = "Library || " . 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/library/get-library-collection', [
                '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['collection'] = $apiResponse['data'] ?? [];
            } else {
                $data['collection'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch collection list';
            }

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

        return view('library/collection/index', $data);
    }
    public function addCollection(){
        
        $session = session();
        $jwtToken = session('jwt_token');
        $userId = session('user_id');

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

        $data['page_title'] = "Add Collection || " . 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('library/collection/add', $data);
        
    }
    public function deleteCollection($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/library/delete-collection', [
                '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/library/collection/'))->with('success', $apiResponse['message'] ?? 'Collection deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete collection.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    public function editCollection($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 post by ID
            $postResponse = $client->get(base_url('api/library/get-library-collection-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['collection'] = $postData['data'];

            return view('library/collection/edit', $data);

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

        $data['page_title'] = "Library 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">';

        $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/library/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', 'gallery API Call Failed: ' . $e->getMessage());
            $data['collection'] = [];
            $data['error'] = 'Something went wrong while fetching gallery.';
        }

        return view('library/gallery/index', $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',
            ]);
        }

        $data['page_title'] = "Add 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('library/gallery/add', $data);
        
    }
    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/library/delete-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/library/gallery/'))->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 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();

            // 1. Get gallery data by ID
            $responseGallery = $client->get(base_url('api/library/get-gallery-by-id'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $galleryData = json_decode($responseGallery->getBody(), true);

            if (!isset($galleryData['status']) || $galleryData['status'] !== true) {
                return redirect()->back()->with('error', 'Gallery not found.');
            }

           

            $data = [
                'gallery'    => $galleryData['data'],               // gallery details
            ];

            return view('library/gallery/edit', $data);

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

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

        $data['page_title'] = "Library 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">';

        $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/library/get-team-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['team'] = $apiResponse['data'] ?? [];
            } else {
                $data['team'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch gallery list';
            }

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

        return view('library/team/index', $data);
    }
    public function addTeam(){
        
        $session = session();
        $jwtToken = session('jwt_token');
        $userId = session('user_id');

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

        $data['page_title'] = "Add Team || " . 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('library/team/add', $data);
        
    }
    public function deleteTeam($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/library/delete-team', [
                '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/library/team/'))->with('success', $apiResponse['message'] ?? 'team deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete team.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    public function editTeam($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();

            // 1. Get gallery data by ID
            $responseGallery = $client->get(base_url('api/library/get-team-by-id'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $galleryData = json_decode($responseGallery->getBody(), true);

            if (!isset($galleryData['status']) || $galleryData['status'] !== true) {
                return redirect()->back()->with('error', 'Gallery not found.');
            }

           

            $data = [
                'team'    => $galleryData['data'],               // gallery details
            ];

            return view('library/team/edit', $data);

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

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

        $data['page_title'] = "Library Requisition Form || " . 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/library/get-form-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

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

        
            $data['form'] = $apiResponse['data'] ?? [];
           

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

        return view('library/requisition_form', $data);
    }
    public function membershipForm()
    {
        $session = session();

        $data['page_title'] = "Library Membership Form || " . 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/library/get-membership-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

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

        
            $data['form'] = $apiResponse['data'] ?? [];
           

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

        return view('library/membership_form', $data);
    }

}
?>