<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * @package : Ramom school management system
 * @version : 6.5
 * @developed by : RamomCoder
 * @support : ramomcoder@yahoo.com
 * @author url : http://codecanyon.net/user/RamomCoder
 * @filename : Subject.php
 * @copyright : Reserved RamomCoder Team
 */

class Comments extends Admin_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('subject_model');
    }

    // public function index()
    // {
    //     if (!get_permission('subject', 'is_view')) {
    //         access_denied();
    //     }


        
    //     $this->data['subjectlist'] = $this->app_lib->getTable('comments');
    //     $this->data['title'] = translate('comments_bank');
    //     $this->data['sub_page'] = 'comments/index';
    //     $this->data['main_menu'] = 'comments';
    //     $this->load->view('layout/index', $this->data);
    // }





    public function index()
    {
        if (!get_permission('subject', 'is_view')) {
            access_denied();
        }
    
        $this->db->select('comments.*, subject.name as subject_name, branch.name as branch_name');
        $this->db->from('comments');
        $this->db->join('subject', 'comments.subject_id = subject.id', 'left'); 
        $this->db->join('branch', 'comments.branch_id = branch.id', 'left'); // Ensure branch name is retrieved
        $this->data['subjectlist'] = $this->db->get()->result_array();
    
        $this->data['title'] = translate('comments_bank');
        $this->data['sub_page'] = 'comments/index';
        $this->data['main_menu'] = 'comments';
        $this->load->view('layout/index', $this->data);
    }
    



    // subject edit page
    public function edit($id = '')
    {
        // if (!get_permission('comments', 'is_edit')) {
        //     access_denied();
        // }

        $this->data['subject'] = $this->app_lib->getTable('comments', array('t.id' => $id), true);
        $this->data['title'] = translate('comments');
        $this->data['sub_page'] = 'comments/edit';
        $this->data['main_menu'] = 'subject';
        $this->load->view('layout/index', $this->data);
    }


    public function get_comments()
    {
        $this->load->database();
        
        $this->db->distinct();
        $this->db->select('comment');
        
        if (is_superadmin_loggedin()) {
            $branch_id = $this->input->post('branch_id');
        } else {
            $branch_id = get_loggedin_branch_id();
        }
        
        $this->db->where('branch_id', $branch_id);
        $this->db->where('comment IS NOT NULL', null, false);
        $query = $this->db->get('comments');
        $comments = $query->result_array();
    
        $commentList = [];
        foreach ($comments as $row) {
            $commentList[] = $row['comment'];
        }
    
        echo json_encode([
            'status' => 'success',
            'comments' => $commentList
        ]);
    }
    



//     public function getSubjectsByBranch()
// {
//     $branch_id = $this->input->post('branch_id');
    
//     if (empty($branch_id)) {
//         echo json_encode(['error' => translate('invalid_branch_id')]);
//         return;
//     }

//     $this->db->where('branch_id', $branch_id);
//     $subjects = $this->db->get('subject')->result_array(); // Make sure 'subjects' is your table name

//     $subjectList = array();
//     foreach ($subjects as $subject) {
//         $subjectList[$subject['id']] = $subject['name']; // Adjust based on your table columns
//     }

//     echo json_encode($subjectList);
// }


