<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<link rel="stylesheet" type="text/css" href="<?=base_url('assets/css/pledge.css');?>">
<?php 

$session_data = $this->session->userdata('pledge_cart');
$cart_count = isset($session_data['ids']) && $session_data['ids'] ? count($session_data['ids']) : 0;
$cart_count = $cart_count != '' ? $cart_count : 0;
if(empty($session_data['ids'])) {
	$session_data = array('totalPrice' => 0.00, 'ids' => array());
}

?>
<main id="main">
	<section style="background-image: url(<?=base_url('assets/img/elegant-background-with-mandala.png');?>);background-size: auto;">
		<center> 
			<h2 class="bottomborder" style="font-weight:bold!important;font-size: 35px!important;">Pledge Form</h2> 
		</center>
		<br>

		<!-- <?php echo '<pre>'; print_r($session_data['totalPrice']); ?> -->

			<div class="h-100 responsive-container">
				<div class="row d-flex justify-content-center align-items-center h-100">
					<div class="col-12">
						<div class="card card-registration card-registration-2 mb-4" style="border-radius: 15px;">
							<div class="card-body p-3">
								<div class="card-header text-end px-3" style="font-size: 18px!important;background-color:#315c61;">
									<a href="javascript:void(0)" class="btn" onclick="window.history.back()" style=";background-color:#df4a19;color: white!important;border-radius: 1px!important;">← Back</a>
									<a href="<?= base_url('donations'); ?>" class="btn" style=";background-color:#009688;color: white!important;border-radius: 1px!important;">Close X</a>
								</div>
								<?php 
								$currencySymbol = isset($GeneralSettings['currencySymbol']) ? (CheckEmptyNullVar($GeneralSettings['currencySymbol']) != '' ? $GeneralSettings['currencySymbol'] : '$' ) : '$'; ?>




								<div class="row g-0">
									<div class="col-lg-7" style="background-color:#f5f5f5">
										<div class="p-5">

											<div class="d-flex justify-content-between align-items-center mb-5">
												<h3 class="fw-bold mb-0 text-black">Pledge For</h3>

												<!-- <h6 class="mb-0 text-muted">items</h6> -->
											</div>
											<hr class="my-4">
											<!-- ============================================= -->


											<div class="responsive" style="height: auto!important;">
												<table width="100%" height="100%">
													<thead>
														<tr>
															<th width="95%">Pledge For</th>
															<!-- <th width="25%"></th> -->
															<th width="5%"></th>
														</tr>
													</thead>
													<tbody style="overflow-y: auto;">
														<?php foreach($recurring_donations as $item){ ?>
															<tr>
																<td><?=$item['refDataName']?><?=@$item['serviceAmount'] ? '($ '.@price_format($item['serviceAmount'], 2).')': '$ 0.00'?></td>
																<td>
																	<div class="form-check">
																		<input type="checkbox" class="form-check-input"  value="<?=$item['_id']?>"  data-id="<?=$item['_id']?>" data-category="<?=$item['serviceCategoryTypes']?>" cart_category="PLEDGE FORM" data-service-type="<?=$item['serviceTypes']?>" data-start-time="<?=$item['startTime']?>" data-start-date="<?=$item['startDate']?>"  data-service-name="<?=replaceSingleQuotesWithBackticks($item['refDataName'])?>" data-price="<?=$item['serviceAmount']?>" data-end-date="<?=$item['endDate']?>" data-end-time="<?=$item['endTime']?>" data-description="<?=replaceSingleQuotesWithBackticks(trim($item['description']))?>" data-image="<?=$item['Image']?>" booking_type="<?=@$bookingType?>"   onchange="addTocartList()" name="services_id[]" includeSankalpam="<?=@$includeSankalpam?>" style="padding:14px!important" <?= ((@in_array($item['_id'], @$session_data['ids']))?'checked':'') ?> >
																	</div>
																</td>
															</tr>

														<?php } ?>

													</tbody>
												</table>
											</div>
											<!-- ============================================= -->

											<hr class="my-4">

											<div class="row mt-3">
												<div class="col-md-10"><h5 class="mb-0"  style="font-weight:bold!important;">Subtotal</h5></div>
												<div class="col-md-2 text-end"><span style="font-weight:bold!important;" id="subttl">$ <?=price_format($session_data['totalPrice'], 2)?></span></div>

											</div>


											<hr class="my-4">

											<div class="row p-3" style="background-color:#dbdbdb">
												<div class="col-md-8"><h4 class="text-dark" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;">Pledge Total</h4></div>
												<div class="col-md-4">

													<h4 class="text-dark text-end" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;" id="pledgetotal">$ <?=price_format($session_data['totalPrice'], 2)?>
												</h4>
											</div>
										</div>
									</div>
								</div>
								<div class="col-lg-5">
									<div class="p-5">
										<div class="row">
											<div class="col-md-7 fw-bold text-start"><h5 class="mb-2" style="color:#009688!important"><?= @$this->session->userdata('refDataName');?></h5><span><?=@ base64_decode($this->session->userdata('email')) ;?></span></div>
											<div class="col-md-5 fw-bold text-end" style="word-wrap:none ;color:#009688!important">

												<?=formatPhoneNumber(@base64_decode($this->session->userdata('phone')));?>

											</div>
										</div>
										<hr class="my-4">


										<div class="text-center my-3">

											<ul id="cartListHeading">
												<li>
													<span style="font-weight: bold;font-size: 18px;" id="ttl_items">Pledge For (<?=$cart_count < 2 ? $cart_count.' Item' : $cart_count.' Items' ?>)</span>
													<span style="font-weight: bold;font-size: 18px;">Amount</span>
												</li>
											</ul>

											<ul id="cartList">
												<?php for($i = 0; $i < count($session_data['ids']); $i++) { ?>
													<li>
														<span><?=$session_data['serviceName'][$i]?></span>
														<span>$ <?=price_format($session_data['serviceAmount'][$i], 2)?></span>
													</li>
												<?php } ?>
											</ul>


											<div class="d-flex justify-content-between my-4">
												<h3 class="fw-bold" style="font-size: 25px;">Amount to Pay:</h3>
												<h3 class="fw-bold text-end" style="font-size: 25px;border: 2px solid #dbdbdb;border-radius: 9px;padding: 3px;" id="total-price">$ <?=price_format($session_data['totalPrice'], 2)?></h3>
											</div>

											<!-- <h3>Recurring Module Coming Soon...</h3> -->
											<!-- Recurring Form Start-->

											<form id="pledge-form" action="<?=base_url('PledgeForm/SubmitPledgeForm')?>" method="post">
												<fieldset class="border-2 shadow bg-white p-0">

													<div class="row">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Select Debit Frequency</legend>
																<div class="input-group">

																	<select id="debitFequency" name="debitFequency" style="color:black!important;" class="form-control rounded  form-select border-0">
																		<option value=" " selected disabled>Select Debit Frequency</option>
																		<option value="Daily">Daily</option>
																		<option value="Weekly">Weekly</option>
																		<option value="Monthly">Monthly</option>
																		<option value="Annually">Annually</option>

																	</select>
																</div>
															</fieldset>
														</div>
													</div>



													<!-- Daily Section start -->

													<div class="row payment-section" style="display: none;" id="DailySection">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Daily Payment Schedule<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>
																<div class="input-group">

																	<input type="text" name="startDailyDate" id="startDailyDate" class="form-control" placeholder="Start Date" required readonly>

																</div>
																<div class="input-group my-2">

																	<input type="text" name="endDailyDate" id="endDailyDate" class="form-control" placeholder="End Date" required readonly>

																</div>


															</fieldset>
														</div>
													</div>

													<!-- Daily Section end -->

													<!-- Weekly Section start -->

													<div class="row payment-section" style="display: none;" id="WeeklySection">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Weekly Payment Schedule<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>
																<div class="input-group">

																	<input type="text" name="startWeeklyDate" id="startWeeklyDate" class="form-control" placeholder="Start Date" required readonly>

																</div>
																<div class="input-group my-2">

																	<input type="text" name="endWeeklyDate" id="endWeeklyDate" class="form-control" placeholder="End Date" required readonly>

																</div>

																<div class="input-group my-2">
																	<select id="selectWeeklyDay" name="selectWeeklyDay" style="color:black!important;" class="form-control rounded  form-select " required>
																		<option value=" " selected disabled>Select Day</option>
																		<option value="Monday">Monday</option>
																		<option value="Tuesday">Tuesday</option>
																		<option value="Wednesday">Wednesday</option>
																		<option value="Thursday">Thursday</option>
																		<option value="Friday">Friday</option>
																		<option value="Saturday">Saturday</option>
																		<option value="Sunday">Sunday</option>
																	</select>
																</div>

															</fieldset>
														</div>
													</div>

													<!-- Weekly Section end -->


													<!-- Monthly Section start -->

													<div class="row payment-section" style="display: none;" id="MonthlySection">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Monthly Payment Schedule<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>
																<div class="input-group">

																	<input type="text" name="startMonthlyDate" id="startMonthlyDate" class="form-control" placeholder="Start Date" required readonly>

																</div>
																<div class="input-group my-2">

																	<input type="text" name="endMonthlyDate" id="endMonthlyDate" class="form-control" placeholder="End Date" required readonly>

																</div>

																<div class="input-group my-2">
																	<select id="selectmonthDate" name="selectmonthDate" style="color:black!important;" class="form-control rounded  form-select " required>
																		<option value=" " selected disabled>Select Day of Month</option>
																		<?php for($i=1; $i<=30; $i++){ ?>
																			<option value="<?=$i?>"><?=$i?></option>

																		<?php } ?>
																	</select>
																</div>


															</fieldset>
														</div>
													</div>

													<!-- Monthly Section end -->

													<!-- Annually Section start -->

													<div class="row payment-section" style="display: none;" id="AnnuallySection">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Annually Payment Schedule<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>

																<div class="input-group my-2">
																	<select id="selectAnualyMonthValue" name="selectAnualyMonthValue" style="color:black!important;" class="form-control rounded form-select" required>
																		<option value="" selected disabled>Select Month</option>
																		<?php
																		$months = array(
																			"January", "February", "March", "April", "May", "June",
																			"July", "August", "September", "October", "November", "December"
																		);

																		foreach ($months as $index => $month) {
																			?>
																			<option value="<?= $index + 1 ?>"><?= $month ?></option>
																			<?php
																		}
																		?>
																	</select>
																</div>

																<div class="input-group my-2">
																	<select id="selectAnualyDateValue" name="selectAnualyDateValue" style="color:black!important;" class="form-control rounded form-select" required>
																		<option value="" selected disabled>Select Date</option>
																	</select>
																</div>


																<div class="input-group">
																	<select name="startAnualyDate" id="startAnualyDate" style="color:black!important;" class="form-control rounded  form-select " required>
																		<option class=" " disabled selected>Start Year</option>
																		<!-- Generate options for start year -->
																		<?php
																		$currentYear = date("Y");
																		for ($year = $currentYear; $year <= $currentYear + 100; $year++) {
																			echo "<option value='$year'>$year</option>";
																		}
																		?>
																	</select>
																</div>
																<div class="input-group my-2">
																	<select name="endAnualyDate" id="endAnualyDate" style="color:black!important;" class="form-control rounded  form-select " required>
																		<option class=" " disabled selected>End Year</option>
																		<!-- Options for end year are set using JavaScript based on the selected start year -->
																	</select>
																</div>
															</fieldset>
														</div>
													</div>

													<!-- Annually Section end -->

													<div class="row">

														<div class="col-md-12">
															<fieldset class="border">
																<legend  class="legend-inner float-none w-auto">Mode of Payment<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>
																<div class="form-check form-check-inline" style="padding-bottom: 5px;">
																	<input class="form-check-input" type="checkbox" id="inlineCheckbox2" name="creditcard" checked readonly>
																	<label class="form-check-label m-auto pt-2" for="inlineCheckbox2">Credit Card</label>
																</div>

																<!-- <div class="form-check form-check-inline" style="padding-bottom: 5px;">
																	<input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="ach">
																	<label class="form-check-label m-auto pt-2" for="inlineCheckbox1">ACH</label>
																</div> -->

																<script src="https://use.fontawesome.com/67ed5102d2.js"></script>
																<script type="text/javascript" src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
																<script type="text/javascript" src="https://nosir.github.io/cleave.js/lib/cleave-phone.i18n.js"></script>

																<div class="row">
																	<div class="col-md-12 mt-2">
																		<div class="input-group">
																			<span class="input-group-addon">
																				<span class="type"></span>
																			</span>

																			<input name="card-number" id="card-number" class="cardNumber type form-control" placeholder="Card Number" required>
																		</div>
																		
																	</div>
																	<div class="col-md-6 mt-2">
																		<input type="text" name="exp-date" id="exp-date" class="expiry form-control" placeholder="Expired Date" required>
																		
																	</div>
																	<div class="col-md-6 mt-2">
																		<input  maxlength="4" name="cvv" id="cvv" class="cvv form-control" placeholder="CVV" maxlength="3" required>
																		
																	</div>
																	<div class="col-md-12 my-2">
																		<input type="text" name="card-holder" id="card-holder" class="form-control" placeholder="Card Holder" required>
																		
																	</div>
																</div>
																<script type="text/javascript">
																	new Cleave('.cardNumber', {
																		creditCard: true,
																		onCreditCardTypeChanged: function(type) {
																			document.querySelector('.type').innerHTML = '<i class="fa fa-cc-' + type + ' fa-fw fa-2x active" aria-hidden="true"></i>';
																		}
																	});


																	new Cleave('.expiry', {
																		date: true,
																		datePattern: ['m', 'y']
																	});


																</script>

																<!-- ACH -->


															</fieldset>
														</div>

													</div>

													<a href="javascript:void(0)" id="submitRecurring" class=" my-3 btn btn-success">
														SUBMIT
													</a>
												</fieldset>
											</form>


											<!-- Recurring Form End -->


										</div>
									</div>
								</div>
							</div>
							<input type="hidden" id="totalDonation" value="">

						</div>
					</div>
				</div>
			</div>
		</div>
	</section>
