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

class Application extends CI_Controller
{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('front/long_menu');
	}

	public function menu2()
	{
		$request = $this->input->post();
		$old_student = false;
		$new_student = true;
		if (isset($request['old_student'])) {
			$old_student = false;
		}
		if (isset($request['new_student'])) {
			$new_student = true;
		}
		$this->load->model("Event_model");
		$this->load->model("Event_timeslot_model");
		$event_data = $this->Event_model->get_menu();



		//$timeslot_data = $this->Event_timeslot_model->listing();


		foreach ($event_data as $idx => $event) {
			$event_data[$idx]['weekday_json'] = json_decode(($event['weekday_json']));
		}
		//var_dump($event_data);
		//exit;

		$this->load->view('front/long_menu_2', [
			'data' => $event_data,
			"old_student" => $old_student,
			"new_student" => $new_student
		]);
	}

	public function menu3()
	{
		$request = $this->input->post();
		$new_student = $request['new_student'];
		$old_student = $request['old_student'];
		$recommand = false;
		$recommand_person = "";
		if (isset($request['recommand'])) {
			$recommand = true;
			$recommand_person = $request['recommand'];
		}

		$double = false;
		$double_name = "";
		$double_age = "";
		$double_gender = "";
		if (isset($request['double'])) {
			$double = true;
			$double_name = $request['double'];
			$double_age = $request['double_age'];
			$double_gender = $request["double_gender"];
		}




		$this->load->model("Event_model");
		$this->load->model("Event_timeslot_model");
		$event_data = $this->Event_model->simple_get();
		foreach ($event_data as $idx => $event) {
			$event_data[$idx]['weekday_json'] = json_decode($event['weekday_json']);
		}
		$class_keys = array_keys($request['class']);
		$first = "";
		$second = "";
		for ($i = 0; $i < sizeof($class_keys); $i++) {
			if ($request['class'][$class_keys[$i]] == "1") {
				$first = $class_keys[$i];
			}
			if ($request['class'][$class_keys[$i]] == "2") {
				$second = $class_keys[$i];
			}
		}
		//echo $first;
		//echo $second;




		$this->load->view('front/long_menu_3', [

			"data" => $event_data,
			"request" => $request,
			"first" => $first,
			"second" => $second,
			"recommand" => $recommand,
			"recommand_person" => $recommand_person,
			"double" => $double,
			"double_name" => $double_name,
			"double_age" => $double_age,
			"double_gender" => $double_gender,
			'price' => $request['price'],
			'double_discount_amount' => $request['double_discount_amount'],
			"recommand_discount_amount" => $request['recommand_discount_amount'],
			"old_student" => $old_student,
			"new_student" => $new_student



		]);
	}

	function paypal_testing()
	{
		$request = $this->input->post();
	
		$this->session->set_userdata("_user", $request);
		$this->load->model("Order_payment_paypal_model");
		$payment_descript = "payment";
		$params = [
			"payment_total" => $request['price'],
			"payment_curreny" => "HKD",
			"product_json" =>  [
				['sku' => '123', 'name' => '賬單支付', 'quantity' => 1, 'currency' => 'HKD', 'price' => $request['net_amount']],
				//	['sku' => '456', 'name' => '賬單支付', 'quantity' => 1, 'currency' => 'HKD', 'price' => doubleval(920)],
				['sku' => null, 'name' => 'Discount', 'quantity' => 1, 'currency' => 'HKD', 'price' => (-1 * ($request['discount_amount'])) ],
			]

		];
		$member = [];
		$paypal = $this->Order_payment_paypal_model->paypal_create_payment($payment_descript,$params,$member,base_url("/front/application/success"),base_url("/front/application/cancel"));
		header(sprintf('Location: %s', $paypal['approval_link']));
	}


	function submission()
	{
		
		if($this->session->userdata("_user") != null){
		$request = $this->session->userdata('_user');
		}else{
			$request = $this->input->post();
		}

		$this->load->model("Event_timeslot_model");
		$this->load->model("Event_enrollment_model");
		$this->load->model("Event_enrollment_item_model");
		$this->load->model('Student_model');
		$this->load->model("Parent_model");

		$first_choice = $request['first-choice'];
		$second_choice = isset($request['second-choice']) ? $request['second-choice'] : "";
		$recommand = isset($request['recommand_person']) ? $request["recommand_person"] : "";
		$discount = "";
		if ($recommand != "") {
			$discount = "舊生推薦";
		}
		$double = isset($request['double_name']) ? $request['double_name'] : "";
		$double_gender = isset($request['double_gender']) ? $request['double_gender'] : "";
		$double_age = isset($request['double_age']) ? $request['double_age'] : "";
		if ($double != "" && $double_gender != "" && $double_age != "") {
			$discount = "兩人同行";
		}

		$discount_amount = $request['discount_amount'];
		$net_amount = $request['net_amount'];
		$price = $request['price'];
		$double_id = "";

		if ($request['new_student'] == 1) {
			$student_information = [
				'chi_name' => $request['student'],
				'eng_name' => "",
				'student_no' => "",
				'gender' => $request['gender'],
				'age' => $request['age'],
				'content1_name' => $request['parent'],
				'content1_phone' => $request['contact_number'],
				"content1_email" => $request['email'],
				"recommand" => $recommand
			];
			if (isset($request['paypal'])) {
				$student_information['payment_method'] = "paypal";
			}
			if (isset($request['payme'])) {
				$student_information['payment_method'] = "payme";
			}
			if (isset($request['bank'])) {
				$student_information['payment_method'] = "bank";
			}

			$parent_information = [
				"chi_name" => $request['parent'],
				'username' => $request['email'],
				"email" => $request['email'],
				"password" => sha1($request['contact_number']),
				'mobile' => $request["contact_number"],
			];

			if ($double != "" && $double_gender != "" && $double_age != "") {
				$double_information = [
					"chi_name" => $double,
					"eng_name" => "",
					'gender' => $double_gender,
					'age' => $double_age,
					"student_no" => "",
					"content1_name" => "",
					"content1_phone" => "",
					'content1_email' => ""

				];
				$double_id = $this->Student_model->create($double_information);
			}

			$student_id = $this->Student_model->create($student_information);
			$parent_id = $this->Parent_model->create($parent_information);
			$this->Parent_model->link($student_id, $parent_id['id']);

			$enrollment_information = [
				'event_id' => $first_choice,
				'student_id' => $student_id,
				"enroll_date" => time(),
			];
			$enrollment_id = $this->Event_enrollment_model->create($enrollment_information);

			try {
				$this->load->model('Event_enrollment_invoicing_model');
				$enrollment_information['net_amount'] =  $net_amount;
				$enrollment_information['discount_amount'] = $discount_amount;
				$enrollment_information['price'] = $price;
				$enrollment_information['discount'] = $discount_amount;
				$this->Event_enrollment_invoicing_model->run($enrollment_information, $first_choice);

				if (array_key_exists('submit_redirect', $enrollment_information)) {
					$this->load->model('Student_model');
					$student = $this->Student_model->detail($enrollment_information['student_id']);
					redirect('/invoicing?studentno=' . $student['student_no'] . '&selectedno=' . $student['student_no']);
				} else {
					$this->_data['__alert_success_message'] = '儲存成功。';
				}
			} catch (Exception $e) {
				$this->_data['__alert_error_message'] = $e->getMessage();
			}

			$event_timeslot_information = $this->Event_timeslot_model->listing_by_event_id($first_choice);
			/*foreach ($event_timeslot_information as $timeslot) {
				$timeslot_data = [
					'event_id' => $first_choice,
					'event_timeslot_id' => $timeslot['id'],
					'event_enrollment_id' => $enrollment_id['id'],
					'student_id' => $student_id
				];
				$this->Event_enrollment_item_model->create($timeslot_data);
			}*/

			if ($double_id != "") {
				$enrollment_information = [
					'event_id' => $first_choice,
					'student_id' => $double_id,
					"enroll_date" => time(),
				];
				$enrollment_id = $this->Event_enrollment_model->create($enrollment_information);
				/*
				$event_timeslot_information = $this->Event_timeslot_model->listing_by_event_id($first_choice);
				foreach ($event_timeslot_information as $timeslot) {
					$timeslot_data = [
						'event_id' => $first_choice,
						'event_timeslot_id' => $timeslot['id'],
						'event_enrollment_id' => $enrollment_id['id'],
						'student_id' => $double_id
					];
					$this->event_enrollment_item_model->create($timeslot_data);
				}*/

				try {
					$this->load->model('Event_enrollment_invoicing_model');
					$enrollment_information['net_amount'] =  $net_amount;
					$enrollment_information['discount_amount'] = $discount_amount;
					$enrollment_information['price'] = $price;
					$enrollment_information['discount'] = $discount_amount;
					$this->Event_enrollment_invoicing_model->run($enrollment_information, $first_choice);

					if (array_key_exists('submit_redirect', $enrollment_information)) {
						$this->load->model('Student_model');
						$student = $this->Student_model->detail($enrollment_information['student_id']);
						redirect('/invoicing?studentno=' . $student['student_no'] . '&selectedno=' . $student['student_no']);
					} else {
						$this->_data['__alert_success_message'] = '儲存成功。';
					}
				} catch (Exception $e) {
					$this->_data['__alert_error_message'] = $e->getMessage();
				}
			}
		} else {
			$student_id = $this->Student_model->simple_check($request['student'], $request['parent']);
			if ($student_id == null) {
				return $this->load->view('front/error');
			}
			$enrollment_information = [
				'event_id' => $first_choice,
				'student_id' => $student_id,
				"enroll_date" => time(),
			];
			$enrollment_id = $this->event_enrollment_model->create($enrollment_information);
			$event_timeslot_information = $this->Event_timeslot_model->listing_by_event_id($first_choice);
			/*foreach ($event_timeslot_information as $timeslot) {
				$timeslot_data = [
					'event_id' => $first_choice,
					'event_timeslot_id' => $timeslot['id'],
					'event_enrollment_id' => $enrollment_id['id'],
					'student_id' => $student_id
				];
				$this->event_enrollment_item_model->create($timeslot_data);
			}*/
			try {
				$this->load->model('Event_enrollment_invoicing_model');
				$enrollment_information['net_amount'] =  $net_amount;
				$enrollment_information['discount_amount'] = $discount_amount;
				$enrollment_information['price'] = $price;
				$enrollment_information['discount'] = $discount_amount;
				$this->Event_enrollment_invoicing_model->run($enrollment_information, $first_choice);

				if (array_key_exists('submit_redirect', $enrollment_information)) {
					$this->load->model('Student_model');
					$student = $this->Student_model->detail($enrollment_information['student_id']);
					redirect('/invoicing?studentno=' . $student['student_no'] . '&selectedno=' . $student['student_no']);
				} else {
					$this->_data['__alert_success_message'] = '儲存成功。';
				}
			} catch (Exception $e) {
				$this->_data['__alert_error_message'] = $e->getMessage();
			}

			if ($double != "" && $double_gender != "" && $double_age != "") {
				$double_information = [
					"chi_name" => $double,
					"eng_name" => "",
					'student_no' => "",
					'content1_name' => "",
					'content1_phone' => "",
					'content1_email' => "",
					'gender' => $double_gender,
					'age' => $double_age
				];
				$double_id = $this->Student_model->create($double_information);
			}

			if ($double_id != "") {
				$enrollment_information = [
					'event_id' => $first_choice,
					'studnet_id' => $double_id,
					"enroll_date" => time(),
				];
				/*
				$enrollment_id = $this->event_enrollment_model->create($enrollment_information);
				$event_timeslot_information = $this->Event_timeslot_model->listing_by_event_id($first_choice);
				foreach ($event_timeslot_information as $timeslot) {
					$timeslot_data = [
						'event_id' => $first_choice,
						'event_timeslot_id' => $timeslot['id'],
						'event_enrollment_id' => $enrollment_id['id'],
						'student_id' => $double_id
					];
					$this->event_enrollment_item_model->create($timeslot_data);
				}*/
				try {
					$this->load->model('Event_enrollment_invoicing_model');
					$enrollment_information['net_amount'] =  $net_amount;
					$enrollment_information['discount_amount'] = $discount_amount;
					$enrollment_information['price'] = $price;
					$enrollment_information['discount'] = $discount_amount;
					$this->Event_enrollment_invoicing_model->run($enrollment_information, $first_choice);

					if (array_key_exists('submit_redirect', $enrollment_information)) {
						$this->load->model('Student_model');
						$student = $this->Student_model->detail($enrollment_information['student_id']);
						redirect('/invoicing?studentno=' . $student['student_no'] . '&selectedno=' . $student['student_no']);
					} else {
						$this->_data['__alert_success_message'] = '儲存成功。';
					}
				} catch (Exception $e) {
					$this->_data['__alert_error_message'] = $e->getMessage();
				}
			}
		}




		$this->load->view('front/notice');
		// if new_student == 1  -> create student -> enroll class
		// if old_student == 1 -> enroll class
	}


	public function success()
	{
		redirect("front/application/submission");
	}

	public function cancel()
	{
		$this->load->view("front/error");
	}
}
