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

class Facilities extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$currency = '';

		$this->$currency =  GeneralSettings();
	}

	public function index()
	{
		// if ($this->session->userdata('logged_in') != 1) {
		// 	redirect(base_url());
		// }
		$currency = '';

		// if ($this->session->userdata('logged_in') == 1) {
		// 	$response = getUserDetails();
		// 	if (!empty($response)) {
		// 		// var_dump($response);
		// 		$data['userDetails'] = $response->data[0];
		// 	} else {
		// 		redirect(base_url());
		// 	}
		// }
		$data['userDetails'] = [];
		if (!empty($this->session->userdata('facilities_cart'))) {
			$this->session->unset_userdata('facilities_cart');
			$this->session->unset_userdata('event_details');

		}

		$data['GetState'] = GetState();
		$data['preferredLanguage'] = getPreferredLanguage();



		$data['currency'] = $this->$currency;
		$data['page'] = 'Facilities';
		$data['title'] = 'Facilities';
		$this->load->view('facilities/facilities', $data);
	}



	public function getcityByState()
	{
		$stateName = $this->input->post('stateCode');
		return GetCity($stateName);
	}



	public function addCart()
	{

		if ($this->input->post()) {

			$membershipDetails = membershipStatusCheck();

			$setting =  SettingsApi();
			
			$facilityMembershipDiscount = @$setting['result']['data'][0]['membershipSettings']['facilityMembershipDiscount'];
			$facilityDiscountType = @$setting['result']['data'][0]['membershipSettings']['facilityDiscountType'];

			$cart_items = $this->input->post();
			// var_dump($cart_items);
			if (isset($cart_items['ids'])) {
				foreach ($cart_items['ids'] as $key => $value) {
					$couponCode = '';
					if ($cart_items['serviceAmount'][$key] > 0) {
						if ($membershipDetails['membershipStatus'] == "ACTIVE" &&  @$cart_items['is_membership_discount'][$key] == 'YES') {

							if ($facilityDiscountType == 'SERVICE LEVEL') {
								// if (@$cart_items['is_membershipDiscountedAmt'][$key]) {
								// 	$rentalSericeAmt = @$cart_items['is_membershipDiscountedAmt'][$key];//service amout
								// 	$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
								// 	$RentaldiscountedAmount = $cart_items['serviceAmount'][$key] - @$cart_items['is_membershipDiscountedAmt'][$key];
								// 	$couponCode = $membershipDetails['membershipType'];
								// } else {
								// 	$rentalSericeAmt = $cart_items['serviceAmount'][$key];
								// 	$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
								// 	$RentaldiscountedAmount = 0;
								// }

								if ($cart_items['serviceAmount'][$key] > $facilityMembershipDiscount) {
									$rentalSericeAmt = $cart_items['serviceAmount'][$key] - $facilityMembershipDiscount;
									$oldRentalServiceAmount = $facilityMembershipDiscount;
									$RentaldiscountedAmount = $facilityMembershipDiscount;
									$couponCode = $membershipDetails['membershipType'];
								} else {
									$rentalSericeAmt = $cart_items['serviceAmount'][$key];
									$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
									$RentaldiscountedAmount = 0;
								}
							}else if ($facilityDiscountType == 'FLAT') {

								if ($cart_items['serviceAmount'][$key] > $facilityMembershipDiscount) {
									$rentalSericeAmt = $cart_items['serviceAmount'][$key] - $facilityMembershipDiscount;
									$oldRentalServiceAmount = $facilityMembershipDiscount;
									$RentaldiscountedAmount = $facilityMembershipDiscount;
									$couponCode = $membershipDetails['membershipType'];
								} else {
									$rentalSericeAmt = $cart_items['serviceAmount'][$key];
									$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
									$RentaldiscountedAmount = 0;
								}
							} else {

								$rentalSericeAmt = $cart_items['serviceAmount'][$key] - (($cart_items['serviceAmount'][$key] * $facilityMembershipDiscount) / 100);
								$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
								$RentaldiscountedAmount = $cart_items['serviceAmount'][$key] - $rentalSericeAmt;
								$couponCode = $membershipDetails['membershipType'];
							}
						} else {


							$rentalSericeAmt = $cart_items['serviceAmount'][$key];
							$oldRentalServiceAmount = $cart_items['serviceAmount'][$key];
							$RentaldiscountedAmount = 0;
						}
					} else {
						$rentalSericeAmt = 0;
						$oldRentalServiceAmount = 0;
						$RentaldiscountedAmount = 0;
					}

					$cart_items['serviceAmount'][$key] = $rentalSericeAmt;
					$cart_items['oldServiceAmount'][$key] = $oldRentalServiceAmount;
					$cart_items['discountedAmount'][$key] = $RentaldiscountedAmount;
					$cart_items['couponCode'][$key] = $couponCode;
					$cart_items['couponId'][$key] = "";
				}
			}


			$this->session->set_userdata('facilities_cart', $cart_items);
		}
		$response = array('status' => '1', 'message' => "Success");
		echo json_encode($response);
	}




	public function BookFacilities()
	{


		if ($this->session->userdata('logged_in') == 1) {


			$facilitySettings = SettingsApi()['result']['data'][0]['facilitySettings'];
			$facilities_shift = $facilitySettings['shift'];


			$eventDetails = $this->session->userdata('event_details');
			$serviceDetails = $this->session->userdata('service_details');
			if (empty($serviceDetails)) {
				$serviceDetails = new stdClass();
			}
			$facilitySecurityAmount = @$facilitySettings['facilitySecurityAmount'];
			$facilitySecurityType = @$facilitySettings['facilitySecurityType'];
			// var_dump($eventDetails);
			// echo "<br><br><br>";
			// var_dump($serviceDetails);
			// echo "<br><br><br>";
			$cart_data = $this->session->userdata('facilities_cart');
			// var_dump($cart_data);
			// echo "<br><br><br>";
			if (!empty($this->input->post('totalPrice'))) {
				$totalPrice = $this->input->post('totalPrice');
			} else {
				$totalPrice = $cart_data['totalPrice'];
			}

			$facilitiesData = array();

			for ($i = 0; $i < count($cart_data['ids']); $i++) {

				$startTime = '';
				$endTime = '';
				foreach ($facilities_shift as $shift) {


					if ($shift['name'] === @$cart_data['bookingTypes'][$i]) {
						$startTime = @$shift['startTime'];
						$endTime = @$shift['endTime'];
						// Break the loop once matching shift is found
						break;
					} else {
						$startTime =  @$cart_data['start_time'][$i];
						$endTime  = @$cart_data['end_time'][$i];
					}
				}


				$facilitiesData[] = array(
					"_id" => $cart_data['ids'][$i],
					"ServiceId" => $cart_data['ids'][$i],
					"serviceName" => $cart_data['serviceName'][$i],
					"serviceCategory" => $cart_data['ctg'][$i],
					// "serviceCategory" => "IN-TEMPLE",
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"costPerDay" => $cart_data['serviceAmount'][$i],
					"startDate" => @$cart_data['startDate'][$i],
					"qty" => $cart_data['qty'][$i],
					"time" => @$cart_data['startTime'][$i],
					"day" => "",
					"bookingTypes" => @$cart_data['bookingTypes'][$i],
					"oldServiceAmount" => @$cart_data['oldServiceAmount'][$i],
					"discountedAmount" => @$cart_data['discountedAmount'][$i],
					"couponCode" => @$cart_data['couponCode'][$i],
					"couponId" => @$cart_data['couponId'][$i],
					"startTime" => @$startTime,
					"endTime" => @$endTime
				);
			}
			$paymentType = 'PENDING';
			if ($this->input->post('paymentType') && !empty($this->input->post('paymentType'))) {
				$paymentType = $this->input->post('paymentType');
			}
			$bookingType = '';
			if ($this->input->post('bookingType') && !empty($this->input->post('bookingType'))) {
				$bookingType = $this->input->post('bookingType');
			}



			$mpiInvNumber = floor(microtime(true) * 1000);

			$paymentStatus = '';
			if ($this->input->post('paymentStatus') && !empty($this->input->post('paymentStatus'))) {
				$paymentStatus = $this->input->post('paymentStatus');
			}
			// print_r($facilitiesData); 

			$facilitiesData = json_encode($facilitiesData);

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

			curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . addRentalServiceCart()['url']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);

			curl_setopt($ch, CURLOPT_POSTFIELDS, "{

				\"productId\":\"" . ApiBaseUrl()['productID'] . "\",
				\"clientId\":\"" . ApiBaseUrl()['clientID'] . "\",
				\"memberId\":\"" . $this->session->userdata('id') . "\",
				\"memberName\":\"" . $this->session->userdata('refDataName') . "\",
				\"prsnEmail\":\"" . $this->session->userdata('email') . "\",
				\"prsnPhone\":\"" . $this->session->userdata('phone') . "\",
				\"eventDetail\":" . json_encode($eventDetails) . ",
				\"serviceDetail\": " . json_encode($serviceDetails) . ",
				\"deliveryDetails\":{},
				\"deliveryTime\":\"\",
				\"paymentType\":\"" . $paymentType . "\",
				\"deliveryDate\":\"\",
				\"delivery\":\"\",
				\"etKitchenTIp\":\"\",
				\"pickupTime\":\"\",
				\"bankName\":\"\",
				\"chequeNo\":\"\",
				\"chequeAmount\":\"\",
				\"chequeDate\":\"\",
				\"source\":\"WEBSITE\",
				\"totalAmount\": " . $totalPrice . ",
				\"securityDeposit\": " . $facilitySecurityAmount . ",
				\"transactionId\":\"" . @$this->input->post('transactionId') . "\",
				\"stationName\":\"\",
				\"stationId\":\"\",
				\"userId\":\"" . $this->session->userdata('refDataName') . "\",
				\"data\":$facilitiesData,
				\"cartCreDate\":\"" . date('m/d/Y') . "\",
				\"cartCreTime\":\"" . date('H:i A') . "\",
 		\"serviceImage\":\"\",
        \"serviceName\":\"\",
        \"serviceCategory\":\"\",
        \"serviceType\":\"\",
        \"qty\":\"\",
        \"startTime\":\"\",
        \"endTime\":\"\",
        \"uniteType\":\"\",
        \"costPerUnitType\":\"\",
        \"serviceAmount\":\"\",
        \"userName\":\"\",
        \"beneName\":\"\",
        \"acharyasanbhavana\":0,
        \"generaldonations\":0,
        \"bookingType\": \"" . $bookingType . "\",
        \"paymentStatus\": \"" . $paymentStatus . "\",
        \"mpiInvNumber\": \"" . $mpiInvNumber . "\"
			}");


			$headers = array();
			$headers[] = 'Content-Type: application/json';
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

			$result = curl_exec($ch);
			if (curl_errno($ch)) {
				echo 'Error:' . curl_error($ch);
			}
			curl_close($ch);


			$response = json_decode($result);

			if ($response->statusCode == 1) {
				$this->session->unset_userdata('facilities_cart');
				$this->session->unset_userdata('event_details');
				$this->session->unset_userdata('service_details');
				echo json_encode($response);
			}
		}
	}

	public function ViewCart()
	{
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Facilities';
		$data['title'] = 'Facilities Cart';
		$data['session_data'] = 'facilities_cart';
		$this->load->view('facilities/view-cart', $data);
	}

	public function delete_cart_row()
	{
		$row_id = $this->input->post('row_id');
		$cart_items = $this->session->userdata('facilities_cart');
		$total_price = $cart_items['totalPrice'];
		$row_price = 0;
		foreach ($cart_items['ids'] as $key => $id) {
			if ($id == $row_id) {
				// remove the row from the cart data
				$row_price = $cart_items['serviceAmount'][$key];
				unset($cart_items['ids'][$key]);
				unset($cart_items['serviceName'][$key]);
				unset($cart_items['description'][$key]);
				unset($cart_items['serviceAmount'][$key]);
				unset($cart_items['qty'][$key]);
				unset($cart_items['image'][$key]);
				break;
			}
		}
		// subtract the row amount from the total amount
		$total_price -= $row_price;
		// update the total price in the cart data
		$cart_items['totalPrice'] = $total_price;
		// save the updated cart data to session
		$this->session->set_userdata('facilities_cart', $cart_items);
		// send response to the client
		echo json_encode(array('status' => 'success'));
	}

	public function getShiftTimings()
	{
		$shift = $this->input->post('shift');

		$facilities_shift = SettingsApi()['result']['data'][0]['facilitySettings']['shift'];
		// var_dump($facilities_shift);
		foreach ($facilities_shift as $item) {

			if ($item['name'] == $shift) {
				$startTime = $item['startTime'];
				$endTime = $item['endTime'];
				// Break the loop once matching shift is found
				break;
			} else {
				$startTime =  '';
				$endTime  = '';
			}
		}


		$timings = array('startTime' => $startTime, 'endTime' => $endTime);


		echo json_encode($timings);
	}

	public function getShiftTimingsNew()
	{
		$shift = $this->input->post('shift');
		$facilities_shift = json_decode($this->input->post('facilities_shift'));

		// $facilities_shift = SettingsApi()['result']['data'][0]['facilitySettings']['shift'];

		foreach ($facilities_shift as $item) {

			if ($item['name'] == $shift) {
				$startTime = $item['startTime'];
				$endTime = $item['endTime'];
				// Break the loop once matching shift is found
				break;
			} else {
				$startTime =  '';
				$endTime  = '';
			}
		}


		$timings = array('startTime' => $startTime, 'endTime' => $endTime);


		echo json_encode($timings);
	}

	public function getShiftTimingsRules()
	{
		$shift = $this->input->post('shift');
		$startParsed = $this->input->post('serviceTime');
		// $facilities_shift = json_decode($this->input->post('facilities_shift'));
		$hourlyBookingRules = $this->input->post('hourlyBookingRules');

		// $facilities_shift = SettingsApi()['result']['data'][0]['facilitySettings']['shift'];

		foreach ($hourlyBookingRules as $item) {

			if ($item['slotName'] == $shift) {
				$timeDiffMin = $item['hourFrom'];
				$timeDiffMax = $item['hourTo'];
				$startTime =  '';
				$endTime  = '';
				// Break the loop once matching shift is found
				break;
			} else {
				$timeDiffMin = "";
				$timeDiffMax = "";
				$startTime =  '';
				$endTime  = '';
			}
		}


		$StartTimeValue = $startParsed;
		$EndTimeValue = '';
		if (!empty($startParsed)) {
			if (is_numeric($timeDiffMin) && is_numeric($timeDiffMax)) {
				// Convert the start time to a timestamp
				$startTimestamp = strtotime($startParsed);

				if ($startTimestamp) {
					// Calculate the next available time by adding hourTo (in seconds) to startParsed
					$nextTimestamp = $startTimestamp + ($timeDiffMin * 60 * 60);
					$EndTimeValue = date('h:i A', $nextTimestamp); // Format the next available time as HH:mm

				}
			} else {
				$startTimestamp = strtotime($startParsed);

				$nextTimestamp = $startTimestamp + (30 * 60 * 60);
				$EndTimeValue = date('h:i A', $nextTimestamp);
			}
		}



		$timings = array('startTime' => $startTime, 'endTime' => $endTime, 'hourFrom' => $timeDiffMax, 'hourTo' => $timeDiffMin, '$shift' => $shift, 'slotName' => $item['slotName'], 'StartTimeValue' => $StartTimeValue, 'EndTimeValue' => $EndTimeValue);


		echo json_encode($timings);
	}

	public function SubmitEventForm()
	{
		$postData = $this->input->post();




		$serviceDetails = array();
		if (isset($postData['add_service']) && $postData['add_service'] == 'YES') {

			$membershipDetails = membershipStatusCheck();

			$setting =  SettingsApi();
			$membershipDiscountAmt = $setting['result']['data'][0]['membershipSettings']['membershipDiscount'];
			$discountType = $setting['result']['data'][0]['membershipSettings']['discountType'];



			$serviceDetails['serviceId'] = $postData['serviceId'];
			$serviceDetails['serviceName'] = $postData['serviceName'];
			$serviceDetails['serviceCategory'] = "IN-TEMPLE";
			$serviceDetails['serviceType'] = $postData['serviceType'];
			$serviceDetails['serviceAmount'] = $postData['serviceAmount'];
			$serviceDetails['priestId'] = $postData['priestId'];
			$serviceDetails['priestName'] = $postData['priestName'];
			$serviceDetails['serviceDate'] = $postData['serviceDate'];
			$serviceDetails['serviceTime'] = $postData['serviceTime'];
			$serviceDetails['priestEmail'] = $postData['priestEmail'];
			$serviceDetails['priestPhone'] = $postData['priestPhone'];

			$couponCode = "";
			if ($membershipDetails['membershipStatus'] == "ACTIVE" &&  @$postData['serviceMembershipDiscount'] == 'YES') {

				if ($discountType == 'SERVICE LEVEL') {
					if (@$postData['serviceMembershipDiscountAmt']) {
						$sericeAmt = @$postData['serviceMembershipDiscountAmt'];
						$oldServiceAmount = $postData['serviceAmount'];
						$discountedAmount = $membershipDiscountAmt;
						$couponCode = $postData['serviceAmount'] - @$postData['serviceMembershipDiscountAmt'];
					} else {
						$sericeAmt = $postData['serviceAmount'];
						$oldServiceAmount = $postData['serviceAmount'];
						$discountedAmount = 0;
					}
				} else if ($discountType == 'FLAT') {
					if ($postData['serviceAmount'] > $membershipDiscountAmt) {
						$sericeAmt = $postData['serviceAmount'] - $membershipDiscountAmt;
						$oldServiceAmount = $membershipDiscountAmt;
						$discountedAmount = $membershipDiscountAmt;
						$couponCode = $membershipDetails['membershipType'];
					} else {
						$sericeAmt = $postData['serviceAmount'];
						$oldServiceAmount = $postData['serviceAmount'];
						$discountedAmount = 0;
					}
				} else {

					$sericeAmt = $postData['serviceAmount'] - (($postData['serviceAmount'] * $membershipDiscountAmt) / 100);
					$oldServiceAmount = $postData['serviceAmount'];
					$discountedAmount = $postData['serviceAmount'] - $sericeAmt;
					$couponCode = $membershipDetails['membershipType'];
				}
			} else {


				$sericeAmt = $postData['serviceAmount'];
				$oldServiceAmount = $postData['serviceAmount'];
				$discountedAmount = 0;
			}

			$serviceDetails['serviceAmount'] = $sericeAmt;
			$serviceDetails['oldServiceAmount'] = $oldServiceAmount;
			$serviceDetails['discountedAmount'] = $discountedAmount;
			$serviceDetails['couponCode'] = $couponCode;
			$serviceDetails['couponId'] = "";
		}
		// var_dump($serviceDetails);
		$this->session->set_userdata('service_details', $serviceDetails);


		$eventDetails = array();
		$eventDetails['eventName'] = $postData['eventName'];
		$eventDetails['eventDate'] = $postData['eventDate'];
		$eventDetails['eventTime'] = $postData['eventTime'];
		$eventDetails['eventEndTime'] = @$postData['eventEndTime'];
		$eventDetails['eventAddress'] = $postData['eventLocation'];
		$eventDetails['eventCity'] = $postData['city'];
		$eventDetails['eventState'] = $postData['state'];
		$eventDetails['eventLanguage'] = isset($postData['preferredLanguage']) ? $postData['preferredLanguage'] : '';
		$eventDetails['adults'] = $postData['adults'];
		$eventDetails['children'] = $postData['children'];
		$eventDetails['zip'] = $postData['zipcode'];
		$eventDetails['eventDescription'] = $postData['eventDescription'];

		// Set session data
		$this->session->set_userdata('event_details', $eventDetails);
		
		// Return a response
		$response = array(
			'success' => 1,
			'message' => 'Event details saved successfully.'
		);
		echo json_encode($response);
	}

	public function getfacilityAvailbility()
	{
		if (!empty($this->input->post())) {
			$this->session->unset_userdata('facilities_cart');
			$serviceDate = $this->input->post('serviceDate');
			$targetTime = $this->input->post('targetTime');
			$timestamp = strtotime($targetTime);
			$targetTime = date("h:i A", $timestamp);
			$facilityId = $this->input->post('facilityId');
			$cartList = $this->session->userdata('facilities_cart');
			$participant = $this->input->post('participant');
			// var_dump($cartList);
			echo getfacilityAvailbility($serviceDate, $targetTime, $facilityId, $cartList,$participant);
		} else {
			echo '';
		}
	}

	public function getfacilityAvailbilityStatus()
	{
		if (!empty($this->input->post())) {
			// $this->session->unset_userdata('facilities_cart');
			$serviceDate = $this->input->post('serviceDate');
			$targetTime = $this->input->post('targetTime');
			$targetEndTime = $this->input->post('targetEndTime');
			$timestamp = strtotime($targetEndTime);
			$targetEndTime = date("h:i A", $timestamp);
			$facilityId = $this->input->post('facilityId');
			$participant = $this->input->post('participant');
			// var_dump($cartList);
			echo getfacilityAvailbilityStatus($serviceDate, $targetTime, $facilityId, $targetEndTime,$participant);
		} else {
			echo json_encode(0);
		}
	}

}