public function getSubjectsByBranch()
{
    $branch_id = $this->input->post('branch_id');
    $user_id = get_loggedin_user_id(); // Get logged-in user ID
    $role_id = loggedin_role_id(); // Get logged-in user role ID

    if (empty($branch_id)) {
        echo json_encode(['error' => translate('invalid_branch_id')]);
        return;
    }

    if ($role_id == 3) { 
        // If the logged-in user is a teacher, join with subject_assign
        $this->db->select('subject.id, subject.name');
        $this->db->from('subject_assign');
        $this->db->join('subject', 'subject_assign.subject_id = subject.id');
        $this->db->where('subject_assign.branch_id', $branch_id);
        $this->db->where('subject_assign.teacher_id', $user_id);
        $subjects = $this->db->get()->result_array();
    } else { 
        // For other roles (e.g., admin), get all subjects for the branch
        $this->db->where('branch_id', $branch_id);
        $subjects = $this->db->get('subject')->result_array();
    }

    $subjectList = array();
    foreach ($subjects as $subject) {
        $subjectList[$subject['id']] = $subject['name']; // Adjust based on your table columns
    }

    echo json_encode($subjectList);
}




    // moderator subject all information
    // public function save()
    // {
    //     if ($_POST) {
    //         if (is_superadmin_loggedin()) {
    //             $this->form_validation->set_rules('branch_id', translate('branch'), 'required');
    //         }
    //         $this->form_validation->set_rules('comment', translate('comment'), 'trim|required');
    //         $this->form_validation->set_rules('comment_code', translate('comment_code'), 'trim|required');
           
    //         if ($this->form_validation->run() !== false) {
    //             $arraySubject = array(
    //                 'comment' => $this->input->post('comment'),
    //                 'comment_code' => $this->input->post('comment_code'),
                   
    //                 'branch_id' => $this->application_model->get_branch_id(),
    //             );
    //             $subjectID = $this->input->post('subject_id');
    //             if (empty($subjectID)) {
    //                 if (get_permission('comments', 'is_add')) {
    //                     $this->db->insert('comments', $arraySubject);
    //                 }
    //                 set_alert('success', translate('information_has_been_saved_successfully'));
    //             } else {
    //                 if (get_permission('comments', 'is_edit')) {
    //                     if (!is_superadmin_loggedin()) {
    //                         $this->db->where('branch_id', get_loggedin_branch_id());
    //                     }
    //                     $this->db->where('id', $subjectID);
    //                     $this->db->update('comments', $arraySubject);
    //                 }
    //                 set_alert('success', translate('information_has_been_updated_successfully'));
    //             }
    //             $url = base_url('comments/index');
    //             $array = array('status' => 'success', 'url' => $url);
    //         } else {
    //             $error = $this->form_validation->error_array();
    //             $array = array('status' => 'fail', 'error' => $error);
    //         }
    //         echo json_encode($array);
    //     }
    // }



    public function save()
{
    if ($_POST) {
        $this->load->library('form_validation');

        if (is_superadmin_loggedin()) {
            $this->form_validation->set_rules('branch_id', translate('branch'), 'required');
        }
        $this->form_validation->set_rules('comment', translate('comment'), 'trim|required');
        $this->form_validation->set_rules('comment_code', translate('comment_code'), 'trim|required');
        $this->form_validation->set_rules('subject_id', translate('subject'), 'required');

        if ($this->form_validation->run() !== false) {
            $comment = $this->input->post('comment');
            $comment_code = $this->input->post('comment_code');
            $branch_id = $this->input->post('branch_id');
            $subjectID = $this->input->post('subject_id');
            $commentID = $this->input->post('comment_id'); // Hidden field for updating

            // Check if comment or comment_code already exists for the given branch_id and subject_id
            $this->db->where('branch_id', $branch_id);
            $this->db->where('subject_id', $subjectID);
            $this->db->group_start()
                     ->where('comment', $comment)
                     ->or_where('comment_code', $comment_code)
                     ->group_end();

            if (!empty($commentID)) {
                $this->db->where('id !=', $commentID); // Exclude current record for updates
            }

            $exists = $this->db->get('comments')->num_rows();

            if ($exists > 0) {
                $array = array(
                    'status' => 'fail',
                    'error' => array(
                        'comment' => translate('comment_or_code_already_exists_for_branch')
                    )
                );
            } else {
                $data = array(
                    'comment' => $comment,
                    'comment_code' => $comment_code,
                    'branch_id' => $branch_id,
                    'subject_id' => $subjectID
                );

                if (empty($commentID)) { // Save new comment
                   // if (get_permission('comments', 'is_add')) {    }
                        $this->db->insert('comments', $data);
                        set_alert('success', translate('information_has_been_saved_successfully'));
                
                } else { // Update existing comment
                  //  if (get_permission('comments', 'is_edit')) {    }
                        if (!is_superadmin_loggedin()) {
                            $this->db->where('branch_id', get_loggedin_branch_id());
                        }
                        $this->db->where('id', $commentID);
                        $this->db->update('comments', $data);
                        set_alert('success', translate('information_has_been_updated_successfully'));
                
                }

                $url = base_url('comments/index');
                $array = array('status' => 'success', 'url' => $url);
            }
        } else {
            $error = $this->form_validation->error_array();
            $array = array('status' => 'fail', 'error' => $error);
        }

        echo json_encode($array);
    }
}


