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

class Brsalesmodel extends CI_Model {

	function __construct() {
		parent::__construct();
		date_default_timezone_set('Asia/Hong_Kong');
		$this->load->model('Brcustomermodel', 'customer_model');
		$this->load->model('BrBookingModel', 'booking_model');
		$this->load->model('BrServicesModel', 'services_model');
		$this->load->model('BrshopModel', 'shop_model');
		$this->load->model('Bremployeemodel', 'employee_model');
		$this->load->model('BrRoomModel', 'room_model');
		$this->load->model('Brinvoicemodel', 'invoice_model');
		$this->load->model('BrservicesModel', 'services_model');
	}

	//added salary model
	function getMonthlySales($employeeid, $year, $month) {
		$firstdate = $this->getFirstDateofThisMonth($year, $month);
		$firstdateObject = new DateTime($firstdate);
		$firstdatetimestamp = $firstdateObject->getTimestamp();
		$lastdate = $this->getLastDateofThisMonth($year, $month);
		$lastdateObject = new DateTime($lastdate);
		$lastdatetimestamp = $lastdateObject->getTimestamp();
		$this->db->select('brinvoice.*,brpurchase_payment.payment_date');
		$this->db->from('brinvoice');
		$this->db->group_start(); // Open bracket
		$this->db->where('therapist_id =', $employeeid);
		$this->db->or_where('therapist2_id =', $employeeid);
		$this->db->or_where('consultant_id =', $employeeid);
		$this->db->group_end();
		// $this->db->where('issued_date >=', $firstdatetimestamp);
		// $this->db->where('issued_date <=', $lastdatetimestamp);
		$this->db->where('brinvoice.invoice_status =', 'paid');
		$this->db->where('brpurchase_payment.payment_date >=', $firstdatetimestamp);
		$this->db->where('brpurchase_payment.payment_date <=', $lastdatetimestamp);
		$this->db->where('brinvoice.delete_time', NULL);
		$this->db->join('brpurchase_payment', 'brinvoice.id=brpurchase_payment.invoice_id');
		$this->db->order_by("issued_date", "asc");
		$this->db->group_by("brinvoice.id");
		$query = $this->db->get();
		// echo "<br>";
		// var_dump($this->db->last_query());
		// var_dump($query->result());
		// echo "<br>";
		// echo "<br>";
		// var_dump($this->modifiedresult($query->result()));
		// echo "<br>";
		return $this->modifiedresult($query->result());

	}
	function modifiedresult($result) {
		$customer_array = $this->customer_model->getCustomerAllShop();
		$shop_array = $this->shop_model->getAllShop();
		$employee_array = $this->employee_model->getAllEmpolyeeName();
		$room_array = $this->room_model->getAllRoomName();
		$services_array = $this->services_model->getAllServices();

		$modifiedarray = array();

		foreach ($result as $resultRow) {
			$modifiedrow = array();
			$modifiedrow['id'] = $resultRow->id;
			$modifiedrow['user_id'] = $resultRow->user_id;
			//get customer name
			$modifiedrow['display_name'] = "";
			$modifiedrow['mobile'] = "";
			foreach ($customer_array as $customerRow) {
				if ($customerRow->id == $resultRow->user_id) {
					$modifiedrow['display_name'] = $customerRow->display_name;
					$modifiedrow['mobile'] = $customerRow->mobile;
				}
			}
			//end get customer name
			$modifiedrow['therapist_id'] = $resultRow->therapist_id;
			//get therapist_name
			$modifiedrow['therapist_name'] = "";
			foreach ($employee_array as $employeeRow) {
				if ($resultRow->therapist_id == $employeeRow->id) {
					$modifiedrow['therapist_name'] = $employeeRow->chi_name;
				}
			}
			//end get therapist_name
			$modifiedrow['therapist2_id'] = $resultRow->therapist2_id;
			//get therapist2_name
			$modifiedrow['therapist2_name'] = "";
			foreach ($employee_array as $employeeRow) {
				if ($resultRow->therapist2_id == $employeeRow->id) {
					$modifiedrow['therapist2_name'] = $employeeRow->chi_name;
				}
			}
			//end get therapist2_name
			//get consultant_name
			$modifiedrow['consultant_name'] = "";
			foreach ($employee_array as $employeeRow) {
				if ($resultRow->consultant_id == $employeeRow->id) {
					$modifiedrow['consultant_name'] = $employeeRow->chi_name;
				}
			}
			//end get therapist2_name
			$modifiedrow['payment_date'] = $resultRow->payment_date;
			$modifiedrow['payment_date_convert'] = date('Y-m-d', $resultRow->payment_date);

			$modifiedrow['issued_name'] = $resultRow->issued_name;
			$modifiedrow['issued_date'] = $resultRow->issued_date;
			$modifiedrow['issued_date_convert'] = date('Y-m-d', $resultRow->issued_date);
			$modifiedrow['total_amount_due'] = $resultRow->total_amount_due;
			$modifiedrow['parent_id'] = $resultRow->parent_id;
			$modifiedrow['partialpayment'] = $resultRow->partialpayment;
			$modifiedrow['invoice_status'] = $resultRow->invoice_status;
			$modifiedrow['status'] = $resultRow->status;

			$searchinvoiceid = "";
			if ($resultRow->parent_id == 0) {
				$searchinvoiceid = $resultRow->id;
			}
			if ($resultRow->parent_id != 0) {
				$searchinvoiceid = $resultRow->parent_id;
			}
			$modifiedrow['calTrailInvoiceamount'] = $this->invoice_model->getTotalTrailProductAmount($searchinvoiceid);
			$modifiedrow['totalPaymentList'] = $this->getTotalPaymentList($searchinvoiceid, $resultRow->payment_date);
			$modifiedrow['totalPaymentListTotal'] = $this->getTotalPaymentListTotal($searchinvoiceid, $resultRow->payment_date);
			$modifiedrow['paymentListTotal'] = $this->getPaymentListTotal($resultRow->id);

			// $modifiedrow['invoicePayment']
			// $modifiedrow['shopId'] = $resultRow->shopId;
			// //get room name
			// $modifiedrow['room_name'] = "";
			// foreach ($room_array as $roomRow) {
			// 	if ($resultRow->room_id == $roomRow->id) {
			// 		$modifiedrow['room_name'] = $roomRow->name;
			// 	}

			// }
			// //end get room name
			// $modifiedrow['user_id'] = $resultRow->user_id;
			// $modifiedrow['pic_1'] = $resultRow->pic_1;
			// //get pic1 name
			// $modifiedrow['pic_1_name'] = "";
			// foreach ($employee_array as $employeeRow) {
			// 	if ($resultRow->pic_1 == $employeeRow->id) {
			// 		$modifiedrow['pic_1_name'] = $employeeRow->chi_name;
			// 	}
			// }
			// //end get pic name
			// $modifiedrow['pic_2'] = $resultRow->pic_2;
			// //get pic1 name
			// $modifiedrow['pic_2_name'] = "";
			// foreach ($employee_array as $employeeRow) {
			// 	if ($resultRow->pic_2 == $employeeRow->id) {
			// 		$modifiedrow['pic_2_name'] = $employeeRow->chi_name;
			// 	}
			// }
			// //end get pic name

			//getInvoiceitemdetails
			// var_dump($resultRow->id);
			$invoiceitem = $this->invoice_model->getInvoiceItemDetail($resultRow->id);

			$invoiceitemArray = array();
			$totalsales = 0;
			foreach ($invoiceitem as $invoiceitemRow) {
				$invoiceitemDetails = array();
				$invoiceitemDetails['id'] = $invoiceitemRow->id;
				$invoiceitemDetails['item_id'] = $invoiceitemRow->item_id;

				$invoiceitemDetails['item_name'] = $invoiceitemRow->item_name;
				$invoiceitemDetails['price'] = $invoiceitemRow->price;
				$invoiceitemDetails['qty'] = $invoiceitemRow->qty;
				$invoiceitemDetails['discount'] = $invoiceitemRow->discount;
				$invoiceitemDetails['amount'] = $invoiceitemRow->amount;
				$invoiceitemDetails['istried'] = false;
				$invoiceitemDetails['category_id'] = 0;
				$invoiceitemDetails['code'] = '';
				foreach ($services_array as $servicesRow) {
					if ($invoiceitemRow->item_id == $servicesRow->id) {
						if ($servicesRow->category_id == 1) {
							$invoiceitemDetails['istried'] = true;
						}
						if ($servicesRow->category_id == 2) {
							$invoiceitemDetails['istried'] = false;
						}
						$invoiceitemDetails['category_id'] = $servicesRow->category_id;
						$invoiceitemDetails['code'] = $servicesRow->code;
					}
				}
				array_push($invoiceitemArray, $invoiceitemDetails);
			} //foreach ($invoiceitemRowiceitem as $invoiceitemRow) {
			// var_dump($invoiceitemArray);
			$modifiedrow['invoiceitemArray'] = $invoiceitemArray;
			//end getInvoiceitemdetails
			// //get booking item
			// // $bookingitem = $this->booking_model->getBookingItem($resultRow->id);
			// $bookingitemArray = array();
			// $totalwork = 0;
			// //booking item
			// $bookingitem = $this->booking_model->getBookingItem($resultRow->id);
			// foreach ($bookingitem as $bookingRow) {
			// 	$bookingitemDetails = array();
			// 	$bookingitemDetails['id'] = $bookingRow->id;
			// 	$bookingitemDetails['code'] = $bookingRow->code;
			// 	$bookingitemDetails['name'] = $bookingRow->name;
			// 	$bookingitemDetails['category_id'] = $bookingRow->category_id;
			// 	$bookingitemDetails['work'] = $bookingRow->work;
			// 	$bookingitemDetails['price'] = $bookingRow->price;
			// 	$bookingitemDetails['serviceCount'] = $this->services_model->serviceConvert($bookingRow->work);
			// 	array_push($bookingitemArray, $bookingitemDetails);
			// 	$totalwork = $totalwork + $bookingitemDetails['serviceCount'];
			// }
			// //end
			// //booking service use
			// $bookingUseServiceItem = $this->booking_model->getUseServiceItemByBooking($resultRow->id);
			// foreach ($bookingUseServiceItem as $bookingUseServiceRow) {
			// 	$bookingitemDetails = array();
			// 	$bookingitemDetails['id'] = $bookingUseServiceRow->itemid;
			// 	$bookingitemDetails['code'] = $bookingUseServiceRow->code;
			// 	$bookingitemDetails['name'] = $bookingUseServiceRow->name;
			// 	$bookingitemDetails['category_id'] = $bookingUseServiceRow->category_id;
			// 	$bookingitemDetails['work'] = $bookingUseServiceRow->work;
			// 	$bookingitemDetails['price'] = $bookingUseServiceRow->unit_price;
			// 	$bookingitemDetails['serviceCount'] = $this->services_model->serviceConvert($bookingUseServiceRow->work);
			// 	array_push($bookingitemArray, $bookingitemDetails);
			// 	$totalwork = $totalwork + $bookingitemDetails['serviceCount'];
			// }

			// //end booking service use

			// $modifiedrow['bookingitem'] = $bookingitemArray;
			// $modifiedrow['totalwork'] = $totalwork;
			// $modifiedrow['numOfPic'] = $this->calculateNumOfPic($resultRow);
			// $modifiedrow['caltotalwork'] = $this->caltotalwork($totalwork, $modifiedrow['numOfPic']);
			// //end get booking item

			//getshopname
			$modifiedrow['shopId'] = $resultRow->shopId;
			$modifiedrow['shopname'] = "";
			foreach ($shop_array as $shoprow) {
				if ($shoprow->id == $resultRow->shopId) {
					$modifiedrow['shopname'] = $shoprow->name;
				}
			}
			//end getshopname

			array_push($modifiedarray, $modifiedrow);
		} //foreach ($result as $resultRow) {
		return $modifiedarray;
	}
	function sumAllSalesPerMonth($result) {
		$totalSales = 0;
		foreach ($result as $resultRow) {
			$totalWork = $totalWork + $resultRow['caltotalwork'];
		} //foreach($result as $resultRow){
		return $totalSales;
	}
	function getTotalPaymentList($searchinvoiceid, $payment_date) {
		$this->db->select('brinvoice.*,brpurchase_payment.payment_date');
		$this->db->from('brinvoice');
		$this->db->group_start(); // Open bracket
		$this->db->where('brinvoice.id =', $searchinvoiceid);
		$this->db->or_where('brinvoice.parent_id =', $searchinvoiceid);
		$this->db->group_end();
		// $this->db->where('issued_date >=', $firstdatetimestamp);
		// $this->db->where('issued_date <=', $lastdatetimestamp);
		$this->db->where('brpurchase_payment.payment_date >=', $payment_date);
		$this->db->where('brpurchase_payment.payment_date <=', $payment_date);
		$this->db->where('brinvoice.delete_time', NULL);
		$this->db->join('brpurchase_payment', 'brinvoice.id=brpurchase_payment.invoice_id');
		$this->db->order_by("issued_date", "asc");
		$this->db->group_by("brinvoice.id");
		$query = $this->db->get();
		return $query->result();
	}
	function getPaymentList($invoiceid) {
		$paymentList = array();
		$this->db->select('*');
		$this->db->from('brpurchase_payment');
		$this->db->where('invoice_id =', $searchinvoiceid);

		// $this->db->where('issued_date >=', $firstdatetimestamp);
		// $this->db->where('issued_date <=', $lastdatetimestamp);
		$query = $this->db->get();
		$result = $query->result();
		foreach ($result as $resultRow) {
			$paymentListDetails = array();
			$paymentListDetails['id'] = $resultRow->id;
			$paymentListDetails['id'] = $resultRow->id;
			array_push($paymentList);
		}
		// echo "<br>";
		// var_dump($this->db->last_query());
		// var_dump($query->result());
		// echo "<br>";
		// echo "<br>";
		// var_dump($this->modifiedresult($query->result()));
		// echo "<br>";
		// return $this->modifiedresult($query->result());

		return $paymentList;
	}
	function getTotalPaymentListTotal($searchinvoiceid, $payment_date) {
		$this->db->select('brinvoice.*,brpurchase_payment.payment_date');
		$this->db->from('brinvoice');
		$this->db->group_start(); // Open bracket
		$this->db->where('brinvoice.id =', $searchinvoiceid);
		$this->db->or_where('brinvoice.parent_id =', $searchinvoiceid);
		$this->db->group_end();
		// $this->db->where('issued_date >=', $firstdatetimestamp);
		// $this->db->where('issued_date <=', $lastdatetimestamp);
		// $this->db->where('brpurchase_payment.payment_date >=', $payment_date);
		$this->db->where('brpurchase_payment.payment_date <=', $payment_date);
		$this->db->where('brinvoice.delete_time', NULL);
		$this->db->join('brpurchase_payment', 'brinvoice.id=brpurchase_payment.invoice_id');
		$this->db->order_by("issued_date", "asc");
		$this->db->group_by("brinvoice.id");
		$query = $this->db->get();
		$result = $query->result();
		$sumTotal = 0;
		foreach ($result as $resultRow) {
			$sumTotal = $sumTotal + $this->getPaymentListTotal($resultRow->id);
		}
		return $sumTotal;
	}
	function getPaymentListTotal($invoiceid) {
		$paymentList = array();
		$this->db->select('*');
		$this->db->from('brpurchase_payment');
		$this->db->where('invoice_id =', $invoiceid);

		// $this->db->where('issued_date >=', $firstdatetimestamp);
		// $this->db->where('issued_date <=', $lastdatetimestamp);
		$query = $this->db->get();
		$result = $query->result();
		$total = 0;
		foreach ($result as $resultRow) {
			$total = $total + $resultRow->payment_amount;
		}
		// echo "<br>";
		// var_dump($this->db->last_query());
		// var_dump($query->result());
		// echo "<br>";
		// echo "<br>";
		// var_dump($this->modifiedresult($query->result()));
		// echo "<br>";
		// return $this->modifiedresult($query->result());

		return $total;
	}
	function sumAllWorkPerMonth($result) {
		$totalWork = 0;
		foreach ($result as $resultRow) {
			$totalWork = $totalWork + $resultRow['caltotalwork'];
		} //foreach($result as $resultRow){
		return $totalWork;
	}
	function caltotalwork($totalwork, $numofPic) {
		$returnTotalWork = 0;
		if ($numofPic == 0) {
			$returnTotalWork = $totalwork;
		}
		if ($numofPic == 1) {
			$returnTotalWork = $totalwork;
		}
		if ($numofPic == 2) {
			$returnTotalWork = $totalwork / 2;
		}
		return $returnTotalWork;
	}
	function calculateNumOfPic($resultRow) {
		$numOfPic = 0;
		if (!empty($resultRow->pic_1)) {
			$numOfPic = $numOfPic + 1;
		}
		if (!empty($resultRow->pic_2)) {
			$numOfPic = $numOfPic + 1;
		}
		return $numOfPic;
	}
	function getFirstDateofThisMonth($year, $month) {
		$d = $year . '-' . $month . '-01';

		$calmonth = new DateTime($d);
		$calmonth->modify('first day of this month');
		return $calmonth->format('Y-m-d');
	}
	function getLastDateofThisMonth($year, $month) {
		$d = $year . '-' . $month . '-01';
		$calmonth = new DateTime($d);
		$calmonth->modify('last day of this month');
		return $calmonth->format('Y-m-d');

	}

