<?php

namespace App\Controllers\Course;

use App\Controllers\BaseController;

class CourseController extends BaseController
{
    public function courses()
    {
        $session = session();

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

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

        return view('courses/list', $data);
    }
    public function addCourses(){
        
        $session = session();
        
        $data['page_title'] = "Courses || " . 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('courses/add', $data);
        
    }
    public function editCourse($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/courses/get-course-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['courses'] = $apiResponse['data'];
                return view('courses/edit', $data);
            } else {
                return redirect()->back()->with('error', 'courses not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function deleteCourse($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/courses/delete-courses', [
                '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/courses'))->with('success', $apiResponse['message'] ?? 'Course deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete Course.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    public function coursePapers($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/courses/get-coursepapers-by-id', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

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

           
            $data['papers'] = $apiResponse['data'];
            $data['courseid'] = $id;
            return view('courses/papers/list', $data);
            
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function addPaper($id){
        
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

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

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

        $data['course'] = $apiResponse['data'];
        
        $data['page_title'] = "Paper || " . 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('courses/papers/add', $data);
        
    }
    public function editPaper($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/courses/get-paper-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['paper'] = $apiResponse['data'];
                return view('courses/papers/edit', $data);
            } else {
                return redirect()->back()->with('error', 'courses paper not found.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
    public function deletePaper($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/courses/delete-paper', [
                '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/courses'))->with('success', $apiResponse['message'] ?? 'Course paper deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete Course.');
            }

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