</main>

<!-- Live Client Id -->



<?php $this->load->view('includes/footer') ?>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
	var loader = new ldLoader({root: ".ldld.full"});
	if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
		
	}
	document.addEventListener("click", function(event) {
		if (event.target.matches(".navlink, .loader")) {
			
		}
	});
	window.onload = function() {
		
	};

	$(document).ready(function() {
		$('#inlineCheckbox2').on('click', function() {
        return false; // Prevent the checkbox from being clicked
      });
	});


	$(document).ready(function() {
		$(".payment-section").hide();

		$("#debitFequency").on("change", function() {
			$("#startDailyDate").val("");
			$("#endDailyDate").val("");
			$("#startWeeklyDate").val("");
			$("#endWeeklyDate").val("");
			$("#startMonthlyDate").val("");
			$("#endMonthlyDate").val("");
			$("#selectAnualyMonthValue").val("");
			$("#selectAnualyDateValue").val("");
			$("#startAnualyDate").val("");
			$("#endAnualyDate").val("");
			$("#cvv").val("");
			$("#card-number").val("");
			$("#exp-date").val("");
			$("#card-holder").val("");
			var selectedFrequency = $(this).val();
			$(".payment-section").hide(); 
			$("#" + selectedFrequency + "Section").show(); 
		});
	});



	document.getElementById("cvv").addEventListener("input", function(e) {
    // Get the input value and remove any non-numeric characters
		const cvvValue = this.value.replace(/\D/g, '');

    // Update the input field with the cleaned value
		this.value = cvvValue;
	});


	$( function() {
		var dateFormat = "mm/dd/yy",
		from = $( "#startDailyDate" )
		.datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			var selectedDate = getDate(this);
			if (selectedDate) {
				selectedDate.setDate(selectedDate.getDate() + 1);
				to.datepicker("option", "minDate", selectedDate);
			}
		}),
		to = $( "#endDailyDate" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			from.datepicker( "option", "maxDate", getDate( this ) );
		});

		function getDate( element ) {
			var date;
			try {
				date = $.datepicker.parseDate( dateFormat, element.value );
			} catch( error ) {
				date = null;
			}

			return date;
		}
	} );


	$( function() {
		var dateFormat = "mm/dd/yy",
		from = $( "#startWeeklyDate" )
		.datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			var selectedDate = getDate(this);
			if (selectedDate) {
				selectedDate.setDate(selectedDate.getDate() + 7);
				to.datepicker("option", "minDate", selectedDate);
			}
		}),
		to = $( "#endWeeklyDate" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			from.datepicker( "option", "maxDate", getDate( this ) );
		});

		function getDate( element ) {
			var date;
			try {
				date = $.datepicker.parseDate( dateFormat, element.value );
			} catch( error ) {
				date = null;
			}

			return date;
		}
	} );


	$( function() {
		var dateFormat = "mm/dd/yy",
		from = $( "#startMonthlyDate" )
		.datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			var selectedDate = getDate(this);
			if (selectedDate) {
				selectedDate.setMonth(selectedDate.getMonth() + 1); 
				to.datepicker("option", "minDate", selectedDate);
			}

		}),
		to = $( "#endMonthlyDate" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1
		})
		.on( "change", function() {
			from.datepicker( "option", "maxDate", getDate( this ) );
		});

		function getDate( element ) {
			var date;
			try {
				date = $.datepicker.parseDate( dateFormat, element.value );
			} catch( error ) {
				date = null;
			}

			return date;
		}
	} );







	$(function() {
		var monthSelect = $("#selectAnualyMonthValue");
		var daySelect = $("#selectAnualyDateValue");

		monthSelect.on("change", function() {
			var selectedMonth = parseInt(monthSelect.val());
			var daysInMonth = new Date(new Date().getFullYear(), selectedMonth, 0).getDate();

    // Populate the day dropdown based on the selected month
			daySelect.empty();
			daySelect.append($("<option>").val("").text("Select Date"));

			for (var i = 1; i <= daysInMonth; i++) {
				daySelect.append($("<option>").val(i).text(i));
			}
		});
	});





	$(function() {
  // Get references to the select boxes
		var fromYearSelect = $("#startAnualyDate");
		var toYearSelect = $("#endAnualyDate");

  // Populate the initial options for the start year
		var currentYear = new Date().getFullYear();
		for (var year = currentYear; year <= currentYear + 100; year++) {
			fromYearSelect.append(new Option(year, year));
		}

  // Update the options for the end year when the start year is changed
		fromYearSelect.on("change", function() {
    toYearSelect.empty(); // Clear the existing options
    var selectedStartYear = parseInt(fromYearSelect.val());

    // Populate the end year options starting from the selected start year
    for (var year = selectedStartYear+1; year <= selectedStartYear + 100; year++) {
    	toYearSelect.append(new Option(year, year));
    }
  });
	});