	function getEmployeeMonth($employeeid) {
		$startDate = $this->getEmployeeEntry($employeeid);
		//hard code a start month of empoyee
		if (empty($startDate)) {
			$startDate = "2020-08-01";
		}
		//end hard code a start month of empoyee
		$endDate = $this->getEmployeeQuit($employeeid);
		if ($endDate == null) {
			$endDate = $date = date('Y-m-d');
		}
		$months = array();
		while (strtotime($startDate) <= strtotime($endDate)) {
			$months[] = array('year' => date('Y', strtotime($startDate)), 'month' => date('m', strtotime($startDate)));
			$startDate = date('01 M Y', strtotime($startDate .
				'+ 1 month')); // Set date to 1 so that new month is returned as the month changes.
		}

		return $months;

	}

	function getEmployeeEntry($employeeid) {
		$this->db->from('bemployee');
		// $this->db->where('shop_id', 1);
		$this->db->where('id', $employeeid);

		$dateofentry = $this->db->get()->row()->dateofentry;
		return $dateofentry;
	}

	function getEmployeeQuit($employeeid) {
		$this->db->from('bemployee');
		// $this->db->where('shop_id', 1);
		$this->db->where('id', $employeeid);

		$dateofentry = $this->db->get()->row()->dateofquit;
		return $dateofentry;
	}

