<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\CoursesModel;
use App\Models\CoursePapersModel;
use CodeIgniter\RESTful\ResourceController;

class CourseController extends BaseApiController
{
    public function getCoursesList()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            // Optionally verify user exists if needed
            $userModel = new \App\Models\UserModel();
            $user = $userModel->where('user_id', $userId)->first();
            if (!$user) {
                return $this->failNotFound('User not found.');
            }

            // Fetch departments
            $courseModel = new CoursesModel();
            $courses = $courseModel->where('row_status', 1)->findAll();

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

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    
    public function addCourse()
    {
        helper(['form']);
        $this->validate([
            'name'            => 'required|min_length[2]|max_length[255]',
            'description'  => 'required',
        ]);

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

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

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            $courseModel = new CoursesModel();

            $insertData = [
                'name'     => $this->request->getPost('name'),
                'description'     => $this->request->getPost('description'),
                'created_by' => $userId, // optional if your table supports it
                'row_status' => 1,
            ];

            if ($courseModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Courses added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert Courses.');
            }

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode/Add Courses Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getCourseById()
    {
        $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.');
            }

            $coursesModel = new \App\Models\CoursesModel();
            $courses = $coursesModel->find($id);

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

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

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateCourse()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

            $coursesModel = new \App\Models\CoursesModel();
            $existing = $coursesModel->find($id);
            if (!$existing) {
                return $this->failNotFound('Courses not found.');
            }

            $updateData = [
                'name'   => $this->request->getPost('name'),
                'description'   => $this->request->getPost('description'),
            ];

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

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

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }
    public function deleteCourses()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

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

            if (!$pubid || !is_numeric($pubid)) {
                return $this->fail('Invalid or missing news ID.');
            }

            $facultyModel = new \App\Models\CoursesModel();
            $existing = $facultyModel->find($pubid);

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

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

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


        } catch (\Exception $e) {
            log_message('error', 'Delete Courses Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getCoursePaperById()
    {
        $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.');
            }

            $coursePapersModel = new \App\Models\CoursePapersModel();
            $papers = $coursePapersModel
                ->where('course_id', $id)
                ->where('row_status', 1)
                ->findAll();

          

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

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

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

        $validationRules = [
            'paper_name'        => 'required',
            'paper_type'        => 'required',
            'calender_year'        => 'required',
            'prof_year'        => 'required',
            'paper_attachment'  => 'uploaded[paper_attachment]|max_size[paper_attachment,10240]|ext_in[paper_attachment,pdf,doc,docx,zip,rar]',
        ];

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

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

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            $coursePapersModel = new CoursePapersModel();

            // Handle file upload
            $uploadedFile = $this->request->getFile('paper_attachment');
            $filePath = null;

            if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
                $newFileName = $uploadedFile->getRandomName();
                $uploadPath = ROOTPATH . 'public/uploads/course_papers';

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

                if (!$uploadedFile->move($uploadPath, $newFileName)) {
                    return $this->fail('File move failed.');
                }

                $filePath = 'uploads/course_papers/' . $newFileName; // Relative path for browser
            } else {
                return $this->fail('Invalid or missing file.');
            }

            $insertData = [
                'course_id'   => $this->request->getPost('course_id'),
                'paper_name'  => esc($this->request->getPost('paper_name')),
                'paper_type'  => esc($this->request->getPost('paper_type')),
                'calender_year'  => esc($this->request->getPost('calender_year')),
                'prof_year'  => esc($this->request->getPost('prof_year')),
                'file'        => $filePath,
                'created_by'  => $userId,
                'row_status'  => 1,
            ];

            if ($coursePapersModel->insert($insertData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Course paper added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert course paper.');
            }

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


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

            
            $coursePapersModel = new \App\Models\CoursePapersModel();
            $papers = $coursePapersModel->find($id);

          

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

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

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

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

            // Input validation
            $rules = [
                'id' => 'required|is_natural_no_zero',
                'paper_name' => 'required',
                'paper_type' => 'required',
                'calender_year'        => 'required',
                'prof_year'        => 'required',
                'paper_attachment' => 'permit_empty|max_size[paper_attachment,10240]|ext_in[paper_attachment,pdf,doc,docx,zip,rar]',
            ];

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

            $id = $this->request->getPost('id');
            $model = new \App\Models\CoursePapersModel();
            $existing = $model->find($id);

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

            $updateData = [
                'paper_name' => $this->request->getPost('paper_name'),
                'paper_type' => $this->request->getPost('paper_type'),
                'calender_year'  => esc($this->request->getPost('calender_year')),
                'prof_year'  => esc($this->request->getPost('prof_year')),
                'updated_by' => $userId,
            ];

            // File upload
            $uploadedFile = $this->request->getFile('paper_attachment');
            if ($uploadedFile && $uploadedFile->isValid() && !$uploadedFile->hasMoved()) {
                $uploadDir = ROOTPATH . 'public/uploads/course_papers/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $newFileName = $uploadedFile->getRandomName();
                $uploadedFile->move($uploadDir, $newFileName);
                $newFilePath = 'uploads/course_papers/' . $newFileName;

                // Optional: Delete old file
                if (!empty($existing['file']) && file_exists(ROOTPATH . 'public/' . $existing['file'])) {
                    unlink(ROOTPATH . 'public/' . $existing['file']);
                }

                $updateData['file'] = $newFilePath;
            }

            // Update record
            if ($model->update($id, $updateData)) {
                return $this->respond([
                    'status' => true,
                    'message' => 'Course paper updated successfully.'
                ]);
            } else {
                return $this->failServerError('Failed to update record.');
            }

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

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

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

            if (!$paperId || !is_numeric($paperId)) {
                return $this->fail('Invalid or missing paper ID.');
            }

            $paperModel = new \App\Models\CoursePapersModel();
            $existing = $paperModel->find($paperId);

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

            // Remove associated file if it exists
            if (!empty($existing['file'])) {
                $filePath = ROOTPATH . 'public/' . $existing['file'];
                if (file_exists($filePath)) {
                    if (!unlink($filePath)) {
                        log_message('error', 'Failed to delete file: ' . $filePath);
                        // Not fatal — continue with soft delete
                    }
                }
            }

            // Soft delete
            $paperModel->update($paperId, ['row_status' => 0]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Course Paper Error: ' . $e->getMessage());
            return $this->failServerError('Server error or invalid token.');
        }
    }

    public function getPapersData()
    {
    
        try {
            $courseId = $this->request->getGet('courseId');
            $year = $this->request->getGet('year');
            
            $coursePapersModel = new \App\Models\CoursePapersModel();
            $papers = $coursePapersModel
            ->select('course_papers.*, courses.name course_name')
            ->join('courses', 'courses.id = course_papers.course_id')
            ->where('course_papers.course_id', $courseId)
            ->where('course_papers.calender_year', $year)
            ->where('course_papers.row_status', 1)
            ->findAll();

          

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

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

}

?>