// 	$(document).ready(function() {
// 		$('#submitRecurring').click(function(event) {
//         event.preventDefault(); 

  
//         var totalAmount = parseFloat($("#total-price").text().replace('$', '').trim());
//         if (totalAmount <= 0) {
//         	alert("Please select a service for pledge.");
//         	return;
//         }

//         if (!isAnyItemChecked()) {
//             alert("Please select at least one item.");
//             return;
//         }


        

//         var debitFrequency = $("#debitFequency").val();
//         if (debitFrequency == null || debitFrequency.trim() === '') {
//         	alert("Please select a Debit Frequency.");
//         	return;
//         }

       
//         if (debitFrequency === "Daily") {
//             // Validation for the Daily section
//         	var startDailyDate = $("#startDailyDate").val();
//         	var endDailyDate = $("#endDailyDate").val();

//         	if (!startDailyDate || !endDailyDate) {
//         		alert("Please provide Start Date and End Date for Daily Payment Schedule.");
//         		return;
//         	}
//         } else if (debitFrequency === "Weekly") {
//             // Validation for the Weekly section
//         	var startWeeklyDate = $("#startWeeklyDate").val();
//         	var endWeeklyDate = $("#endWeeklyDate").val();
//         	var selectWeeklyDay = $("#selectWeeklyDay").val();