	//end added salary model

	function getAllRoom($id) {
		$this->db->from('brroom');
		$this->db->where('shop_id', $id);
		$this->db->where('delete_time', NULL);
		$query = $this->db->get();
		return $query->result();
	}
	function room_exists($shop_id, $name) {
		// $this->db->from('adminUsers');
		$this->db->where('LOWER(name)', $name);
		$this->db->where('shop_id', $shop_id);
		$this->db->where('delete_time', NULL);
		$query = $this->db->get('brroom');
		if ($query->num_rows() == 1) {
			return false;
		} else {
			return true;
		}
	}
	function insertAdmin($data) {
		// 'inputadminname'=>$inputadminname,
		//         'inputloginname'=>$inputloginname,
		//         'inputPassword'=>$inputPassword,
		$data = array(
			'shop_id' => $data['shop_id'],
			'name' => $data['name'],
			'capacity' => $data['capacity'],
			'description' => $data['description'],
			// 'fullName' => $data['inputadminname'] ,
			'remark' => $data['remark'],

		);
		date_default_timezone_set('UTC');

		$this->db->set('update_time', time(), FALSE);
		$this->db->set('create_time', time(), FALSE);
		// $this->db->set('update_time', 'NOW()', FALSE);
		// $this->db->set('create_time', 'NOW()', FALSE);
		$query = $this->db->insert('brroom', $data);
		return $query;
	}
	function getRoom($id) {
		$this->db->from('brroom');
		$this->db->where('delete_time', NULL);
		$this->db->where('id', $id);
		// $this->db->order_by('code');
		$query = $this->db->get();
		$ret = $query->row();
		return $ret;
	}