public function update()
{
    if ($_POST) {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('comment_id', translate('comment_id'), 'required');
        $this->form_validation->set_rules('comment', translate('comment'), 'trim|required');
        $this->form_validation->set_rules('comment_code', translate('comment_code'), 'trim|required');
        $this->form_validation->set_rules('subject_id', translate('subject'), 'required');

        if ($this->form_validation->run() !== false) {
            $commentID = $this->input->post('comment_id');
            $comment = $this->input->post('comment');
            $comment_code = $this->input->post('comment_code');
            $branch_id = $this->input->post('branch_id');
            $subjectID = $this->input->post('subject_id');

            // Check if the comment or comment_code already exists (excluding the current comment)
            $this->db->where('branch_id', $branch_id);
            $this->db->where('subject_id', $subjectID);
            $this->db->group_start()
                     ->where('comment', $comment)
                     ->or_where('comment_code', $comment_code)
                     ->group_end();
            $this->db->where('id !=', $commentID); 

            $exists = $this->db->get('comments')->num_rows();

            if ($exists > 0) {
                $array = array(
                    'status' => 'fail',
                    'error' => array(
                        'comment' => translate('comment_or_code_already_exists_for_branch')
                    )
                );
            } else {
                $data = array(
                    'comment' => $comment,
                    'comment_code' => $comment_code,
                    'subject_id' => $subjectID,
                    'branch_id' => $branch_id  // Ensure branch_id is included
                );

                log_message('debug', 'Update Data: ' . json_encode($data)); // Debug log

                if (!is_superadmin_loggedin()) {
                    $data['branch_id'] = get_loggedin_branch_id(); // Restrict non-superadmins
                }

                $this->db->where('id', $commentID);
                $this->db->update('comments', $data);
                set_alert('success', translate('information_has_been_updated_successfully'));

                $url = base_url('comments/index');
                $array = array('status' => 'success', 'url' => $url);
            }
        } else {
            $error = $this->form_validation->error_array();
            $array = array('status' => 'fail', 'error' => $error);
        }

        echo json_encode($array);
    }
}







public function get_suggestions() {
    $this->load->database();
    $term = $this->input->post('subject_id'); // Get the typed text
    $this->db->like('comment', $term); // Search in the comment field
    $this->db->limit(10); // Limit the results
    $query = $this->db->get('comments'); // Fetch from the 'comments' table

    $suggestions = [];
    foreach ($query->result() as $row) {
        $suggestions[] = $row->comment_value;
    }

    echo json_encode($suggestions);
}





// public function getSubjectsByBranch() {
//     if (is_superadmin_loggedin()) {
//         $branch_id = $this->input->post('branch_id');
//     } else {
//         $branch_id = get_loggedin_branch_id();
//     }

//     if (empty($branch_id)) {
//         echo json_encode(['error' => 'Branch ID not found']);
//         return;
//     }

//     $subjects = $this->subject_model->getSubjectsByBranch($branch_id)->result_array();

//     $data = [];
//     foreach ($subjects as $row) {
//         $data[$row['subject_id']] = $row['subjectname'];
//     }

//     echo json_encode($data);
// }


// public function getSubjectsByBranch() {
//     $this->load->model('subject_model');
//     $this->load->library('session');

//     $branch_id = is_superadmin_loggedin() ? $this->input->post('branch_id') : get_loggedin_branch_id();
//     $role_id = loggedin_role_id();
//     $user_id = get_loggedin_user_id();

//     log_message('error', 'Role ID: ' . $role_id . ' | Branch ID: ' . $branch_id . ' | User ID: ' . $user_id);

//     if (empty($branch_id)) {
//         echo json_encode(['error' => 'Branch ID not found']);
//         return;
//     }

//     $subjects = [];
//     if ($role_id == 1 || $role_id == 2) {
//         // Superadmin and Admin can see all subjects in the branch
//         $subjects = $this->subject_model->getSubjectsByBranch($branch_id)->result_array();
//     } elseif ($role_id == 3) {
//         // Teachers (role_id = 3) can only see assigned subjects
//         $subjects = $this->subject_model->getAssignedSubjects($branch_id, $user_id)->result_array();
//     } else {
//         // Other roles should also see assigned subjects
//         $subjects = $this->subject_model->getAssignedSubjects($branch_id, $user_id)->result_array();
//     }