//         	if (!startWeeklyDate || !endWeeklyDate || selectWeeklyDay == null) {
//         		alert("Please provide Start Date, End Date, and select a Day for Weekly Payment Schedule.");
//         		return;
//         	}
//         } else if (debitFrequency === "Monthly") {
//             // Validation for the Monthly section
//         	var startMonthlyDate = $("#startMonthlyDate").val();
//         	var endMonthlyDate = $("#endMonthlyDate").val();
//         	var selectmonthDate = $("#selectmonthDate").val();

//         	if (!startMonthlyDate || !endMonthlyDate || selectmonthDate == null) {
//         		alert("Please provide Start Date, End Date, and select a Day of the Month for Monthly Payment Schedule.");
//         		return;
//         	}
//         } else if (debitFrequency === "Annually") {
//             // Validation for the Annually section
//         	var selectAnualyMonthValue = $("#selectAnualyMonthValue").val();
//         	var selectAnualyDateValue = $("#selectAnualyDateValue").val();
//         	var startAnualyDate = $("#startAnualyDate").val();
//         	var endAnualyDate = $("#endAnualyDate").val();

//         	if (selectAnualyMonthValue == null || selectAnualyDateValue == null || !startAnualyDate || !endAnualyDate) {
//         		alert("Please select a Month, a Date, and provide Start and End Years for Annually Payment Schedule.");
//         		return;
//         	}
//         }

        
//         var cardNumber = $("#card-number").val();
//         var expDate = $("#exp-date").val();
//         var cvv = $("#cvv").val();
//         var cardHolder = $("#card-holder").val();