	function room_existsbyid($id, $shop_id, $name) {
		// $this->db->from('adminUsers');
		$this->db->where('LOWER(name)', $name);
		$this->db->where('shop_id', $shop_id);
		$this->db->where('id !=', $id);
		$this->db->where('delete_time', NULL);
		$query = $this->db->get('brroom');
		if ($query->num_rows() == 1) {
			return false;
		} else {
			return true;
		}
	}

	function updateAdmin($dataori) {
		// 'inputadminname'=>$inputadminname,
		//         'inputloginname'=>$inputloginname,
		//         'inputPassword'=>$inputPassword,
		$data = array(
			'shop_id' => $dataori['shop_id'],
			'name' => $dataori['name'],
			'capacity' => $dataori['capacity'],
			'description' => $dataori['description'],
			// 'fullName' => $dataori['inputadminname'] ,
			'remark' => $dataori['remark'],

		);
		date_default_timezone_set('UTC');

		$this->db->set('update_time', time(), FALSE);
		// $this->db->set('create_time', time(), FALSE);
		// $this->db->set('update_time', 'NOW()', FALSE);
		// $this->db->set('create_time', 'NOW()', FALSE);
		$this->db->where('id', $dataori['id']);
		$query = $this->db->update('brroom', $data);
		return $query;
	}
	function updateStatus($data) {
		$data2 = array(
			'status' => $data['status'],
		);
		date_default_timezone_set('UTC');

		$this->db->set('update_time', time(), FALSE);

		$this->db->where('id', $data['id']);
		$query = $this->db->update('brroom', $data2);
		return $query;
	}
	function deleteRoom($id) {
		date_default_timezone_set('UTC');

		$this->db->set('delete_time', time(), FALSE);
		$this->db->where('id', $id);
		$query = $this->db->update('brroom');
		return $query;
	}
	function getRoomName($id) {
		$this->db->from('brroom');
		// $this->db->where('shop_id', 1);
		$this->db->where('id', $id);

		$name = $this->db->get()->row()->name;
		return $name;
	}
	function getAllRoomName() {
		$this->db->select("name,id");
		$this->db->from('brroom');
		// $this->db->where('shop_id', 1);
		$query = $this->db->get();
		return $query->result();
	}