//     log_message('error', 'Subjects Retrieved: ' . json_encode($subjects));

//     $data = [];
//     foreach ($subjects as $row) {
//         $data[$row['subject_id']] = $row['subjectname'];
//     }

//     echo json_encode($data);
// }



    

    // public function save()
    // {
    //     if ($_POST) {
    //         if (is_superadmin_loggedin()) {
    //             $this->form_validation->set_rules('branch_id', translate('branch'), 'required');
    //         }
    //         $this->form_validation->set_rules('comment', translate('comment'), 'trim|required');
    //         $this->form_validation->set_rules('comment_code', translate('comment_code'), 'trim|required');
    
    //         if ($this->form_validation->run() !== false) {
    //             $comment = $this->input->post('comment');
    //             $comment_code = $this->input->post('comment_code');
    //             $branch_id = $this->input->post('branch_id');
    //             $subjectID = $this->input->post('subject_id');
    
    //             // Ensure subjectID is NULL or empty when not provided
    //             $subjectID = (!empty($subjectID) && $subjectID != '0') ? $subjectID : null;
    
    //             // Check if comment or comment_code already exists for the given branch_id
    //             $this->db->where('branch_id', $branch_id);
    //             $this->db->group_start()
    //                      ->where('comment', $comment)
    //                      ->or_where('comment_code', $comment_code)
    //                      ->group_end();
                
    //             if (!empty($subjectID)) {
    //                 $this->db->where('id !=', $subjectID); // Exclude current record for updates
    //             }
    
    //             $exists = $this->db->get('comments')->num_rows();
    
    //             // if ($exists > 0) {
    //             //     $array = array(
    //             //         'status' => 'fail',
    //             //         'error' => array(
    //             //             'comment' => translate('comment_or_code_already_exists_for_branch')
    //             //         )
    //             //     );
    //             // } 
    //             // else {
    //                 $arraySubject = array(
    //                     'comment' => $comment,
    //                     'comment_code' => $comment_code,
    //                     'branch_id' => $branch_id
    //                 );
    
    //                 if (empty($subjectID)) {
    //                     // Insert New Record
    //                     if (get_permission('comments', 'is_add')) {
    //                         $this->db->insert('comments', $arraySubject);
    //                     }
    //                     set_alert('success', translate('information_has_been_saved_successfully'));
    //                 } else {
    //                     // Update Existing Record
    //                     if (get_permission('comments', 'is_edit')) {
    //                         if (!is_superadmin_loggedin()) {
    //                             $this->db->where('branch_id', get_loggedin_branch_id());
    //                         }
    //                         $this->db->where('id', $subjectID);
    //                         $this->db->update('comments', $arraySubject);
    //                     }
    //                     set_alert('success', translate('information_has_been_updated_successfully'));
    //                 }
    //                 $url = base_url('comments/index');
    //                 $array = array('status' => 'success', 'url' => $url);
    //           //  }
    //         } else {
    //             $error = $this->form_validation->error_array();
    //             $array = array('status' => 'fail', 'error' => $error);
    //         }
    //         echo json_encode($array);
    //     }
    // }
    


   

    public function delete($id = '')
    {
        if (get_permission('subject', 'is_delete')) {
            $this->app_lib->check_branch_restrictions('subject', $id);
            $this->db->where('id', $id);
           // $this->db->delete('subject');
          //  $this->db->where('subject_id', $id);
            $this->db->delete('comments');
        }
    }

    // add subject assign information and delete
    public function class_assign()
    {
        if (!get_permission('subject_class_assign', 'is_view')) {
            access_denied();
        }

        $this->data['branch_id'] = $this->application_model->get_branch_id();
        $this->data['assignlist'] = $this->subject_model->getAssignList();
        $this->data['title'] = translate('group_type_assign');
        $this->data['sub_page'] = 'subject/class_assign';
        $this->data['main_menu'] = 'subject';
        $this->load->view('layout/index', $this->data);
    }

    // moderator class assign save all information
    public function class_assign_save()
    {
        if ($_POST) {
            if (get_permission('subject_class_assign', 'is_add')) {
                if (is_superadmin_loggedin()) {
                    $this->form_validation->set_rules('branch_id', translate('branch'), 'required');
                }
                $this->form_validation->set_rules('class_id', translate('group_type'), 'trim|required|callback_unique_subject_assign');
                $this->form_validation->set_rules('section_id', translate('group_name'), 'trim|required');
                $this->form_validation->set_rules('subjects[]', translate('subject'), 'trim|required');
                $this->form_validation->set_rules('term_id', translate('session_term'), 'trim|required');
                if ($this->form_validation->run() !== false) {
                    $branchID = $this->application_model->get_branch_id();
                    $arraySubject = array(
                        'class_id' => $this->input->post('class_id'),
                        'section_id' => $this->input->post('section_id'),
                        'session_id' => get_session_id(),
                        'branch_id' => $branchID,
                        'session_term_id' =>$this->input->post('term_id')
                    );

                 

                    // get class teacher details
                    $get_teacher = $this->subject_model->get('teacher_allocation', $arraySubject, true);
                  //  var_dump($get_teacher); die();
                    $subjects = $this->input->post('subjects');
                    foreach ($subjects as $subject) {
                        $arraySubject['subject_id'] = $subject;
                        $query = $this->db->get_where("subject_assign", $arraySubject);
                        if ($query->num_rows() == 0) {
                            $arraySubject['teacher_id'] = empty($get_teacher) ? 0 : $get_teacher['teacher_id'];
                            $this->db->insert('subject_assign', $arraySubject);
                        }
                    }
                    set_alert('success', translate('information_has_been_saved_successfully'));
                    $url = base_url('subject/class_assign');
                    $array = array('status' => 'success', 'url' => $url, 'error' => '');
                } else {
                    $error = $this->form_validation->error_array();
                    $array = array('status' => 'fail', 'url' => '', 'error' => $error);
                }
                echo json_encode($array);
            }
        }
    }

    // subject assign information edit
    public function class_assign_edit()
    {
        if ($_POST) {
            if (get_permission('subject_class_assign', 'is_edit')) {
                $this->form_validation->set_rules('subjects[]', translate('subject'), 'trim|required');
                if ($this->form_validation->run() !== false) {
                    $sessionID = get_session_id();
                    $classID = $this->input->post('class_id');
                    $sectionID = $this->input->post('section_id');
                    $branchID = $this->application_model->get_branch_id();
                    $arraySubject = array(
                        'class_id' => $classID,
                        'section_id' => $sectionID,
                        'session_id' => $sessionID,
                        'branch_id' => $branchID,
                    );
                    // get class teacher details
                    $get_teacher = $this->subject_model->get('teacher_allocation', $arraySubject, true);

                    $subjects = $this->input->post('subjects');
                    foreach ($subjects as $subject) {
                        $arraySubject['subject_id'] = $subject;
                        $query = $this->db->get_where("subject_assign", $arraySubject);
                        if ($query->num_rows() == 0) {
                            $arraySubject['teacher_id'] = empty($get_teacher) ? 0 : $get_teacher['teacher_id'];
                            $this->db->insert('subject_assign', $arraySubject);
                        }
                    }
                    $this->db->where_not_in('subject_id', $subjects);
                    $this->db->where('class_id', $classID);
                    $this->db->where('section_id', $sectionID);
                    $this->db->where('session_id', $sessionID);
                    $this->db->where('branch_id', $branchID);
                    $this->db->delete('subject_assign');
                    set_alert('success', translate('information_has_been_updated_successfully'));
                    $url = base_url('subject/class_assign');
                    $array = array('status' => 'success', 'url' => $url, 'error' => '');
                } else {
                    $error = $this->form_validation->error_array();
                    $array = array('status' => 'fail', 'url' => '', 'error' => $error);
                }
                echo json_encode($array);
            }
        }
    }

    public function class_assign_delete($class_id = '', $section_id = '')
    {
        if (!get_permission('subject_class_assign', 'is_delete')) {
            access_denied();
        }
        if (!is_superadmin_loggedin()) {
            $this->db->where('branch_id', get_loggedin_branch_id());
        }
        $this->db->where('class_id', $class_id);
        $this->db->where('section_id', $section_id);
        $this->db->where('session_id', get_session_id());
        $this->db->delete('subject_assign');
    }

    // validate here, if the check class assign
    public function unique_subject_assign($class_id)
    {
        $where = array(
            'class_id' => $class_id,
            'section_id' => $this->input->post('section_id'),
            'session_id' => get_session_id(),
        );
        $q = $this->db->get_where('subject_assign', $where)->num_rows();
        if ($q == 0) {
            return true;
        } else {
            $this->form_validation->set_message('unique_subject_assign', 'This class and section is already assigned.');
            return false;
        }
    }

    // teacher assign view page
    public function teacher_assign()
    {
        if (!get_permission('subject_teacher_assign', 'is_view')) {
            access_denied();
        }
        if ($_POST) {
            if (get_permission('subject_teacher_assign', 'is_add')) {
                if (is_superadmin_loggedin()) {
                    $this->form_validation->set_rules('branch_id', translate('branch'), 'required');
                }
                $this->form_validation->set_rules('staff_id', translate('group_leader'), 'trim|required');
                $this->form_validation->set_rules('class_id', translate('group_type'), 'trim|required');
                $this->form_validation->set_rules('section_id', translate('group_name'), 'trim|required');
                $this->form_validation->set_rules('subject_id', translate('subject'), 'trim|required');
                if ($this->form_validation->run() !== false) {
                    $sessionID = get_session_id();
                    $branchID = $this->application_model->get_branch_id();
                    $classID = $this->input->post('class_id');
                    $sectionID = $this->input->post('section_id');
                    $subjectID = $this->input->post('subject_id');
                    $teacherID = $this->input->post('staff_id');
                    $query = $this->db->get_where("subject_assign", array(
                        'class_id' => $classID,
                        'section_id' => $sectionID,
                        'subject_id' => $subjectID,
                        'session_id' => $sessionID,
                        'branch_id' => $branchID,
                    ));
                    if ($query->num_rows() != 0) {
                        $this->db->where('id', $query->row()->id);
                        $this->db->update('subject_assign', array('teacher_id' => $teacherID));
                    }
                    set_alert('success', translate('information_has_been_updated_successfully'));
                    $url = base_url('subject/teacher_assign');
                    $array = array('status' => 'success', 'url' => $url, 'error' => '');
                } else {
                    $error = $this->form_validation->error_array();
                    $array = array('status' => 'fail', 'url' => '', 'error' => $error);
                }
                echo json_encode($array);
                exit();
            }
        }

        $this->data['branch_id'] = $this->application_model->get_branch_id();
        $this->data['assignlist'] = $this->subject_model->getTeacherAssignList();
        $this->data['title'] = translate('group_leader_assign');
        $this->data['sub_page'] = 'subject/teacher_assign';
        $this->data['main_menu'] = 'subject';
        $this->load->view('layout/index', $this->data);
    }

    // teacher assign information moderator
    public function teacher_assign_delete($id = '')
    {
        if (get_permission('subject_teacher_assign', 'is_delete')) {
            if (!is_superadmin_loggedin()) {
                $this->db->where('branch_id', get_loggedin_branch_id());
            }
            $this->db->where('id', $id);
            $this->db->update('subject_assign', array('teacher_id' => 0));
        }
    }

    // get subject list based on class section
    public function getByClassSection()
    {
        $html = '';
        $classID = $this->input->post('classID');
        $sectionID = $this->input->post('sectionID');
        if (!empty($classID)) {
            $query = $this->subject_model->getSubjectByClassSection($classID, $sectionID);
            if ($query->num_rows() > 0) {
                $html .= '<option value="">' . translate('select') . '</option>';
                $subjects = $query->result_array();
                foreach ($subjects as $row) {
                    $html .= '<option value="' . $row['subject_id'] . '">' . $row['subjectname'] . " (" . $row['subject_code'] . ')</option>';
                }
            } else {
                $html .= '<option value="">' . translate('no_information_available') . '</option>';
            }
        } else {
            $html .= '<option value="">' . translate('select') . '</option>';
        }
        echo $html;
    }
}