//         if (!cardNumber || !expDate || !cvv || !cardHolder) {
//         	alert("Please provide all the required card details for Mode of Payment.");
//         	return;
//         }


//          CheckLoginOrNot('pledge_form');
      
     


//       });
// });

// function isAnyItemChecked() {
//     var checkboxes = document.getElementsByName('services_id[]');
//     return Array.from(checkboxes).some(checkbox => checkbox.checked);
// }

// function CheckLoginOrNot(page){

// 	    var serviceAmt = parseFloat($("#total-price").text().replace('$', '').trim());
//     if (serviceAmt > 0) {
     
//      var page_name = page;
//      event.preventDefault();
//      $.ajax({
//       url: "<?=base_url('check-login-status')?>",
//       type: "POST",
//       dataType: "json",
//       success: function(data) 
//       {
       
//        if (data == 0) {
//         openLoginModal(page_name);
//       }else{
//         if (page_name == 'pledge_form') {
//             submitRecurringForm();
//         }
//       }
//     }
//   });
//    }else{
//     swal({
//       title: "Your cart is empty!",
//       text: "Please add some items to your cart.",
//       icon: "warning",
//       confirmButtonText: 'OK',
//       confirmButtonColor: '#005D4B',
//     });
//   }
// }

// function submitRecurringForm() {
//     var formData = new FormData(document.getElementById('pledge-form'));