	function getBannerAll() {

		$this->db->from('frontendUsers');
		// $this->db->where(array('show' => 1));
		// $this->db->order_by('rank');
		$query = $this->db->get();
		return $query->result();
	}

	function checking() {

		$userid = $this->session->userdata('userid');
		$username = $this->session->userdata('username');
		$fullName = $this->session->userdata('fullName');
		$logged_in = $this->session->userdata('logged_in');
		$secret = $this->session->userdata('secret');
		$usertype = $this->session->userdata('usertype');

		$passLogin = false;
		if ($usertype == "frontenduser") {
			if ($logged_in == false) {
				return false;
			}
			if (empty($userid)) {
				return false;
			}
			if (empty($secret)) {
				return false;
			}
			$this->db->where('id', $userid);
			$this->db->where('secret', $secret);
			if ($this->db->get('frontendUsers')->row_array()) {
				$passLogin = true;
				return true;
			} else {
				return false;
			}

		} //if($usertype=="frontenduser"){
		if ($usertype == "backenduser") {
			if ($logged_in == false) {
				return false;
			}
			if (empty($userid)) {
				return false;
			}
			if (empty($secret)) {
				return false;
			}
			$this->db->where('id', $userid);
			$this->db->where('secret', $secret);
			if ($this->db->get('adminUsers')->row_array()) {
				$passLogin = true;
				return true;
			} else {
				return false;
			}

		}
	}

}