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

Class Studentids extends Admin_Controller {
/*
| -----------------------------------------------------
| PRODUCT NAME: 	INILABS SCHOOL MANAGEMENT SYSTEM
| -----------------------------------------------------
| AUTHOR:			INILABS TEAM
| -----------------------------------------------------
| EMAIL:			info@inilabs.net
| -----------------------------------------------------
| COPYRIGHT:		RESERVED BY INILABS IT
| -----------------------------------------------------
| WEBSITE:			http://inilabs.net
| -----------------------------------------------------
*/
	function __construct() {
		parent::__construct();
		$this->load->model("student_m");
		$this->load->model("subjectteacher_m");
        $this->load->model("studentids_m");
		$this->load->model("teacher_m");
		$this->load->model("user_m");
		$this->load->model("studentrelation_m");
		$language = $this->session->userdata('lang');
        $this->lang->load('studentids', $language);
	}

    protected function rules()
    {
        $rules = [
            [
                'field' => 'photo',
                'label' => 'Photo',
                'rules' => 'trim|max_length[200]|xss_clean|callback_photoupload'
            ],
        ];
        return $rules;
    }

    public function index() {
		$this->data['headerassets'] = array(
			'css' => array(
				'assets/select2/css/select2.css',
				'assets/select2/css/select2-bootstrap.css'
			),
			'js' => array(
				'assets/select2/select2.js'
			)
		);
        $this->data['photos'] = $this->studentids_m->getData();
		$this->data["subview"] = "studentids/index";
		$this->load->view('_layout_main', $this->data);
	}

    public function savephoto()
	{
		if ($this->input->is_ajax_request()) {
			$userType = $this->input->post('userType');
			$identifier = $this->input->post('identifier');
			$imageData = $this->input->post('imageData');

			if (empty($userType) || empty($identifier) || empty($imageData)) {
				echo json_encode(['success' => false, 'message' => 'Invalid input']);
				return;
			}

			// $imageData = str_replace('data:image/png;base64,', '', $imageData);
			$binaryImageData = base64_decode($imageData);
        
                    $filename = $identifier . '.png';
        
                    $filePath = 'uploads/images/' . $filename;
                   
                    file_put_contents($filePath, $binaryImageData);

			switch ($userType) {
				case 'Student':
					$user = $this->student_m->getStudentByAdm($identifier);
					if (!empty($user)) {
						$this->updateStudentPhoto($identifier, $filename);
						// echo json_encode(['success' => true, 'message' => 'Photo saved for student']);
					} else {
						echo json_encode(['success' => false, 'message' => 'Student not found']);
					}
					break;

				case 'Teacher':
					$user = $this->teacher_m->get_single_teacher(['teacherID' => $identifier]);
					if (!empty($user)) {
						$this->updateTeacherPhoto($user->teacherID, $filename);
						
					} else {
						echo json_encode(['success' => false, 'message' => 'Teacher not found']);
					}
					break;

				case 'User':
					$user = $this->user_m->get_single_user(['userID' => $identifier]);
					if (!empty($user)) {
						$this->updateUserPhoto($user->userID, $filename);
						// echo json_encode(['success' => true, 'message' => 'Photo saved for user']);
					} else {
						echo json_encode(['success' => false, 'message' => 'User not found']);
					}
					break;

				default:
					echo json_encode(['success' => false, 'message' => 'Invalid user type']);
			}

			$exists = $this->studentids_m->getStudent($identifier);
			if (empty($exists)) {
				$this->studentids_m->insert_photo(['registerNO' => $identifier, 'name'=>$user->name, 'photo' => $filename, 'userType'=> $userType]);
			}else{
				$this->studentids_m->update_data(['photo' => $filename], $exists[0]->studentidsID);
			}
            $data = $this->studentids_m->getData();
            echo json_encode(['success' => true, 'message' => 'Photo saved for teacher', 'photos'=> $data ]);
		} else {
			show_404();
		}
	}

	private function updateStudentPhoto($registerNO, $filename)
	{		
		$student = $this->student_m->getStudentByAdm($registerNO);
		$this->student_m->update_student(['photo' => $filename], $student[0]->studentID);
	}

	private function updateTeacherPhoto($teacherID, $filename)
	{
		$this->teacher_m->update_teacher(['photo' => $filename], $teacherID);
	}

	private function updateUserPhoto($userID, $filename)
	{
		$this->user_m->update_user(['photo' => $filename], $userID);
	}

    public function savephotoo() {
        if ($this->input->is_ajax_request()) {

            $userType = $this->input->post('userType');

            if($userType == 'Student'){
                $student = $this->student_m->getStudentByAdm($this->input->post('registerNO'));

                if (!empty($student)) {
                    $imageData = $this->input->post('imageData');
    
                    $binaryImageData = base64_decode($imageData);
        
                    $filename = $this->input->post('registerNO') . '.png';
        
                    $filePath = 'uploads/images/' . $filename;
        
                    $folderPath = 'uploads/images';
                   
                    file_put_contents($filePath, $binaryImageData);
                    $exists = $this->studentids_m->getStudent($this->input->post('registerNO'));
                    if(empty($exists)){
                        $array = array(
                            'registerNO' => $this->input->post('registerNO'),
                            'photo' => $filename
                        );
                        $this->studentids_m->insert_photo($array);
                    }                
                    $data = $this->studentids_m->getData();
                    $array = array(
                        'photo' => $filename
                    );
                    $this->student_m->update_student($array, $student[0]->studentID);
        
                    $response = array('success' => true, 'message' => 'Photo captured successfully', 'photos'=>$data);
                } else {
                    $response = array('success' => false, 'message' => 'Student does not exist');
                }
            }elseif($userType == 'Teacher'){
                $array['photo']       = $this->upload_data['file']['file_name'];
            }elseif($userType == 'User'){
                
            }
            echo json_encode($response);
        } else {
            show_404();
        }
    }

    public function delete($id){
        $student = $this->studentids_m->getStudent($id);

        if(config_item('demo') == FALSE) {
            if($student[0]->photo != 'default.png' && $student[0]->photo != 'defualt.png') {
                if(file_exists(FCPATH.'uploads/images/'.$student[0]->photo)) {
                    unlink(FCPATH.'uploads/images/'.$student[0]->photo);
                }
            }
        }
        $this->studentids_m->delete_student($id);

        redirect(base_url("studentids/index"));
    }

}