//     var serviceAmt = parseFloat($("#total-price").text().replace('$', '').trim());
//     formData.append("serviceAmt", serviceAmt);

//     $.ajax({
//         type: 'POST',
//         url: '<?=base_url('RecurringSponsorNow/SubmitRecurringSponsors')?>',
//         data: formData,
//         processData: false,  // Important! Don't process the form data
//         contentType: false,  // Important! Don't set contentType
//         success: function(response) {
//             var res = JSON.parse(response);
//             if (res.statusCode == 1) {
//                 swal({
//                         html: true,
//                         title: "Payment Successfully Processed!",
//                         text: res.message,
//                         type: "success",
//                         confirmButtonText: 'OK',
//                         confirmButtonColor: '#008080',
//                     },
//                     function() {
//                         window.location.reload();
//                     });
//             } else {
//                 swal({
//                         html: true,
//                         title: "Failed!",
//                         text: res.data.responseDescription,
//                         type: "error",
//                         confirmButtonText: 'OK',
//                         confirmButtonColor: '#008080',
//                     },
//                     function() {
//                         // window.location.reload(); 
//                     });
//             }
//         },
//         error: function(error) {
//             console.error(error);
//         }
//     });
// }


	$(document).ready(function() {
    $('#submitRecurring').click(function(event) {
        event.preventDefault();

        var totalAmount = parseFloat($("#total-price").text().replace('$', '').trim());
        if (totalAmount <= 0) {
            alert("Please select a service for pledge.");
            return;
        }

        if (!isAnyItemChecked()) {
            alert("Please select at least one item.");
            return;
        }

        var debitFrequency = $("#debitFequency").val();
        if (debitFrequency == null || debitFrequency.trim() === '') {
            alert("Please select a Debit Frequency.");
            return;
        }

        if (debitFrequency === "Daily") {
            // Validation for the Daily section
            var startDailyDate = $("#startDailyDate").val();
            var endDailyDate = $("#endDailyDate").val();

            if (!startDailyDate || !endDailyDate) {
                alert("Please provide Start Date and End Date for Daily Payment Schedule.");
                return;
            }
        } else if (debitFrequency === "Weekly") {
            // Validation for the Weekly section
            var startWeeklyDate = $("#startWeeklyDate").val();
            var endWeeklyDate = $("#endWeeklyDate").val();
            var selectWeeklyDay = $("#selectWeeklyDay").val();

            if (!startWeeklyDate || !endWeeklyDate || selectWeeklyDay == null) {
                alert("Please provide Start Date, End Date, and select a Day for Weekly Payment Schedule.");
                return;
            }
        } else if (debitFrequency === "Monthly") {
            // Validation for the Monthly section
            var startMonthlyDate = $("#startMonthlyDate").val();
            var endMonthlyDate = $("#endMonthlyDate").val();
            var selectmonthDate = $("#selectmonthDate").val();

            if (!startMonthlyDate || !endMonthlyDate || selectmonthDate == null) {
                alert("Please provide Start Date, End Date, and select a Day of the Month for Monthly Payment Schedule.");
                return;
            }
        } else if (debitFrequency === "Annually") {
            // Validation for the Annually section
            var selectAnualyMonthValue = $("#selectAnualyMonthValue").val();
            var selectAnualyDateValue = $("#selectAnualyDateValue").val();
            var startAnualyDate = $("#startAnualyDate").val();
            var endAnualyDate = $("#endAnualyDate").val();

            if (selectAnualyMonthValue == null || selectAnualyDateValue == null || !startAnualyDate || !endAnualyDate) {
                alert("Please select a Month, a Date, and provide Start and End Years for Annually Payment Schedule.");
                return;
            }
        }

        var cardNumber = $("#card-number").val();
        var expDate = $("#exp-date").val();
        var cvv = $("#cvv").val();
        var cardHolder = $("#card-holder").val();

        if (!cardNumber || !expDate || !cvv || !cardHolder) {
            alert("Please provide all the required card details for Mode of Payment.");
            return;
        }

        CheckLoginOrNot('pledge_form');
    });
});

