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

class Prasadam extends MY_Controller
{

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

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

	public function index()
	{


		$data['page'] = 'Prasadam';
		$data['title'] = 'Prasadam';
		$data['header'] = 'Prasadam';


		$json_data = json_encode([

			"query" => [
				"date" => date('m/d/Y')
			],
			"userName" => "vaapadmin3230",
			"productId" => ApiBaseUrl()['productID'],
			"clientId" => ApiBaseUrl()['clientID']

		]);


		$data['dailyMenu'] = getDailyMenu($json_data);



		$data['userDetails'] = [];


		$this->load->view('prasadam/index', $data);
	}
	public function List()
	{


		$data['page'] = 'Prasadam';
		$data['title'] = 'Prasadam';
		$data['header'] = 'Prasadam';

		$date = @$this->input->get('selectdate');
		if (empty($data)) {
			$date = date('m/d/Y');
		}

		$json_data = json_encode([

			"query" => [
				"date" => $date
			],
			"userName" => "vaapadmin3230",
			"productId" => ApiBaseUrl()['productID'],
			"clientId" => ApiBaseUrl()['clientID']

		]);


		$dailyMenu = getDailyMenu($json_data);



		$fooItemsList = [];
		$groupedMenu = []; // refDataCode ke hisaab se grouping

		foreach ($dailyMenu as $item) {
			// Step 1: unique refDataCode nikalna
			if (!in_array($item->refDataCode, $fooItemsList)) {
				$fooItemsList[] = $item->refDataCode;
			}

			// Step 2: same refDataCode ke items ko group karna
			$groupedMenu[$item->refDataCode][] = $item;
		}

		$data['dailyMenu'] = $dailyMenu;
		$data['groupedMenu'] = $groupedMenu;
		$data['fooItemsList'] = $fooItemsList;

		$json_food_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "menuType",
					"refDataCode" => "FOOD ITEM",
				],
				"moduleName" => "Master Data Management",
				"aspectType" => "menuType",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 1000
			]
		]);
		// var_dump($json_food_data);

		// $data['fooItemsList'] = getFilterData($json_food_data);
		$data['userDetails'] = [];


		$this->load->view('prasadam/list', $data);
	}

	public function indexOLD()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'Prasadam';
			$data['title'] = 'Prasadam';
			$data['header'] = 'Prasadam';

			// $data['dailyMenu'] = getDailyMenuDevotee();
			$json_data = json_encode([
				"componentConfig" => [
					"query" => [
						"aspectType" => "catering"
					],
					"moduleName" => "Catering Setup",
					"aspectType" => "catering",
					"userName" => "vaapadmin3230",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"skip" => 0,
					"next" => 1000
				]
			]);

			$data['dailyMenu'] = getFilterData($json_data);

			$json_food_data = json_encode([
				"componentConfig" => [
					"query" => [
						"aspectType" => "menuType",
						"refDataCode" => "FOOD ITEM",
					],
					"moduleName" => "Master Data Management",
					"aspectType" => "menuType",
					"userName" => "vaapadmin3230",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"skip" => 0,
					"next" => 1000
				]
			]);

			$data['fooItemsList'] = getFilterData($json_food_data);
			$data['userDetails'] = $response->data[0];
			$addressLine1 = @$data['userDetails']->addressLine1;
			$cityTypes = @$data['userDetails']->cityTypes;
			$county = @$data['userDetails']->county;
			$stateTypes = @$data['userDetails']->stateTypes;
			$zip = @$data['userDetails']->zip;
			if (empty(trim($addressLine1)) || empty(trim($cityTypes)) || empty(trim($stateTypes)) || empty(trim($zip))) {
				$this->session->set_flashdata('show_profile_alert', true);
				redirect(base_url('admin/update-profile'));
			} else {

				$this->load->view('prasadam/list', $data);
			}
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}

	public function index2()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'Prasadam';
			$data['title'] = 'Prasadam';
			$data['header'] = 'Prasadam';

			$data['dailyMenu'] = getDailyMenuDevotee();
			$json_data = json_encode([
				"componentConfig" => [
					"query" => [
						"aspectType" => "catering"
					],
					"moduleName" => "Catering Setup",
					"aspectType" => "catering",
					"userName" => "vaapadmin3230",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"skip" => 0,
					"next" => 1000
				]
			]);

			// $data['dailyMenu'] = getFilterData($json_data);

			$json_food_data = json_encode([
				"componentConfig" => [
					"query" => [
						"aspectType" => "menuType",
						"refDataCode" => "FOOD ITEM",
					],
					"moduleName" => "Master Data Management",
					"aspectType" => "menuType",
					"userName" => "vaapadmin3230",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"skip" => 0,
					"next" => 1000
				]
			]);

			$data['fooItemsList'] = getFilterData($json_food_data);
			$data['userDetails'] = $response->data[0];
			$addressLine1 = @$data['userDetails']->addressLine1;
			$cityTypes = @$data['userDetails']->cityTypes;
			$county = @$data['userDetails']->county;
			$stateTypes = @$data['userDetails']->stateTypes;
			$zip = @$data['userDetails']->zip;
			if (empty(trim($addressLine1)) || empty(trim($cityTypes)) || empty(trim($stateTypes)) || empty(trim($zip))) {
				$this->session->set_flashdata('show_profile_alert', true);
				redirect(base_url('admin/update-profile'));
			} else {

				$this->load->view('prasadam/list2', $data);
			}
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}

	public function addCart()
	{
		if ($this->input->post()) {
			// echo "<pre>";
			// var_dump($this->input->post());die();
			$this->session->set_userdata('prasadam_cart', $this->input->post());

			$cartList = $this->session->userdata('prasadam_cart');

			if (isset($cartList['includeSankalpam'])) {
				$includeSankalpam = checkForYesValue($cartList['includeSankalpam']);
			} else {

				$includeSankalpam = 'NO';
			}
		}


		$response = array(
			'status' => '1',
			'message' => "Success",
			'includeSankalpam' => $includeSankalpam
		);
		echo json_encode($response);
	}


	public function delete_cart_row()
	{
		$row_id 	= $this->input->post('row_id');
		$selected_date 	= $this->input->post('selected_date');

		$cart_items = $this->session->userdata('prasadam_cart');
		$total_price = $cart_items['totalPrice'];
		$row_price = 0;



		foreach ($cart_items['ids'] as $key => $id) {
			if ($id == $row_id) {




				unset($cart_items['ids'][$key]);
				unset($cart_items['qty'][$key]);
				unset($cart_items['serviceName'][$key]);
				unset($cart_items['description'][$key]);
				unset($cart_items['serviceAmount'][$key]);
				unset($cart_items['image'][$key]);
				unset($cart_items['startDate'][$key]);
				unset($cart_items['startTime'][$key]);
				unset($cart_items['cart_ctg'][$key]);
				unset($cart_items['serviceTypes'][$key]);
				unset($cart_items['serviceCategoryTypes'][$key]);
				unset($cart_items['bookingtype'][$key]);
				unset($cart_items['ctg'][$key]);
				unset($cart_items['isServicePaid'][$key]);
				unset($cart_items['service_desc'][$key]);
				unset($cart_items['serviceOccurrencesNo'][$key]);
				unset($cart_items['oldServiceAmount'][$key]);
				unset($cart_items['discountedAmount'][$key]);
				unset($cart_items['trayType'][$key]);
				if (isset($cart_items['fullPackage'][$key])) {
					unset($cart_items['fullPackage'][$key]);
				}
				if (isset($cart_items['isDietySelected'][$key])) {
					unset($cart_items['isDietySelected'][$key]);
				}
				if (isset($cart_items['dietyName'][$key])) {
					unset($cart_items['dietyName'][$key]);
				}
				if (isset($cart_items['disclaimerText'][$key])) {
					unset($cart_items['disclaimerText'][$key]);
				}

				break;
			}
		}

		foreach ($cart_items as $cart_key => &$cart_value) {
			if ($cart_key != 'totalPrice') {
				if (is_array($cart_value)) {
					$cart_value = array_values($cart_value);
				}
			}
		}

		$total_price = (float)$total_price - (float)$row_price;
		// echo $total_price; die();

		$cart_items['totalPrice'] = $total_price;
		$this->session->set_userdata('prasadam_cart', $cart_items);
		echo json_encode(array('status' => 'success'));
	}



	public function getTempCart()
	{
		$session_data = $this->session->userdata('prasadam_cart');
		$currencySymbol = getCurrencySymbol(); // ya database/config se fetch

		$html = '<h4>Cart Items</h4>
									<hr>
								</div>';
		$TotalAmt = 0;
		if (!empty($session_data['ids'])) {
			foreach ($session_data['ids'] as $i => $id) {
				$TotalAmt += (float)$session_data['serviceAmount'][$i];
				$html .= '
            <div class="col-sm-12 col-md-12 col-xl-12 col-lg-12 mb-3 px-1">
                <div class="card">
                    <div class="row">
                        <div class="col-md-4 d-flex justify-content-center align-items-center img-div">
                            <img src="' . ApiBaseUrl()['url'] . $session_data['image'][$i] . '" class="img-fluid rounded-start" alt="' . $session_data['serviceName'][$i] . '" style="max-width: 70%!important;">
                        </div>
                        <div class="col-md-8 details-div">
                            <div class="card-body">
                                <h5 class="card-title">' . $session_data['serviceName'][$i] . '</h5>
                                <p class="card-text"><b>Unit Price : ' . $currencySymbol . $session_data['serviceAmount'][$i] . '</b></p>
								<p><a href="javaScript:void(0)" class="btn-danger btn-sm service-delete-row" data-row-id="' . $id . '" style="font-size:17px"><i class="fa fa-trash-o"></i></a></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>';
			}
		}
		$html .= '<div class="col-sm-12 pt-3 pb-3" style="background:#ffffff!important;">
									<h4>Total: ' . $currencySymbol . price_format($TotalAmt, 2) . '</h4>
									<a href="javaScript:void(0);" onclick="ValidateCheckout()" type="button" class="btn btn-danger"><i class="fa fa-check-circle" aria-hidden="true"></i> Checkout</a>
									<a href="' . base_url('admin/prasadam_clear_cart') . '" type="button" class="btn btn-danger loader" ><i class="fa fa-trash" aria-hidden="true"></i> Clear</a>
								</div>';

		echo $html;
	}

	public function checkout_prasadam()
	{
		$session_data = $this->session->userdata('prasadam_cart');
		if (!empty($session_data['ids']) && ValidatePrasadamCheckout()) {
			$response = getUserDetails();
			if ($response->statusCode == 1) {
				$data['page'] = 'Prasadam';
				$data['title'] = 'Prasadam';
				$data['header'] = 'Prasadam';

				$data['dailyMenu'] = getDailyMenuDevotee();
				$data['userDetails'] = $response->data[0];
				$this->load->view('admin/prasadam', $data);
			} else {
				echo json_encode('User not found!!');
				$this->session->unset_userdata('logged_in');
				redirect(base_url());
			}
		} else {
			// echo "okkk";die();
			redirect(base_url('admin/prasadam'));
		}
	}

	public function clear_cart()
	{

		$session_data = $this->session->userdata('prasadam_cart');
		if (!empty($session_data['ids'])) {
			$this->session->unset_userdata('prasadam_cart');
		}
		redirect(base_url('admin/prasadam'));
	}
	public function ValidateCheckout()
	{
		$returnStatus = ValidatePrasadamCheckout();

		echo json_encode($returnStatus);
	}

	public function AddToCart()
	{

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



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

			if ($paymentSource == 'CAW') {
				$paymentSource_data = 'CAW_CARD_NOT_PRESENT';
			} else if ($paymentSource == 'MPI') {
				$paymentSource_data = 'MPI_CARD_NOT_PRESENT';
			} else {
				$paymentSource_data = 'PAYPAL_CARD_NOT_PRESENT';
			}


			$PaymentStatus = $this->input->post('status');

			$cart_data = $this->session->userdata('prasadam_cart');
			// var_dump($cart_data);
			if (!is_array($cart_data)) {
				$cart_data = json_decode($this->input->post('prasadam_cart'), true);
			}
			// var_dump($cart_data);die();

			$dataWithAmount = array();
			$etKitchenTIp = @$this->input->post('etKitchenTIp') ?? 0;
			$delivery = @$this->input->post('delivery');
			if ($delivery == 'Delivery') {
				$address = @$this->input->post('address');
				$City = @$this->input->post('City');
				$state = @$this->input->post('state');
				$zipcode = @$this->input->post('zipcode');
			} else {
				$address = "";
				$City = "";
				$state = "";
				$zipcode = "";
			}

			$deliveryDetails = new stdClass();

			$deliveryDetails->delivery = $delivery;
			$deliveryDetails->delivery = $delivery;
			$deliveryDetails->address = $address;
			$deliveryDetails->City = $City;
			$deliveryDetails->state = $state;
			$deliveryDetails->zipcode = $zipcode;
			$deliveryDetails->memberName = $this->session->userdata('refDataName');

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

				$payment_type_check = @$cart_data['bookingtype'][$i];


				$dataWithAmount[] = array(
					"_id" => $cart_data['ids'][$i],
					"ServiceId" => $cart_data['ids'][$i],
					"serviceName" => $cart_data['serviceName'][$i],
					"serviceCategory" => $cart_data['ctg'][$i],
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceCategory" => $cart_data['serviceCategoryTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"trayType" => @$cart_data['trayType'][$i],
					"startDate" => '',
					"qty" => $cart_data['qty'][$i],
					"time" => @$cart_data['startTime'][$i],
					"bookingType" => @$payment_type_check,
					"day" => "",
					"serviceAddress" => "",
					"cartCreDate" => date("m/d/Y"),
					"cartCreTime" => date("h:i A"),
					"isServicePaid" => @$cart_data['isServicePaid'][$i],
					"serviceDesc" => @$cart_data['service_desc'][$i],
					"serviceOccurrencesNo" => @$cart_data['serviceOccurrencesNo'][$i],
					"fullPackage" => @$cart_data['fullPackage'][$i],
					"oldServiceAmount" => isset($cart_data['oldServiceAmount'][$i]) && $cart_data['oldServiceAmount'][$i] > 0 ? $cart_data['oldServiceAmount'][$i] : $cart_data['serviceAmount'][$i],
					"discountedAmount" => isset($cart_data['discountedAmount'][$i]) && $cart_data['discountedAmount'][$i] > 0 ? $cart_data['discountedAmount'][$i] : 0,
				);
			}

			$dataWithAmountJson = json_encode($dataWithAmount);

			// var_dump($dataWithAmountJson);die();
			if (!empty($dataWithAmount)) {


				$ch = curl_init();


				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . addServiceCart()['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') . "\", 

					\"data\": $dataWithAmountJson, 

					\"paymentType\": \"CREDIT CARD\",
					\"paymentSource\": \"" . $paymentSource_data . "\", 
					\"attemptType\": \"" . $PaymentStatus . "\",
					\"cartCreDate\": \"" . date("m/d/Y") . "\",
					\"cartCreTime\": \"" . date("h:i A") . "\",

					\"bankName\":\"\" ,
					\"chequeNo\":\"\" , 
					\"chequeAmount\":\"\" , 
					\"chequeDate\": \"\", 
					\"acharyasanbhavana\": \"" . @$this->input->post('acharya_sambhavana') . "\", 
					\"generaldonations\": \"" . @$this->input->post('general_donation') . "\", 

					\"totalAmount\": " . $this->input->post('totalPrice') . ", 
					\"transactionId\":\"" . $this->input->post('transaction_id') . "\",
					\"source\":\"WEBSITE\",
					
					\"deliveryDetails\": " . json_encode($deliveryDetails) . ",
					\"deliveryTime\": \"" . date("h:i A",strtotime($this->input->post('deliveryTime'))) . "\",
					\"deliveryDate\": \"" . $this->input->post('deliveryDate') . "\",
					\"delivery\": \"" . $this->input->post('delivery') . "\",
					\"etKitchenTIp\": \"" . $etKitchenTIp . "\"
					

				}     
				");
				$token = $this->session->userdata('token');
				$headers = array();


				$headers[] = 'Authorization: Bearer ' . $token . '';

				$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);

				$response2 = json_decode($result);
				$sess_temp_order_details = json_decode($result, true);

				// print_r($sess_temp_order_details);


				$this->session->set_userdata('temp_order_details', $sess_temp_order_details['data'][0]);
			}

			if ($PaymentStatus != 'TEMP') {



				echo json_encode($response2);
			} else {
				echo json_encode($response2);
			}
		}
	}

	public function updateTransactionStatus($id = '', $invoiceNo = '', $PaymentStatus = '')
	{

		// if (!empty($this->input->post('transaction_id'))) {
		$paymentDescription = json_encode(@$this->input->post('paymentDescription'));
		$transactionId = @$this->input->post('transaction_id');
		$PaymentStatus = @$this->input->post('status');
		// } else {
		// 	$transactionId = '';
		// }

		if (!empty($this->session->userdata('temp_order_details'))) {
			$invoiceNo = $this->session->userdata('temp_order_details')['invoiceNo'];
			$id = $this->session->userdata('temp_order_details')['_id'];
		}


		$ch = curl_init();

		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . updateTransactionStatus()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{         
			\"productId\": \"" . ApiBaseUrl()['productID'] . "\",
			\"clientId\": \"" . ApiBaseUrl()['clientID'] . "\",  

			\"_id\":\"" . $id . "\",      
			\"invoiceNo\":\"" . $invoiceNo . "\",      
			\"paymentStatus\": \"" . $PaymentStatus . "\",      
			\"transactionId\": \"" . $transactionId . "\"

		}     
		");

		$token = $this->session->userdata('token');

		$headers = array();

		$headers[] = 'Authorization: Bearer ' . $token . '';

		$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);


		if (!empty($this->input->post('transaction_id')) && $PaymentStatus == 'COMPLETED') {
			// print_r($result);
			$response = json_decode($result);

			$this->session->unset_userdata('temp_order_details');
			$this->session->unset_userdata('prasadam_cart');

			$data['orderId'] = $id;
			$data['envoiceNo'] = $invoiceNo;
			$data['statusCode'] = $response->statusCode;
			$data['message'] = $response->message;
			$updatedResponse = json_encode($data);
			print_r($updatedResponse);
		} else if (!empty($this->input->post('transaction_id')) && $PaymentStatus == 'FAILED') {
			// print_r($result);
			$response = json_decode($result);

			// $this->session->unset_userdata('temp_events_order_details');
			// $this->session->unset_userdata('events_cart');

			$data['orderId'] = $id;
			$data['envoiceNo'] = $invoiceNo;
			$data['statusCode'] = $response->statusCode;
			$data['message'] = $transactionId;
			$updatedResponse = json_encode($data);
			print_r($updatedResponse);
		} else {

			return $response = json_decode($result);
		}
	}

	public function checkout_prasadam_web()
	{
		$session_data = $this->session->userdata('prasadam_cart');
		if (!empty($session_data['ids']) && ValidatePrasadamCheckout()) {
			$response = getUserDetails();
			if ($response->statusCode == 1) {
				$data['page'] = 'Prasadam';
				$data['title'] = 'Prasadam';
				$data['header'] = 'Prasadam';
				$data['GetState'] = GetState();
				$data['dailyMenu'] = getDailyMenuDevotee();
				$data['userDetails'] = $response->data[0];
				// $this->load->view('prasadam/list', $data);
				$this->load->view('prasadam/checkout', $data);
			} else {
				echo json_encode('User not found!!');
				$this->session->unset_userdata('logged_in');
				redirect(base_url('prasadam'));
			}
		} else {
			// echo "okkk";die();
			redirect(base_url('prasadam'));
		}
	}



	//================================PRASADAM SAME PRODUCT MULTIPLE TIME ADD TO CART
	public function MenuList()
	{


		$data['page'] = 'Prasadam';
		$data['title'] = 'Prasadam';
		$data['header'] = 'Prasadam';

		// $data['dailyMenu'] = getDailyMenuDevotee();
		$json_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "catering"
				],
				"moduleName" => "Catering Setup",
				"aspectType" => "catering",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 1000
			]
		]);

		$data['dailyMenu'] = getFilterData($json_data);

		$json_food_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "menuType",
					"refDataCode" => "FOOD ITEM",
				],
				"moduleName" => "Master Data Management",
				"aspectType" => "menuType",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 1000
			]
		]);
		// var_dump($json_food_data);

		$data['fooItemsList'] = getFilterData($json_food_data);
		$data['userDetails'] = [];


		$this->load->view('prasadam/menu-list', $data);
	}


	public function addSingleCart()
	{
		if ($this->input->post()) {
			$newItem = $this->input->post();

			// Purana cart nikal lo (agar hai)
			$cartList = @$this->session->userdata('prasadam_cart')['ids'] ? $this->session->userdata('prasadam_cart') : [
				"uniqueKey"               => [],
				"ids"                     => [],
				"totalPrice"              => 0,
				"qty"                     => [],
				"ctg"                     => [],
				"serviceTypes"            => [],
				"serviceName"             => [],
				"startDate"               => [],
				"startTime"               => [],
				"serviceAmount"           => [],
				"cart_type"               => [],
				"image"                   => [],
				"description"             => [],
				"is_membership_discount"  => [],
				"membership_discount_amt" => [],
				"service_desc"            => [],
				"serviceOccurrencesNo"    => [],
				"fullPackage"             => [],
				"isDietySelected"         => [],
				"trayType"                => [],
			];

			// ek item data normalize karke banate hain
			$id       = $newItem['ids'][0];
			$trayType = $newItem['trayType'][0] ?? '';
			$uniqueKey = $id . '_' . $trayType;

			$foundIndex = array_search($uniqueKey, $cartList['uniqueKey']);

			// Item ka amount
			$serviceAmount = (float)($newItem['serviceAmount'][0] ?? 0);
			$qty           = (int)($newItem['qty'][0] ?? 1);

			if ($foundIndex !== false) {
				// update qty and price for existing item
				$cartList['qty'][$foundIndex] = $qty;
			} else {
				// push new values (flat arrays only)
				$cartList['uniqueKey'][]               = $uniqueKey;
				$cartList['ids'][]                     = $id;
				$cartList['qty'][]                     = $qty;
				$cartList['ctg'][]                     = $newItem['ctg'][0] ?? '';
				$cartList['serviceTypes'][]            = $newItem['serviceTypes'][0] ?? '';
				$cartList['serviceName'][]             = $newItem['serviceName'][0] ?? '';
				$cartList['startDate'][]               = $newItem['startDate'][0] ?? '';
				$cartList['startTime'][]               = $newItem['startTime'][0] ?? '';
				$cartList['serviceAmount'][]           = $serviceAmount;
				$cartList['cart_type'][]               = $newItem['cart_type'] ?? '';
				$cartList['image'][]                   = $newItem['image'][0] ?? '';
				$cartList['description'][]             = $newItem['description'][0] ?? '';
				$cartList['is_membership_discount'][]  = $newItem['is_membership_discount'][0] ?? '';
				$cartList['membership_discount_amt'][] = $newItem['membership_discount_amt'][0] ?? '';
				$cartList['service_desc'][]            = $newItem['service_desc'][0] ?? '';
				$cartList['serviceOccurrencesNo'][]    = $newItem['serviceOccurrencesNo'][0] ?? '';
				$cartList['fullPackage'][]             = '';
				$cartList['isDietySelected'][]         = '';
				$cartList['trayType'][]                = $trayType;
			}
			$grandTotal = 0;
			if (!empty($cartList['ids'])) {
				foreach ($cartList['ids'] as $i => $id) {
					$grandTotal += (float)$cartList['serviceAmount'][$i] * (int)$cartList['qty'][$i];
				}
			}
			$cartList['totalPrice'] = $grandTotal;
			// ab session update karo
			$this->session->set_userdata('prasadam_cart', $cartList);



			$response = [
				'status'     => '1',
				'message'    => 'Success',
				'totalPrice' => $grandTotal,
				'cartCount'  => count($cartList['ids']),
				// 'cartList'   => $cartList
			];

			echo json_encode($response);
		}
	}
}
