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

class Admin extends Admin_Core_Controller
{

	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$data['title'] = 'Dashboard';
		$data['app_setting'] = $this->setting_model->get_all_app_setting();
		if (user()->role == 'Student' || user()->role == 'User') {
			$this->load->model('student_model');


			$product_id = user()->product;
			$this->db->select('prd_id, prd_name, prd_image, advance_payment, main_price, disocunt_price');
			$this->db->where('prd_id', $product_id);
			$data['product'] = $this->db->get('products')->row();
			$data['week_event'] = $this->student_model->getUserWeeklyDailyEvents(user()->id);
			$data['medal_report'] = $this->student_model->generateUserMedalSection(user()->id);
			$data['enrolments'] = $this->course_model->get_course_by_studement_enrole();
			$this->load->view('admin/student_lms/include/header', $data);
			$this->load->view('admin/student_lms/dashboard', $data);
			$this->load->view('admin/student_lms/include/footer', $data);
		} else {
			$this->load->view('admin/include/header', $data);
			$this->load->view('admin/dashboard', $data);
			$this->load->view('admin/include/footer', $data);
		}
	}

	public function registration()
	{
		$mobile = $this->input->post('mobile');
		$avaliablity_check = $this->user_model->check_user_avaliablity_by_mobile_no($mobile);
		if ($avaliablity_check == 1) {
			$this->session->set_userdata('error', "Mobile Number Already Taken;");
			redirect($this->agent->referrer());
		} else {
			if ($this->user_model->update_data_first_time()) {
				$this->session->set_userdata('success', "Data Successfully Updated");
				redirect($this->agent->referrer());
			} else {
				$this->session->set_userdata('error', "Data Update Faild");
				redirect($this->agent->referrer());
			}
		}
	}



	public function logout()
	{
		$this->session->unset_userdata('bcount_sess_id');
		$this->session->unset_userdata('bcount_sess_mobile');
		$this->session->unset_userdata('bcount_sess_email');
		$this->session->unset_userdata('bcount_sess_role');
		$this->session->unset_userdata('bcount_sess_status');
		$this->session->unset_userdata('bcount_sess_logged_in');
		$this->session->unset_userdata('bcount_sess_token');
		$this->session->unset_userdata('bcount_sess_app_id');
		$this->session->sess_destroy();
		redirect(base_url());
	}

	public function contact_request()
	{
		if (check_user_permission('contact_request')) {
			$data['title'] = 'All Contact';
			$data['app_setting'] = $this->setting_model->get_all_app_setting();
			$data['get_all_course_reg'] = $this->course_model->get_all_course_reg();
			$this->load->view('admin/include/header', $data);
			$this->load->view('admin/all_contact_request', $data);
			$this->load->view('admin/include/footer', $data);
		} else {
			$this->session->set_userdata('error', "You Dont Permission to Access This Page ");
			redirect(base_url() . 'admin/admin');
		}
	}

	public function trail_class_application()
	{
		if (check_user_permission('trail_class_application')) {
			$data['title'] = 'Trail Class Application';
			$data['app_setting'] = $this->setting_model->get_all_app_setting();
			$data['get_all_course_reg'] = $this->course_model->get_all_trail_class_application();
			$this->load->view('admin/include/header', $data);
			$this->load->view('admin/trail_class_application', $data);
			$this->load->view('admin/include/footer', $data);
		} else {
			$this->session->set_userdata('error', "You Dont Permission to Access This Page ");
			redirect(base_url() . 'admin/admin');
		}
	}

	function lead_management()
	{
		if (check_user_permission('lead_management')) {
			$data['title'] = 'Lead Management';
			$data['app_setting'] 	= $this->setting_model->get_all_app_setting();
			$data['all_data'] 		= $this->setting_model->get_all_contact_details();
			$this->load->view('admin/include/header', $data);
			$this->load->view('admin/lead/lead_management');
			$this->load->view('admin/include/footer');
		} else {
			$this->session->set_userdata('error', "You Dont Permission to Access This Page ");
			redirect(base_url() . 'admin/admin');
		}
	}

	function pick_lead($id)
	{
		$user_id = user()->id;

		$this->db->where('lead_id', $id);
		$status = $this->db->update('lead_management', ['lead_assign_for' => $user_id, 'lead_pick' => 1]);

		if ($status) {
			$this->session->set_userdata('success', "Lead Successfully Picked");
			redirect($this->agent->referrer());
		} else {
			$this->session->set_userdata('error', "Lead Pick Faild");
			redirect($this->agent->referrer());
		}
	}

	function generate_quot($id)
	{
		error_reporting(0); 

		$data['title'] = 'Lead Management';
		$data['app_setting'] 	= $this->setting_model->get_all_app_setting();

		$this->db->where('lead_management.lead_id', $id);
		$this->db->join('products', 'products.prd_id = lead_management.lead_product_id');
		$data['data'] 		= $this->db->get('lead_management')->row();

				$this->db->where('lead_id', $id);
				$this->db->order_by('id', 'DESC');
		$data['quote'] = $this->db->get('quotes')->row();

		$data['quots_json'] = json_decode($data['quote']->editable_json);


		$this->load->view('admin/lead/generate_quot', $data);
	}

	function generate_invoice($id)
	{
		error_reporting(0); 

		$data['title'] = 'Lead Management';
		$data['app_setting'] 	= $this->setting_model->get_all_app_setting();

		$this->db->where('lead_management.lead_id', $id);
		$this->db->join('products', 'products.prd_id = lead_management.lead_product_id');
		$data['data'] 		= $this->db->get('lead_management')->row();

				$this->db->where('lead_id', $id);
				$this->db->where('status', "approved");
				$this->db->order_by('id', 'DESC');
		$data['quote'] = $this->db->get('quotes')->row();

		$data['quots_json'] = json_decode($data['quote']->editable_json);

		$this->load->view('admin/lead/generate_invoice', $data);
	}

	function check_mobile()
	{
		$mobile = $this->input->post('mobile');
		$query = $this->db->get_where('users', ['mobile' => $mobile]);

		if ($query->num_rows() > 0) {
			echo "exists";
		} else {
			echo "available";
		}
	}

	function generate_login()
	{
		$name     = $this->input->post('name');
		$mobile   = $this->input->post('mobile');
		$password = hash("sha256", $this->input->post('password'));

		// Insert into database
		$this->db->insert('users', [
			'name' => $name,
			'mobile' => $mobile,
			'password' => $password,
			'role' => 'User',
			'status' => 'Active',
			'created_at' => date('Y-m-d H:i:s'),
			'added_by' => user()->id
		]);

		$insert_id = $this->db->insert_id();

		if ($insert_id) {

			$this->db->insert('product_purchase', [
				'pur_prd_id' => $this->input->post('lead_prd_id'),
				'pur_lead_id' => $this->input->post('lead_id'),
				'pur_user_id' => $insert_id,
				'pur_date' => date('Y-m-d'),
			]);

			$this->session->set_userdata('success', "User Successfully Added");
			redirect($this->agent->referrer());
		}
	}

	function save_quots()
	{
		$data = array(
			'subtotal'     => $this->input->post('subtotal'),
			'tax'          => $this->input->post('tax'),
			'discount'     => $this->input->post('discount'),
			'grand_total'  => $this->input->post('grand_total'),
			'emi_months'   => $this->input->post('emi_months'),
			'emi_amount'   => $this->input->post('emi_amount'),
			'emi_amount'   => $this->input->post('emi_amount'),
			'lead_id'      => $this->input->post('lead_id'),
			'emp_id'   	   => user()->id,
			'editable_json' => json_encode($this->input->post('editable_fields')), // save all texts
			'status'       => $this->input->post('status'), // draft or approved
			'created_at'   => date('Y-m-d H:i:s')
		);

		$this->db->insert('quotes', $data);
		$id = $this->db->insert_id();

		if ($data['status'] === 'approved') {
			$this->session->set_userdata('success', "Quote approved and locked!");
			redirect($this->agent->referrer());
		} else {
			$this->session->set_userdata('success', "Quote saved as draft.");
			redirect($this->agent->referrer());
		}
	}

	function change_lead_mgmt_status($status, $id)
	{
		if ($id) {
			$this->db->where('lead_id', $id);
			$data = $this->db->update('lead_management', ['lead_status' => $status]);
			echo $data;
		}
	}

	public function lesson($slug = "", $course_id = "", $lesson_id = "")
	{
		// $enroll_status = enroll_status($course_id);
		$enroll_status = 1;

		$user_id = user()->id;

		// $course_instructor_ids = array();
		// if ($this->session->userdata('user_login') != 1) {
		// 	if ($this->session->userdata('admin_login') != 1) {
		// 		redirect('home', 'refresh');
		// 	}
		// }


		$course_details = $this->course_model->get_course_by_id_for_lms($course_id)->row_array();
		// $course_instructor_ids = explode(',', $course_details['user_id']);

		// if ($course_details['course_type'] == 'general') {

		//this function saved current lesson id and return previous lesson id if $lesson_id param is empty
		$lesson_id = $this->course_model->update_last_played_lesson($course_id, $lesson_id);
		$sections = $this->course_model->get_section('course', $course_id);
		if ($sections->num_rows() > 0) {
			$page_data['sections'] = $sections->result_array();
			if ($lesson_id == "") {
				$default_section = $sections->row_array();
				$page_data['section_id'] = $default_section['id'];
				$lessons = $this->course_model->get_lessons('section', $default_section['id']);
				if ($lessons->num_rows() > 0) {
					$default_lesson = $lessons->row_array();
					$lesson_id = $default_lesson['id'];
					$page_data['lesson_id']  = $default_lesson['id'];
				}
			} else {
				$page_data['lesson_id']  = $lesson_id;
				$section_id = $this->db->get_where('lesson', array('id' => $lesson_id))->row()->section_id;
				$page_data['section_id'] = $section_id;
			}
		} else {
			$page_data['sections'] = array();
		}
		// } else if ($course_details['course_type'] == 'scorm') {
		// 	$this->load->model('addons/scorm_model');
		// 	$scorm_course_data = $this->scorm_model->get_scorm_curriculum_by_course_id($course_id);
		// 	$page_data['scorm_curriculum'] = $scorm_course_data->row_array();
		// }

		//if not admin or course owner
		// if ($this->session->userdata('role_id') != 1 && !in_array($user_id, $course_instructor_ids)) {
		// 	if ($enroll_status == 'expired') {
		// 		$this->session->set_flashdata('error_message', site_phrase('Your course accessibility has expired. You need to buy it again'));
		// 		redirect(site_url('home/course/' . slugify($course_details['title']) . '/' . $course_details['id']), 'refresh');
		// 	} elseif (!$enroll_status) {
		// 		$this->session->set_flashdata('error_message', site_phrase('You have to buy the course first'));
		// 		redirect(site_url('home/course/' . slugify($course_details['title']) . '/' . $course_details['id']), 'refresh');
		// 	}
		// }

		$lesson_details = $this->course_model->get_lessons('lesson', $lesson_id)->row_array();
		if ($lesson_details['course_id'] != $course_id) {
			$this->session->set_flashdata('error_message', site_phrase('Access denied'));
			redirect('home', 'refresh');
		}

		$page_data['lesson_details'] = $lesson_details;
		$page_data['course_details']  = $course_details;
		// $page_data['drip_content_settings']  = json_decode(get_settings('drip_content_settings'), true);
		$page_data['watch_history']  = $this->course_model->get_watch_histories($user_id, $course_id)->row_array();
		$page_data['course_id']  = $course_id;
		$page_data['page_name']  = 'lessons';
		$page_data['page_title'] = $course_details['course_heading'];
		$page_data['app_setting'] 	= $this->setting_model->get_all_app_setting();
		$this->load->view('lessons/index', $page_data);
	}

	function start_quiz($quiz_id = "", $retake = "")
	{
		$quiz_details = $this->course_model->get_lessons('lesson', $quiz_id)->row_array();

		$data['quiz_id'] = $quiz_details['id'];
		$data['user_id'] = user()->id;
		$data['user_answers'] = json_encode(array());
		$data['correct_answers'] = json_encode(array());
		$data['date_added'] = time();
		$data['date_updated'] = time();
		$data['is_submitted'] = 0;
		$data['total_obtained_marks'] = 0;

		$row = $this->db->get_where('quiz_results', array('user_id' => $data['user_id'], 'quiz_id' => $quiz_id));
		$total_attemped = $this->db->where('quiz_id', $quiz_id)->where('user_id', $data['user_id'])->get('quiz_results')->num_rows();
		if ($quiz_details['quiz_attempt'] == 0 && $row->num_rows() <= 0 || $quiz_details['quiz_attempt'] > ($total_attemped - 1)) :

			if ($this->db->get_where('quiz_results', array('user_id' => $data['user_id'], 'is_submitted' => 0, 'quiz_id' => $quiz_id))->num_rows() == 0) :
				$this->db->insert('quiz_results', $data);
			endif;
		endif;

		if ($retake != "") {
			$course_title = $this->course_model->get_course_by_id_for_lms($quiz_details['course_id'])->row('course_slug');
			redirect(base_url('admin/admin/lesson/' . slugify($course_title) . '/' . $quiz_details['course_id'] . '/' . $quiz_details['id']), 'refresh');
		}

		$page_data['quiz_questions'] = $this->db->get_where('question', array('quiz_id' => $quiz_id));
		$page_data['quiz_id'] = $quiz_id;
		$this->load->view('lessons/quiz_answer_sheet', $page_data);
	}

	function submit_quiz_answer($quiz_id = "", $question_id = "", $question_type = "")
	{

		//Quize details
		$user_id = user()->id;
		$quiz_details = $this->course_model->get_lessons('lesson', $quiz_id)->row_array();
		$total_seconds = time_to_seconds($quiz_details['duration']);
		$total_marks = json_decode($quiz_details['attachment'], true)['total_marks'];

		//Question details
		$question_details = $this->db->get_where('question', array('id' => $question_id))->row_array();


		$results = $this->db->order_by('quiz_result_id', 'desc')->get_where('quiz_results', array('quiz_id' => $quiz_id, 'user_id' => $user_id));

		if ($results->num_rows() > 0 && ($total_seconds + $results->row('date_added')) > time() || $total_seconds == 0) {
			$result = $results->row_array();
			$correct_answer_question_ids = json_decode($result['correct_answers'], true);

			$answers = $this->input->post('answer');

			$user_answers = json_decode($result['user_answers'], true);
			$user_answers[$question_id] = $answers;

			if ($question_type == 'multiple_choice') {
				$is_correct_answer = 1;
				$currect_answers = json_decode($question_details['correct_answers'], true);
				foreach ($answers as $answer) {
					if (!in_array($answer, $currect_answers)) {
						$is_correct_answer = 0;
					}
				}
				if (!is_array($answers) || count($answers) <= 0 || count($currect_answers) != count($answers)) {
					$is_correct_answer = 0;
				}
			} elseif ($question_type == 'single_choice') {
				$is_correct_answer = 0;
				$currect_answers = json_decode($question_details['correct_answers'], true);
				if (in_array($answers[0], $currect_answers)) {
					$is_correct_answer = 1;
				}
			} elseif ($question_type == 'fill_in_the_blank') {
				$is_correct_answer = 1;
				$currect_answers = json_decode(strtolower($question_details['correct_answers']), true);
				foreach ($answers as $key => $answer) {
					$answer = strtolower($answer);
					if ($answer != $currect_answers[$key]) {
						$is_correct_answer = 0;
					}
				}
				if (!is_array($answers) || count($answers) <= 0 || count($currect_answers) != count($answers)) {
					$is_correct_answer = 0;
				}
			}

			if ($is_correct_answer == 1) {
				if (!in_array($question_id, $correct_answer_question_ids)) {
					array_push($correct_answer_question_ids, $question_id);
				}
			} else {
				$updated_correct_answer_question_ids = array();
				foreach ($correct_answer_question_ids as $correct_answer_question_id) {
					if ($correct_answer_question_id != $question_id) {
						array_push($updated_correct_answer_question_ids, $correct_answer_question_id);
					}
				}
				$correct_answer_question_ids = $updated_correct_answer_question_ids;
			}

			$total_questions = $this->db->get_where('question', array('quiz_id' => $quiz_id))->num_rows();
			$data['total_obtained_marks'] = round(($total_marks / $total_questions) * count($correct_answer_question_ids), 1);

			$data['user_answers'] = json_encode($user_answers);
			$data['correct_answers'] = json_encode($correct_answer_question_ids);
			$data['date_updated'] = time();
			$this->db->where('user_id', $user_id);
			$this->db->where('quiz_id', $quiz_id);
			$this->db->where('is_submitted', 0);
			$this->db->update('quiz_results', $data);
		} else {
			$this->finish_quize_submission($quiz_id);
			$response['status'] = 'time_over';
			$response['message'] = site_phrase('time_over');
			echo json_encode($response);
		}
	}

	function finish_quize_submission($quiz_id = "")
	{
		$user_id = user()->id;
		$data['is_submitted'] = 1;
		$this->db->where('user_id', $user_id);
		$this->db->where('is_submitted', 0);
		$this->db->where('quiz_id', $quiz_id);
		$this->db->update('quiz_results', $data);

		//Mark this quiz as completed
		$lesson = $this->course_model->get_lessons('lesson', $quiz_id)->row_array();
		$completed_lessons = $this->course_model->get_watch_histories($user_id, $lesson['course_id'])->row_array();
		$course_details = $this->course_model->get_course_by_id_for_lms($lesson['course_id'])->row_array();
		$quiz_results = $this->db->where('user_id', $user_id)->where('quiz_id', $quiz_id)->order_by('quiz_result_id', 'DESC')->get('quiz_results')->row_array();
		$completed_lessons = json_decode($completed_lessons['completed_lesson'], true);
		if (!is_array($completed_lessons) || !in_array($quiz_id, $completed_lessons)) {

			//check passing mark
			$quiz_attribute = json_decode($lesson['attachment'], true);
			$pass_mark = $quiz_attribute['pass_mark'] ?? 0;
			$drip_content_for_passing_rule = $quiz_attribute['drip_content_for_passing_rule'] ?? 'not_applicable';

			if ($course_details['enable_drip_content'] && $drip_content_for_passing_rule == 'applicable') {
				if ($pass_mark <= $quiz_results['total_obtained_marks']) {
					$this->course_model->update_watch_history_manually($quiz_id, $lesson['course_id'], $user_id);
				}
			} else {
				$this->course_model->update_watch_history_manually($quiz_id, $lesson['course_id'], $user_id);
			}
		}

		$response['status'] = 'submit';
		$response['message'] = site_phrase('quiz_submission_successfully');
		echo json_encode($response);
	}

	function account_setting()
	{
		$data['title'] = 'Account Setting';
		$data['app_setting'] = $this->setting_model->get_all_app_setting();
		$this->load->view('admin/student_lms/include/header', $data);
		$this->load->view('admin/student_lms/account_setting');
		$this->load->view('admin/student_lms/include/footer');
	}

	function update_student_personal_info()
	{
		$this->load->model('student_model');
		if ($this->student_model->update_student_personal_info()) {
			$this->session->set_userdata('success', "Data Successfully Saved");
			redirect($this->agent->referrer());
		} else {
			$this->session->set_userdata('error', "data Saveding Faild");
			redirect($this->agent->referrer());
		}
	}

	function update_student_password_info()
	{
		$this->load->model('student_model');
		if ($this->student_model->update_student_password_info()) {
			$this->session->set_userdata('success', "Data Successfully Saved");
			redirect($this->agent->referrer());
		} else {
			$this->session->set_userdata('error', "data Saveding Faild");
			redirect($this->agent->referrer());
		}
	}

	function learner_report()
	{
		$this->load->model('student_model');
		$data['title'] = 'Learner Report';
		$data['app_setting'] = $this->setting_model->get_all_app_setting();
		$data['student_timing'] = $this->student_model->getUserActivitySummary(user()->id);
		$data['week_activity'] = $this->student_model->getUserWeeklyActivitySummary(user()->id);
		$data['week_timing_data'] = $this->student_model->getUserWeeklyDailyTiming(user()->id);
		$data['week_event'] = $this->student_model->getUserWeeklyDailyEvents(user()->id);
		$data['week_hrs_spent'] = $this->student_model->getUserWeeklyDailyGraph(user()->id);
		$data['medal_report'] = $this->student_model->generateUserMedalSection(user()->id);
		$this->load->view('admin/student_lms/include/header', $data);
		$this->load->view('admin/student_lms/learner_report');
		$this->load->view('admin/student_lms/include/footer');
	}

	function faq()
	{
		$this->load->model('student_model');
		$data['title'] = 'FAQ';
		$data['app_setting'] = $this->setting_model->get_all_app_setting();
		$this->load->view('admin/student_lms/include/header', $data);
		$this->load->view('admin/student_lms/faq');
		$this->load->view('admin/student_lms/include/footer');
	}

	function reminder_save()
	{
		$this->load->model('student_model');
		$json = file_get_contents('php://input');
		$data = json_decode($json, true);

		$user_id = user()->id;
		$this->db->where('user_id', $user_id);
		$main_data = $this->db->get('study_reminders')->result();

		if ($main_data) {
			$this->db->where('user_id', $user_id);
			$this->db->update('study_reminders', ['status' => 0]);
		}



		if (!empty($data['reminders'])) {
			foreach ($data['reminders'] as $reminder) {
				$this->student_model->save_reminder($reminder);
			}
			echo json_encode(['status' => 'success']);
		} else {
			echo json_encode(['status' => 'no_data']);
		}
	}

	function get_reminder()
	{
		$this->load->model('student_model');

		$reminders = $this->student_model->get_all_reminders();
		echo json_encode($reminders);
	}

	public function checkLoginActivity()
	{
		// Check if user is logged in
		if ($this->session->userdata('bcount_sess_logged_in')) {
			// Initialize the login counter if it doesn't exist
			if (!$this->session->userdata('login_count')) {
				$this->session->set_userdata('login_count', 5);
			}

			// Increase the login counter by 1 if the page is active
			$this->session->set_userdata('login_count', $this->session->userdata('login_count') + 5);

			$user_id = user()->id;
			//get the login counter	
			$this->db->where('activity_user_id', $user_id);
			$this->db->where('activity_date', date('Y-m-d'));
			$main_data = $this->db->get('student_learning_activity')->row();


			if (!$main_data) {

				$data = array(
					'activity_date' => date('Y-m-d'),
					'activity_user_id' => user()->id,
					'activity_timing' => $this->session->userdata('login_count')
				);

				$this->db->insert('student_learning_activity', $data);
			} else {
				// Update the login counter


				$data = array(
					'activity_timing' => $this->session->userdata('login_count')
				);

				$this->db->where('activity_user_id', $user_id);
				$this->db->where('activity_date', date('Y-m-d'));
				$this->db->update('student_learning_activity', $data);
			}
		} else {
			echo 'User is not logged in.';
		}
	}

	function course_playing_page_layout()
	{
		if ($this->session->userdata('full_page_layout') == false) {
			$this->session->set_userdata('full_page_layout', true);
		} else {
			$this->session->set_userdata('full_page_layout', false);
		}

		echo json_encode(['reload' => true]);
	}
}

/* End of file Admin.php */
/* Location: ./application/controllers/Admin/Admin.php */