function isAnyItemChecked() {
    var checkboxes = document.getElementsByName('services_id[]');
    return Array.from(checkboxes).some(checkbox => checkbox.checked);
}

function CheckLoginOrNot(page) {
    var serviceAmt = parseFloat($("#total-price").text().replace('$', '').trim());
    if (serviceAmt > 0) {
        var page_name = page;
        event.preventDefault();
        $.ajax({
            url: "<?=base_url('check-login-status')?>",
            type: "POST",
            dataType: "json",
            success: function(data) {
                if (data == 0) {
                    // User not logged in, open login modal
                    openLoginModal(page_name);
                } else {
                    // User is logged in, proceed with form submission
                    submitRecurringForm();
                }
            }
        });
    } else {
        swal({
            title: "Your cart is empty!",
            text: "Please add some items to your cart.",
            icon: "warning",
            confirmButtonText: 'OK',
            confirmButtonColor: '#005D4B',
        });
    }
}

function submitRecurringForm() {
    var formData = new FormData(document.getElementById('pledge-form'));

    var serviceAmt = parseFloat($("#total-price").text().replace('$', '').trim());
    formData.append("serviceAmt", serviceAmt);

    $.ajax({
        type: 'POST',
        url: '<?=base_url('PledgeForm/SubmitPledgeForm')?>',
        data: formData,
        processData: false, // Important! Don't process the form data
        contentType: false, // Important! Don't set contentType
        success: function(response) {
            var res = JSON.parse(response);
            if (res.statusCode == 1) {
                swal({
                        html: true,
                        title: "Payment Successfully Processed!",
                        text: res.message,
                        type: "success",
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#008080',
                    },
                    function() {
                        window.location.reload();
                    });
            } else {
                swal({
                        html: true,
                        title: "Failed!",
                        text: res.data.responseDescription,
                        type: "error",
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#008080',
                    },
                    function() {
                        // window.location.reload(); 
                    });
            }
        },
        error: function(error) {
            console.error(error);
        }
    });
}

function addTocartList() {
      // Get the element that will display the selected services and prices
	var cartList = document.getElementById('cartList');

      // Get the element to display the total price
	var totalPriceElement = document.getElementById('total-price');subttl
	var subttl = document.getElementById('subttl');
	var ttlItemsElement = document.getElementById('ttl_items');
	var pledgetotal = document.getElementById('pledgetotal');

      // Clear the existing content in the cart list and total price
	cartList.innerHTML = '';
	totalPriceElement.innerHTML = '';
	subttl.innerHTML = '';
	pledgetotal.innerHTML = '';
	 ttlItemsElement.innerHTML = '';

      // Get all checkboxes with the name 'services_id[]'
	var checkboxes = document.getElementsByName('services_id[]');

      // Initialize total price
	var totalPrice = 0;
	var itemCount = 0;

      // Loop through each checkbox
	checkboxes.forEach(function (checkbox) {
        // If the checkbox is checked, add its service and price to the cart list and update total price
		if (checkbox.checked) {
          // Get the data attributes from the checkbox
			var serviceName = checkbox.getAttribute('data-service-name');
			var servicePrice = parseFloat(checkbox.getAttribute('data-price'));

          // Create a new list item element
			var listItem = document.createElement('li');

          // Set the innerHTML of the list item with the service name and price
			listItem.innerHTML = `
			<span>${serviceName}</span>
			<span>$${servicePrice.toFixed(2)}</span>
			`;

          // Append the list item to the cart list
			cartList.appendChild(listItem);

          // Update total price
			totalPrice += servicePrice;

			itemCount++;
		}
	});

      // Display the total price with $ sign
	totalPriceElement.innerHTML = `$${totalPrice.toFixed(2)}`;
	subttl.innerHTML = `$${totalPrice.toFixed(2)}`;
	pledgetotal.innerHTML = `$${totalPrice.toFixed(2)}`;

	ttlItemsElement.innerHTML = `Pledge For (${itemCount} ${itemCount > 1 ? 'Items' : 'Item'})`;

	addTocart();

}





function addTocart()
{

	var totalPrice = 0;
	var sankalpam_data = [];
	var cart_type = 'PLEDGE FORM';
	var ids = [];
	var qty = [];
	var ctg = [];
	var serviceTypes = [];
	var serviceName = [];
	var startDate = [];
	var startTime = [];
	var serviceAmount = [];
	var description = [];
	var image = [];
	var cart_ctg = [];

	$('input[name="services_id[]"]:checked').each(function() {
		id = $(this).attr('data-id');

		


		totalPrice = parseFloat(totalPrice)+(parseFloat($(this).attr('data-price')));



		ctg.push($(this).attr('data-category')); 
		serviceTypes.push($(this).attr('data-service-type')); 
		serviceName.push($(this).attr('data-service-name')); 
		image.push($(this).attr('data-image'));




		description.push($(this).attr('data-description')); 
		cart_ctg.push($(this).attr('cart_category')); 
		serviceAmount.push($(this).attr('data-price')); 
		ids.push($(this).attr('data-id')); 
	});




	$.ajax({
		type: "POST", 
		url: "<?= base_url('PledgeForm/addCart'); ?>", 
		dataType: 'json',
		data: {ids: ids, totalPrice:totalPrice, ctg: ctg, serviceTypes: serviceTypes, serviceName: serviceName, serviceAmount: serviceAmount, cart_type: cart_type, image: image, description: description, cart_ctg: cart_ctg}, 
		success: function(result){
			console.log(result);

			

		}});
}



</script>

<?php $this->load->view('includes/script') ?>



<!-- ==========Language Translator Code============= -->
<a href="#" class="back-to-top d-flex align-items-center justify-content-center" style="background-color:var(--headerFooter)!important;"><i class="bi bi-arrow-up-short"></i></a>


<!-- Vendor JS Files -->
<script src="<?=base_url('assets/vendor/aos/aos.js');?>"></script>
<script src="<?=base_url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js');?>"></script>
<script src="<?=base_url('assets/vendor/glightbox/js/glightbox.min.js');?>"></script>
<script src="<?=base_url('assets/vendor/swiper/swiper-bundle.min.js');?>"></script>

<!-- Template Main JS File -->
<script src="<?=base_url('assets/js/main.js');?>"></script>
<div class="ldld full" style="    z-index: 999;"></div>
