<?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/services_checkout.css'); ?>">
<?php

$isIncludeSankalpam = @$this->session->userdata('service_cart')['includeSankalpam'];
$isIncludeSankalpam_result = @checkForYesValue($isIncludeSankalpam);


$userDetails->noSpouse = !isset($userDetails->noSpouse) ? '' : $userDetails->noSpouse;
$userDetails->noFamily = !isset($userDetails->noFamily) ? '' : $userDetails->noFamily;

$parts = explode(" ", @$userDetails->refDataName);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);

if (empty($firstname)) {
  $firstname = $lastname;
  $lastname = "";
}

$current_user = getUserDetails()->data[0];
$fgh = getFullPaymentSettings();


$dsbj = $fgh['result']['data'][0]['paymentGatewayoffon'];

foreach ($dsbj as $key => $dd) {
  if ($dd['source'] == 'WEBSITE') {
    $paymentSeverOn = $dd['isenable'];
    $paymentSeverText = $dd['desc'];
  }
}



$paymentSetting = @getPaymentGatewaySettings();

$getclientInfoById = @getclientInfoById()['data'][0];

$CAW_MerchantId = @$getclientInfoById['ChargeAnywhereMerchantId'] ;
$CAW_TerminalId = @$getclientInfoById['ChargeAnywhereTerminalId'] ;

?>
<main id="main" style="background-image: url(<?= base_url('assets/img/elegant-background-with-mandala.png'); ?>);background-size: auto;">

  <style type="text/css">
    #pageContainer{
      padding: 0px;
    }
    #headerContainer{
      margin: 0px;
      padding: 0px;
    }
    #headerContent{
      height: 0px;
    }
  </style>

  <section style="background-image: linear-gradient(var(--page-wrapper-bg-color), white);">
    <center>
      <h2 class="bottomborder" style="font-weight:bold!important;font-size: 35px!important;">CHECKOUT</h2>
    </center><br>

    <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="<?= $session_data == 'sponsor_cart' ? base_url('puja-sponsorship') : ($session_data == 'service_cart' ? base_url('services') : base_url()) ?>" class="btn" style=";background-color:#009688;color: white!important;border-radius: 1px!important;">Close X</a>
              </div>

              <?php
              $currencySymbol = getCurrencySymbol();


              if (isset($this->session->userdata($session_data)['ids'])) { ?>

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

                    <div class="p-2">
                      <?php $cart_items = $this->session->userdata($session_data); ?>


                      <!-- Sankalpam Form Start-->
                      <?php if ($isIncludeSankalpam_result == 'YES') { ?>

                        <input type="hidden" name="family_members_data">
                        <input type="hidden" name="nakshtra_data">

                        <h4 class="text-center" style="color:#009688">Family Sankalpam Information</h4>
                        <h6 class="text-center mb-3">Please Complete Sponsorship Sankalpam Details</h6>
                        <!-- Sankalpam Form Start-->
                        <form id="sankalpamForm">
                          <fieldset class="border-2 shadow bg-white p-0">
                            <!-- <legend  class="legend-outer  float-none w-auto"> Sankalpam Details </legend> -->

                            <div class="row">

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

                                  <div class="input-group">
                                    <i class="fa fa-user"></i>
                                    <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name" value="<?= set_value('fname', @$firstname) ?>" required aria-label="fname" aria-describedby="basic-addon1">
                                  </div>
                                </fieldset>
                              </div>
                              <div class="col-md-6">
                                <fieldset class="border">
                                  <legend class="legend-inner float-none w-auto">Last Name<span class="text-danger fw-bold" style="font-size: 20px;">*</span></legend>
                                  <div class="input-group">
                                    <i class="fa fa-user"></i>
                                    <input type="text" class="form-control" id="lname" name="lname" value="<?= set_value('lname', @$lastname) ?>" placeholder="Last Name" aria-label="lname" required aria-describedby="basic-addon1">
                                  </div>
                                </fieldset>

                              </div>
                            </div>

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

                                  <div class="input-group">


                                    <input type="text" class="form-control" id="gothram" name="gothram" value="<?= set_value('gothram', @replaceSingleQuotesWithBackticks($userDetails->gotraName)) ?>" placeholder="Gothram" aria-label="gothram" aria-describedby="basic-addon1">
                                  </div>
                                </fieldset>

                              </div>


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

                                    <select id="stars" name="stars" style="color:black!important;" class="form-control rounded  form-select">
                                      <option value=" " selected disabled>Select Nakshtra</option>
                                      <?php foreach ($nakshtra_data as $item) { ?>
                                        <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->Nakshtra) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>
                                      <?php } ?>
                                    </select>
                                  </div>
                                </fieldset>
                              </div>
                            </div>

                            <div class="form-check form-check-inline" style="padding-bottom: 5px;">
                              <input class="form-check-input" type="checkbox" id="No_Spouse" name="No_Spouse" style="margin: 0;" value="<?= @$userDetails->noSpouse == true ? 'checked' : ''; ?>">
                              <label class="form-check-label m-auto pt-2" for="No_Spouse">No Spouse</label>
                            </div>

                            <div class="row spouseSection">
                              <div class="col-md-6">
                                <fieldset class="border">
                                  <legend class="legend-inner float-none w-auto">Spouse Name</legend>
                                  <div class="input-group">
                                    <input type="text" class="form-control" id="spouseName" name="spouseName" placeholder="Spouse Name" value="<?= set_value('spouseName', @$userDetails->spouseName) ?>" aria-label="spouseName">
                                  </div>
                                </fieldset>

                              </div>

                              <div class="col-md-6">
                                <fieldset class="border">
                                  <legend class="legend-inner float-none w-auto">Spouse Nakshatra</legend>
                                  <div class="input-group">

                                    <select id="spouseStars" name="spouseStars" style="color:black!important;" class="form-control rounded  form-select">
                                      <option value=" " selected disabled>Select Nakshtra</option>
                                      <?php foreach ($nakshtra_data as $item) { ?>
                                        <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->spouseNakshtra) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>
                                      <?php } ?>
                                    </select>
                                  </div>
                                </fieldset>
                              </div>
                            </div>
                            <div class="row">


                              <div class="form-check form-check-inline" style="padding-bottom: 5px;">
                                <input class="form-check-input" type="checkbox" id="No_Family_Member" name="No_Family_Member" style="margin: 0;" value="<?= @$userDetails->noFamily == true ? 'checked' : ''; ?>">
                                <label class="form-check-label m-auto pt-2" for="No_Family_Member">No Family Member</label>
                              </div>


                              <?php if (empty(@$userDetails->memberDetail) || @$userDetails->memberDetail[0]->memberName == '') { ?>

                                <div class="row customer_records px-0 familyMemberSection">
                                  <div class="col-md-4">
                                    <fieldset class="border">
                                      <legend class="legend-inner float-none w-auto">Family Member</legend>
                                      <div class="input-group">
                                        <input type="text" class="form-control" id="familyMember" name="family_member[]" placeholder="Family Member Name" aria-label="family_member">
                                      </div>
                                    </fieldset>
                                  </div>


                                  <div class="col-md-4">
                                    <fieldset class="border">
                                      <legend class="legend-inner float-none w-auto">Nakshtra</legend>
                                      <div class="input-group">


                                        <select id="nakshtra" name="nakshtra[]" style="color:black!important;" class="form-control rounded  form-select">
                                          <option value=" " selected disabled>Select Nakshtra</option>
                                          <?php foreach ($nakshtra_data as $item) { ?>
                                            <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->memberDetail[0]->nakshatra) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>
                                          <?php } ?>
                                        </select>
                                      </div>
                                    </fieldset>
                                  </div>




                                  <div class="col-md-4 py-4">

                                    <a class="extra-fields-customer btn btn-success btn-sm" style="border-radius:5px!important" href="#">Add More</a>



                                  </div>
                                </div>




                              <?php } else {

                                foreach (@$userDetails->memberDetail as $key => $val) {

                                  ?>



                                  <div class="row customer_records px-0 familyMemberSection">
                                    <div class="col-md-4">
                                      <fieldset class="border">
                                        <legend class="legend-inner float-none w-auto">Family Member</legend>
                                        <div class="input-group">
                                          <input type="text" class="form-control" id="familyMember" name="family_member[]" placeholder="Family Member Name" value="<?= set_value('family_member', @$val->memberName) ?>" aria-label="family_member">
                                        </div>
                                      </fieldset>
                                    </div>


                                    <div class="col-md-4">
                                      <fieldset class="border">
                                        <legend class="legend-inner float-none w-auto">Nakshtra</legend>
                                        <div class="input-group">
                                          <select id="nakshtra" name="nakshtra[]" style="color:black!important;" class="form-control rounded  form-select">
                                            <option value=" " selected disabled>Select Nakshtra</option>
                                            <?php foreach ($nakshtra_data as $item) { ?>
                                              <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($userDetails->memberDetail[$key]->nakshatra) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>
                                            <?php } ?>
                                          </select>
                                        </div>
                                      </fieldset>


                                      <!-- Hidden Input Fields -->




                                      <input name="dob[]" id="dob" type="text" class="form-control datepicker" placeholder="MM/DD/YYYY" aria-label="dateofbirth" aria-describedby="basic-addon1" value="<?= set_value('dob', @$val->dob); ?>" hidden>

                                      <select name="rashi[]" id="rashi" style="color:black!important;" class="form-control rounded  form-select" hidden>
                                        <option value=" " selected disabled>Select Rashi</option>
                                        <?php foreach ($rashi_data as $item) { ?>
                                          <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>" <?= @replaceSingleQuotesWithBackticks($item['refDataName']) == @replaceSingleQuotesWithBackticks($val->rashi) ? 'selected' : '' ?>><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option>
                                        <?php } ?>
                                      </select>

                                      <select class="form-control rounded form-select" name="relationship[]" hidden>
                                        <option value=" " selected>Select</option>
                                        <option value="FATHER" <?= @$val->relationship == 'FATHER' ? 'selected' : '' ?>>FATHER</option>
                                        <option value="MOTHER" <?= @$val->relationship == 'MOTHER' ? 'selected' : '' ?>>MOTHER</option>
                                        <option value="SPOUSE" <?= @$val->relationship == 'SPOUSE' ? 'selected' : '' ?>>SPOUSE</option>
                                        <option value="SON" <?= @$val->relationship == 'SON' ? 'selected' : '' ?>>SON</option>
                                        <option value="DAUGHTER" <?= @$val->relationship == 'DAUGHTER' ? 'selected' : '' ?>>DAUGHTER</option>
                                      </select>

                                      <input name="anniversaryDate[]" id="anniversary" type="text" class="form-control datepicker" placeholder="MM/DD/YYYY" aria-label="anniversary" aria-describedby="basic-addon1" value="<?= set_value('anniversary', @$val->anniversaryDate); ?>" hidden>

                                      <!-- Hidden Input Fields -->

                                    </div>


                                    <?php if ($key == 0) { ?>
                                      <div class="col-md-4 py-4">

                                        <a class="extra-fields-customer btn btn-success btn-sm" style="border-radius:5px!important" href="#">Add More</a>



                                      </div>

                                    <?php } else { ?>

                                      <div class="col-md-4 py-4"><a href="#" style="border-radius:5px!important" class="remove-field btn-remove-customer btn btn-danger btn-sm">Remove</a></div>

                                    <?php } ?>
                                  </div>


                                <?php }
                              } ?>
                              <div class="customer_records_dynamic px-0"></div>
                            </div>
                          </fieldset>
                        </form>
                        <script type="text/javascript">
                          var count = 1;

                          $('.extra-fields-customer').click(function(e) {
                            e.preventDefault();

                            var newCustomerFields = '<div class="row customer_records">';
                            newCustomerFields += '<div class="col-md-4"> <fieldset class="border"> <legend class="legend-inner float-none w-auto">Family Member</legend> <div class="input-group"> <input type="text" class="form-control" id="familyMember" name="family_member[]" placeholder="Family Member Name"  aria-label="family_member"> </div> </fieldset> </div>';
                            newCustomerFields += '<div class="col-md-4"> <fieldset class="border"> <legend class="legend-inner float-none w-auto">Nakshtra</legend> <div class="input-group"> <select id="nakshtra" name="nakshtra[]" style="color:black!important;" class="form-control rounded  form-select"> <option value=" " selected disabled>Select Nakshtra</option> <?php foreach ($nakshtra_data as $item) { ?> <option value="<?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?>"><?= @replaceSingleQuotesWithBackticks($item['refDataName']); ?></option> <?php } ?> </select> </div> </fieldset> </div>';
                            newCustomerFields += '<div class="col-md-4 py-4"><a href="#" style="border-radius:5px!important" class="remove-field btn-remove-customer btn btn-danger btn-sm">Remove</a></div>';
                            newCustomerFields += '</div>';

                            $('.customer_records_dynamic').append(newCustomerFields);
                          });

                          $(document).on('click', '.remove-field', function(e) {
                            e.preventDefault();
                            $(this).closest('.row.customer_records').remove();
                          });
                        </script>

                      <?php } ?>


                      <!-- Sankalapam Form End -->


                      <div class="d-flex justify-content-between align-items-center mb-5">


                        <h3 class="fw-bold mb-0 text-black">Sale Summary</h3>

                        <h6 class="mb-0 text-muted"><?= count($this->session->userdata($session_data)['ids']); ?> items</h6>
                      </div>
                      <hr class="my-4">


                      <!-- ============================================= -->
                      <div class="table-responsive">
                        <table class="table">
                          <thead>
                            <tr>
                              <th style="width:50%" class="text-start">Service Name</th>
                              <!-- <th style="width:25%" class="text-start">Category</th> -->
                              <th style="width:15%" class="text-center">Date</th>
                              <th style="width:5%" class="text-center">Qty</th>
                              <th style="width:15%" class="text-end">Amount</th>
                              <th style="width:15%" class="text-center">Pay Now</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php
                            $payNowTotalAmount = 0;

                            $s_total = 0;
                            foreach ($cart_items['ids'] as $key => $value) {


                              if ($cart_items['serviceAmount'][$key] > 0) {
                                $payNowTotalAmount = ($cart_items['serviceAmount'][$key] * $cart_items['qty'][$key]) + $payNowTotalAmount;
                              }
                              $selectedCartDats = array();
                              if (!empty($cart_items['startDate'][$key])) {
                                $selectedCartDats = explode(',', $cart_items['startDate'][$key]);

                                foreach ($selectedCartDats as $dateKey => $selectedCatVal) {



                                 $discounted_price = '';



                                 if (@$userDetails->isMember == 1 && @$userDetails->membershipStatus == 'ACTIVE' && @$cart_items['is_membership_discount'][$key] == 'YES') {

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

                                   if ($discountType == 'FLAT') {

                                    if ($cart_items['serviceAmount'][$key] > $membershipDiscount) {

                                      $discounted_price = $cart_items['serviceAmount'][$key] - $membershipDiscount;

                                    }

                                  }else{

                                    $discounted_price = $cart_items['serviceAmount'][$key] - ($cart_items['serviceAmount'][$key] * $membershipDiscount) / 100;

                                  }
                                }


                                ?>
                                <tr class="servicesTr">
                                  <td class="text-start">


                                    <?= $cart_items['serviceName'][$key] . ' (' . $currencySymbol . ' ' . price_format($cart_items['serviceAmount'][$key], 2) . ')'; ?>


                                      <td class="text-start"><?= $selectedCatVal; ?></td>
                                      <td class="text-center"><?= $cart_items['qty'][$key]; ?></td>
                                      <td class="text-end" id="amount_<?= $cart_items['ids'][$key]; ?>">

                                        <?php  
                                        $final_price = $discounted_price ? $discounted_price : $cart_items['serviceAmount'][$key]; 


                                        $s_total += $final_price;
                                        ?>

                                        <?php if ($discounted_price != '') { ?>

                                          <?= $cart_items['bookingtype'][$key] == 'PAY LATER' ? '$ 0.00' : '<span style="text-decoration: line-through;">' . $currencySymbol . '&nbsp;' . price_format($cart_items['serviceAmount'][$key], 2) . '</span>'; ?>

                                          <?= $cart_items['bookingtype'][$key] == 'PAY LATER' ? '$ 0.00' : '<span style="font-weight: bold;font-size: larger;color: #b00000;">' . $currencySymbol . '&nbsp;' . price_format($final_price , 2) . '</span>'; ?>

                                        <?php }else{ ?> 

                                          <?= $cart_items['bookingtype'][$key] == 'PAY LATER' ? '$ 0.00' : '<span>' . $currencySymbol . '&nbsp;' . price_format($cart_items['serviceAmount'][$key], 2) . '</span>'; ?>

                                        <?php } ?>


                                      </td>


                                      <td class="text-end">

                                        <select id="<?= $cart_items['ids'][$key]; ?>" data-booking-type="<?= $cart_items['bookingtype'][$key] ?>" <?= $cart_items['bookingtype'][$key] == 'PAY NOW' || $cart_items['bookingtype'][$key] == 'PAY LATER' ? 'class="form-control is_paynow" readonly disabled style="-webkit-appearance: none!important; -moz-appearance: none!important; text-indent: 1px!important; outline: none!important; border: 1px dotted #000!important; border-radius: 7px!important; padding: 3px 5px!important; text-align: center!important;background:#DBDBDB!important"' : 'class="form-control form-select is_paynow"'; ?>>

                                          <option value="<?= $cart_items['serviceAmount'][$key] ?>" real-value="<?= $cart_items['serviceAmount'][$key]; ?>" <?= $cart_items['bookingtype'][$key] == 'PAY NOW' ?  'selected' : ''; ?>> YES</option>




                                          <option value="0.00" real-value="<?= $cart_items['serviceAmount'][$key]; ?>" <?= $cart_items['bookingtype'][$key] == 'PAY LATER' ?  'selected' : ''; ?>> NO</option>

                                        </select>

                                      </td>
                                    </tr>
                                  <?php } } else { ?>
                                    <tr class="servicesTr">
                                      <td class="text-start"><?= $cart_items['serviceName'][$key] . ' (' . $currencySymbol . ' ' . price_format($cart_items['serviceAmount'][$key], 2) . ')'; ?></td>
                                      <td class="text-center">Not Selected</td>
                                      <td class="text-center"><?= $cart_items['qty'][$key]; ?></td>
                                      <td class="text-end" id="amount_<?= $cart_items['ids'][$key]; ?>"><?= $currencySymbol . '&nbsp;' . price_format($cart_items['serviceAmount'][$key], 2); ?></td>


                                      <td class="text-end">

                                        <select id="<?= $cart_items['ids'][$key]; ?>" class="form-control is_paynow" data-booking-type="<?= $cart_items['bookingtype'][$key] ?>" <?= $cart_items['bookingtype'][$key] == 'PAY NOW' || $cart_items['bookingtype'][$key] == 'PAY LATER' ? 'readonly disabled style="-webkit-appearance: none!important; -moz-appearance: none!important; text-indent: 1px!important; outline: none!important; border: 1px dotted #000!important; border-radius: 7px!important; padding: 3px 5px!important; text-align: center!important;background:#DBDBDB!important"' : 'class="form-control is_paynow form-select"'; ?>>

                                          <option value="<?= $cart_items['serviceAmount'][$key] ?>" real-value="<?= $cart_items['serviceAmount'][$key]; ?>" <?= $cart_items['bookingtype'][$key] == 'PAY NOW' ?  'selected' : ''; ?>> YES</option>

                                          <option value="0.00" real-value="<?= $cart_items['serviceAmount'][$key]; ?>" <?= $cart_items['bookingtype'][$key] == 'PAY LATER' ?  'selected' : ''; ?>> NO</option>

                                        </select>

                                      </td>



                                    </tr>

                                  <?php }
                                } ?>
                              </tbody>
                            </table>
                          </div>

                          <!-- ============================================= -->

                          <hr class="my-4">
                          <?php if (@CheckEmptyNullVar($GeneralSettings['TaxPercent']) != '' && @$GeneralSettings['TaxPercent'] > 0) { ?>

                            <div class="row mt-3">
                              <div class="col-md-10">
                                <h5 class="mb-0" style="font-weight:bold!important;">Tax (<?= @$GeneralSettings['TaxPercent'] != '' || @$GeneralSettings['TaxPercent'] != 0 ?  @$GeneralSettings['TaxPercent'] : 0 ?>%)</h5>
                              </div>
                              <div class="col-md-2 text-end"><span style="font-weight:bold!important;"><?= $currencySymbol ?> <?= (price_format($cart_items['totalPrice'], 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100; ?></span></div>

                              <?php $taxAmt = (price_format($s_total, 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100; ?>
                            </div>

                            <hr class="my-4">
                          <?php } else {
                            $taxAmt = 0;
                          } ?>

                          <div class="row mt-3">
                            <div class="col-md-6">
                              <h5 class="mb-0" style="font-weight:bold!important;">Subtotal</h5>
                            </div>

                            <div class="col-md-6 text-end">

                              <?php if ($payNowTotalAmount > $s_total) { ?>

                              <span style="font-weight:bold!important;text-decoration: line-through;" id="subtle"><?= $currencySymbol ?>&nbsp;<?= price_format( $payNowTotalAmount, 2); ?></span>
                              <span style="font-weight:bold!important;font-size: 22px!important;color: #b00000;" id="subtle"><?= $currencySymbol ?>&nbsp;<?= price_format( $s_total, 2); ?></span>
                               
                             <?php }else{ ?> 

                              <span style="font-weight:bold!important;" id="subtle"><?= $currencySymbol ?>&nbsp;<?= price_format( $s_total, 2); ?></span>


                             <?php } ?>
                            </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;">Sale 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="saletle"><?= $currencySymbol ?>&nbsp;<?= price_format(( $s_total + @$taxAmt), 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">

                        <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
                          <div class="row p-3" style="background-color:#dbdbdb">
                            <div class="col-md-9">
                              <h6 class="fw-bold" style="margin-top:auto;margin-bottom:auto;">Acharya Sambhavana (<?= $currencySymbol ?>)</h6>
                            </div>
                            <div class="col-md-3 text-end">
                              <input type="number" name="acharya_sambhavana" placeholder="<?= $currencySymbol ?> 0.00" class="form-control form-control-sm" id="acharya-sambhavana-input">
                            </div>

                          </div>
                        <?php } ?>

                        <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
                          <div class="row p-3" style="background-color:#dbdbdb">
                            <div class="col-md-9">
                              <h6 class="fw-bold" style="margin-top:auto;margin-bottom:auto;">General Donation Amount (<?= $currencySymbol ?>)</h6>
                            </div>
                            <div class="col-md-3 text-end">
                              <input type="number" name="general_donation" placeholder="<?= $currencySymbol ?> 0.00" class="form-control form-control-sm" id="general-donation-input">
                            </div>

                          </div>
                          <hr class="my-4">
                        <?php } ?>
                        <?php
                        $subTotal =  price_format(((($cart_items['totalPrice'] * @($GeneralSettings['TaxPercent'] ? $GeneralSettings['TaxPercent'] : 0)) / 100) +  $cart_items['totalPrice']), 2);
                        $this->session->set_userdata('totalPrice', $subTotal);
                        $newSubTotal = $this->session->userdata('totalPrice');
                        ?>
                        <?php if (@CheckEmptyNullVar($GeneralSettings['TaxPercent']) != '' && @$GeneralSettings['TaxPercent'] > 0) {
                          $payNowTotalAmount = (price_format($payNowTotalAmount, 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100;
                        } ?>
                        <div class="text-center my-3">

                          <!-- <?= $s_total;?> -->

                          <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 mt-0" style="border: 2px solid #dbdbdb;border-radius: 9px;padding: 3px;font-size: 25px;" id="total-price"><?= $currencySymbol ?>&nbsp;<?= price_format($s_total, 2); ?></h3>
                          </div>


                          <?php if ($paymentSeverOn == 1) { ?>




                            <?php


                            if (isset($paymentSetting) && $paymentSetting == 'MPI') { ?>


                              <link rel="stylesheet" type="text/css" href="<?= base_url('assets/css/mpi.css'); ?>">
                              <form id="paymentForm" action="https://www.bridgepaynetsecuretx.com/WebSecurity/echo.aspx" method="post" style=" max-width: 500px;margin: auto;">
                                <div class="row px-0">
                                  <div class="col-md-12 px-0">
                                    <h6 class="text-center">Card Details</h6>
                                    <div id="card" class="mx-0" style="width: 100%!important;height: 150px;"></div>
                                    <div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
                                  </div>
                                  <div class="col-md-12 px-0">
                                    <h6 class="text-center">Billing Address</h6>
                                    <input type="text" class="form-control" id="fname" name="firstname" placeholder="Enter Your Full Name*" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->refDataName; ?>">
                                    <input type="email" id="email" class="form-control" name="email" placeholder="Enter Your Email Address" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= base64_decode(@$current_user->email); ?>">
                                    <input type="text" class="form-control" id="address" name="address" placeholder="Enter Your Street Address" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->addressLine1; ?>">

                                    <input type="number" class="form-control" id="zipcode" name="zipcode" placeholder="Enter Your Zipcode" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->zip; ?>">

                                    <div class="row m-0 p-0">
                                      <div class="col-md-12 px-0">
                                        <input type="text" id="state" name="state" placeholder="State*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->stateTypes; ?>">
                                      </div>
                                      <div class="col-md-12 px-0">
                                        <input type="text" id="city" name="city" placeholder="City*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->cityTypes; ?>">
                                      </div>
                                    </div>

                                    <center>
                                      <button type="submit" class="btn btn-success" style="max-width: 500px;margin: auto;border-radius: 4px!important;font-weight: 800;padding: 8px 24px;background: #e78b00;border: 0;text-shadow: 1px 1px 0px black;">PAY NOW</button>
                                    </center>
                                  </div>
                                </div>

                              </form>

                            <?php } else if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE') { ?>


                              <iframe id="paymentIframe" title="Payment Page" width="100%" height="600px"></iframe>
                            <?php } else { ?>

                              <?php if ((isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'YES')) { ?>

                                <?php if ($payNowTotalAmount > 0) { ?>
                                  <div id="error-alert"></div>

                                  <?php if ($paymentSeverOn == 1) { ?>
                                    <div id="paypal-button-container"></div>
                                  <?php } else { ?>
                                    <span class="alert mt-5 alert-danger text-center fw-bold"><i class="fa fa-warning fw-bold"></i> <?= $paymentSeverText; ?></span>
                                  <?php } ?>
                                <?php } else { ?>
                                  <a href="javascript:void(0)" class="btn btn-success booknow-btn" onclick="BookNow()">BOOK NOW</a>
                                <?php  } ?>

                              <?php } else if (isset($GeneralSettings['isMultipleSelect']) && $GeneralSettings['isMultipleSelect'] == 'NO') { ?>
                                <a href="javascript:void(0)" class="btn btn-success booknow-btn" onclick="BookNow()">

                                  <?php if ((isset($GeneralSettings['payLetterText']) && $GeneralSettings['payLetterText'] != ''  && $GeneralSettings['payLetterText'] != 'null')) {
                                    echo $GeneralSettings['payLetterText'];
                                  } else {
                                    echo 'BOOK NOW';
                                  } ?>
                                </a>
                              <?php } else { ?>
                                <a href="javascript:void(0)" class="btn btn-success booknow-btn" onclick="BookNow()">
                                  <?php if ((isset($GeneralSettings['payLetterText']) && $GeneralSettings['payLetterText'] != ''  && $GeneralSettings['payLetterText'] != 'null')) {
                                    echo $GeneralSettings['payLetterText'];
                                  } else {
                                    echo 'BOOK NOW';
                                  } ?>
                                </a>
                              <?php } ?>

                            <?php } ?>

                          <?php } else { ?>

                            <span class="alert mt-5 alert-danger text-center fw-bold"><i class="fa fa-warning fw-bold"></i> <?= $paymentSeverText; ?></span>

                          <?php } ?>

                        </div>
                      </div>
                    </div>
                  </div>
                <?php } else { ?>

                  <div class="text-center  my-5">
                    <h3 class="text-danger text-center fw-bold mb-5">Your Cart is empty!</h3>
                    <a href="<?= base_url('services') ?>" class='btn text-center btn-primary btn-sm checkoutbtn' style='background: #910301; border: 1px solid yellow;'>Go to services</a>
                  </div>
                <?php } ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>


 
  <!-- Live Client Id -->


  <?php if ($paymentSeverOn == 1 && $paymentSetting == 'PAYPAL') { ?>
    <?php $paypalLiveClientId  = @$getclientInfoById['paypalClientId'];

    ?>
    <script src="https://www.paypal.com/sdk/js?client-id=<?= @$paypalLiveClientId ?>&enable-funding=venmo&intent=capture" data-sdk-integration-source="integrationbuilder"></script>
  <?php } ?>


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

  <script type="text/javascript">
    var loader = new ldLoader({
      root: ".ldld.full"
    });


    if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
      loader.on();
    }
    document.addEventListener("click", function(event) {

      if (event.target.matches(".navlink, .loader")) {
        loader.on();
      }
    });

    window.onload = function() {
      loader.off();
    };
  </script>


  <?php if ($paymentSeverOn == 1 && $paymentSetting == 'PAYPAL') { ?>
    <script type="text/javascript">
      <?php if ($isIncludeSankalpam_result == 'YES') { ?>
        $(document).ready(function() {
          var isNoSpouseChecked = '<?= @$userDetails->noSpouse ?>';

          if (isNoSpouseChecked == 'true') {
            $("#No_Spouse").prop("checked", true);
            $(".spouseSection").hide();
          } else {
            $("#No_Spouse").prop("checked", false);
            $(".spouseSection").show();
            var isNoFamilyChecked = '<?= @$userDetails->noFamily ?>';

            if (isNoFamilyChecked == 'true') {
              $("#No_Family_Member").prop("checked", true);
              $(".familyMemberSection").hide();
            } else {
              $("#No_Family_Member").prop("checked", false);
              $(".familyMemberSection").show();
            }

          }
        });




        $(document).ready(function() {
          $("#No_Family_Member").change(function() {
            if ($(this).is(":checked")) {
              $(".familyMemberSection").hide();
              $("#No_Family_Member").val('checked');
            } else {
              $(".familyMemberSection").show();
              $("#No_Family_Member").val('');
            }
          });
        });


        $(document).ready(function() {
          $("#No_Spouse").change(function() {
            if ($(this).is(":checked")) {
              $(".spouseSection").hide();
              $("#No_Spouse").val('checked');
            } else {
              $(".spouseSection").show();
              $("#No_Spouse").val('');
            }
          });
        });



        $(document).ready(function() {
        // Initially hide the PayPal button container
          $("#paypal-button-container").hide();

        // Function to check if the form is filled
          function isFormFilled() {
            var fname = $("#fname").val();
            var lname = $("#lname").val();
            var gothram = $("#gothram").val();
            var stars = $("#stars").val();
            var spouseName = $("#spouseName").val();
            var spouseStars = $("#spouseStars").val();
            var familyMember = $("#familyMember").val();
            var nakshtra = $("#nakshtra").val();
            var No_Family_Member = $("#No_Family_Member").is(":checked");
            var No_Spouse = $("#No_Spouse").is(":checked");

          // Check conditions based on checkbox states
            if (No_Family_Member && No_Spouse) {
              return fname && lname && gothram;
            } else if (No_Family_Member) {
              return fname && lname && gothram && spouseName
            } else if (No_Spouse) {
              return fname && lname && gothram && familyMember
            } else {
              return fname && lname && gothram && spouseName && familyMember;
            }
          }

          function updatePayPalButtonVisibility() {
            if (isFormFilled()) {
              $("#paypal-button-container").show();
              $("#error-alert").html('');
            } else {
              $("#paypal-button-container").hide();
              $("#error-alert").html('<div class="alert alert-danger d-flex align-items-center" role="alert"> <i class="fa fa-warning"></i> <div> Please fill all required fields then the PayPal button will be automatically displayed. </div> </div>');
            }
          }
          $("#No_Family_Member, #No_Spouse").change(function() {
            updatePayPalButtonVisibility();
          });
          $("#sankalpamForm input, #sankalpamForm select").on("input", function() {
            updatePayPalButtonVisibility();
          });
          window.onload = function() {
            updatePayPalButtonVisibility();
          };
        });

      <?php } ?>






      $(document).ready(function() {
        var $totalPrice = $('#total-price');


        <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
          var $acharyaInput = $('#acharya-sambhavana-input');
          $acharyaInput.on('input', updateTotalPrice);
        <?php } ?>

        <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
          var $generalInput = $('#general-donation-input');
          $generalInput.on('input', updateTotalPrice);
        <?php } ?>



      // Function to update the total price based on the input values
        function updateTotalPrice() {
        // Get the input values
          var acharyaValue = 0;
          var generalValue = 0;
          <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
            var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
          <?php } ?>
          <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
            var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
          <?php } ?>



        // Get the initial total price
          var initialTotalPrice = parseFloat(<?= @$payNowTotalAmount; ?>) || 0;

        // Calculate the new total price
          var newTotalPrice = initialTotalPrice + acharyaValue + generalValue;

        // Update the total price element
          $totalPrice.text('<?= $currencySymbol ?> ' + newTotalPrice.toFixed(2));
        }

      // Call updateTotalPrice once to include the initial total price
        updateTotalPrice();


        <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
        // Disable arrow key inputs
          $acharyaInput.on('keydown', function(e) {
            if (e.which === 38 || e.which === 40) {
              e.preventDefault();
            }
          });
        // Add validation to prevent input of negative values
          $acharyaInput.on('keydown', function(e) {
            if (e.key === '-' || e.key === '+') {
              e.preventDefault();
            }
          });

        // Add validation to prevent input of "+" and "e" characters
          $acharyaInput.on('input', function() {
            $acharyaInput.val($acharyaInput.val().replace(/[+e]/gi, ''));
          });
        <?php } ?>
        <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
          $generalInput.on('keydown', function(e) {
            if (e.which === 38 || e.which === 40) {
              e.preventDefault();
            }
          });

          $generalInput.on('keydown', function(e) {
            if (e.key === '-' || e.key === '+') {
              e.preventDefault();
            }
          });

          $generalInput.on('input', function() {
            $generalInput.val($generalInput.val().replace(/[+e]/gi, ''));
          });
        <?php } ?>

      });


      const paypalButtonsComponent = paypal.Buttons({
        style: {
          shape: 'rect',
          color: 'gold',
          layout: 'vertical',
          label: 'paypal',

        },

        createOrder: (data, actions) => {



          <?php if ($isIncludeSankalpam_result == 'YES') { ?>

            var familyMembers = [];
            var nakshtras = [];
            var rashi = [];
            var relationship = [];
            var dob = [];
            var anniversaryDate = [];


            $("input[name='family_member[]']").each(function() {
              var value = $(this).val();
              familyMembers.push(value);
            });

            $("select[name='nakshtra[]']").each(function() {
              var value = $(this).val();
              nakshtras.push(value);
            });

            $("input[name='dob[]']").each(function() {
              var value = $(this).val();
              dob.push(value);
            });

            $("select[name='rashi[]']").each(function() {
              var value = $(this).val();
              rashi.push(value);
            });

            $("select[name='relationship[]']").each(function() {
              var value = $(this).val();
              relationship.push(value);
            });

            $("input[name='anniversaryDate[]']").each(function() {
              var value = $(this).val();
              anniversaryDate.push(value);
            });


            var fname = $("#fname").val();
            var lname = $("#lname").val();
            var gothram = $("#gothram").val();
            var stars = $("#stars").val();


            var spouseName = $("#spouseName").val();
            var spouseStars = $("#spouseStars").val();


            var No_Family_Member = $("#No_Family_Member").val();
            var No_Spouse = $("#No_Spouse").val();


            $.ajax({
              url: "<?= base_url('UpdateProfileGlobal/UpdateProfile') ?>",
              type: "POST",
              dataType: "json",
              data: {

                'familyMembers': familyMembers,
                'nakshtras': nakshtras,
                'dob': dob,
                'rashi': rashi,
                'relationship': relationship,
                'anniversaryDate': anniversaryDate,
                'fname': fname,
                'lname': lname,
                'gothram': gothram,
                'stars': stars,
                'spouseName': spouseName,
                'spouseStars': spouseStars,
                "noSpouse": No_Spouse,
                "noFamily": No_Family_Member
              },
              success: function(response) {


                console.log(response);

              }
            });

          <?php } ?>


          var currency = "USD";

          amt = parseFloat($('#total-price').text().replace('<?= $currencySymbol ?> ', '')) || 0;

          var paymentSource = data.paymentSource;

          var status = 'TEMP';

          var totalPrice = amt;

          var acharya_sambhavana = parseFloat($('#acharya-sambhavana-input').val()) || 0;
          var general_donation = parseFloat($('#general-donation-input').val()) || 0;



          var cart_data = '<?= json_encode($cart_items) ?>';

          $.ajax({
            url: "<?= base_url('Services/AddToCart') ?>",
            type: "POST",
            dataType: "json",
            data: {

              'status': status,
              'paymentSource': paymentSource,
              'totalPrice': totalPrice,
              'acharya_sambhavana': acharya_sambhavana,
              'general_donation': general_donation,
              'cart_data': cart_data,
            },
            success: function(response) {

              loader.off();
              console.log(response);

            }
          });






          const createOrderPayload = {
            purchase_units: [{
              amount: {
                currency_code: currency,
                value: amt
              }
            }]
          };

          return actions.order.create(createOrderPayload);
        },


        onApprove: (data, actions) => {

          const captureOrderHandler = (details) => {



            loader.on();






            var status = 'COMPLETED';
            var transaction_id = details.purchase_units[0].payments.captures[0].id;

            $.ajax({
              url: "<?= base_url('Services/updateTransactionStatus') ?>",
              type: "POST",
              dataType: "json",
              data: {

                'status': status,
                'transaction_id': transaction_id,
                'paymentDescription': details
              },
              success: function(response) {
                loader.off();

                if (response.statusCode == 1) {

                  swal({
                    html: true,
                    title: "Service Booking Confirmed!",
                    text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + response.envoiceNo,
                    type: "success",
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#008080',
                  },

                  function() {


                    window.location.reload();

                  });

                } else {
                  swal({
                    html: true,
                    title: "Failed!",
                    text: "<span>Transaction Failed!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + response.envoiceNo,
                    type: "error",
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#008080',
                  },
                  function() {
                    window.location.reload();
                  });
                }

              }
            });

          };

          return actions.order.capture().then(captureOrderHandler);
        },

        onError: (err) => {

          console.log(err);
          alert('Transaction Failed');

        }
      });

paypalButtonsComponent
.render("#paypal-button-container")
.catch((err) => {
  console.log('PayPal Buttons failed to render');
});

function BookNow() {
  loader.on();
  swal({
    title: "Confirmation?",
    text: "Are you sure you want to request this service?",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#008080",
    confirmButtonText: "Yes",
    closeOnConfirm: false
  },
  function(isConfirmed) {
    if (isConfirmed) {
            // Disable the button
      $('.confirm').prop('disabled', true);

      loader.on();
      $.ajax({
        url: "<?= base_url('Services/AddServiceRequest') ?>",
        type: "POST",
        dataType: "json",
        success: function(response) {
          loader.off();
          if (response.statusCode == 1) {
            swal({
              html: true,
              title: "Service Request Successful!",
              type: "success",
              confirmButtonText: 'OK',
              confirmButtonColor: '#008080',
            },
            function() {
              window.location.reload();
            });
          } else {
            swal({
              html: true,
              title: "Failed!",
              text: "<span>Transaction Failed!<span>",
              type: "error",
              confirmButtonText: 'OK',
              confirmButtonColor: '#008080',
            },
            function() {
              window.location.reload();
            });
          }
        }
      });
    }
  });

  loader.off();
}
</script>

<?php } ?>





<?php

if (isset($paymentSetting) && $paymentSetting == 'MPI' && $paymentSeverOn == 1) { ?>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>



  <script type="text/javascript" src="https://www.bridgepaynetsecuretx.com/Bridgepay.WebSecurity/TokenPay/js/tokenPay.js"></script>
  <?php $mpiTokenPayId  = @$getclientInfoById['MPItokenPay'];

  if (isset($mpiTokenPayId) && $mpiTokenPayId != '') {
    $TokenPay = $mpiTokenPayId;
  } else {
    $TokenPay = 'tokenpay10579api20211508121542285';
  }
  ?>
  <script>
    /*Acharya sambhawana And General Donation  Start*/
    $(document).ready(function() {
      var $totalPrice = $('#total-price');


      <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
        var $acharyaInput = $('#acharya-sambhavana-input');
        $acharyaInput.on('input', updateTotalPrice);
      <?php } ?>

      <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
        var $generalInput = $('#general-donation-input');
        $generalInput.on('input', updateTotalPrice);
      <?php } ?>



      // Function to update the total price based on the input values
      function updateTotalPrice() {
        // Get the input values
        var acharyaValue = 0;
        var generalValue = 0;
        <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
          var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
        <?php } ?>
        <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
          var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
        <?php } ?>



        // Get the initial total price
        var initialTotalPrice = parseFloat(<?= @$payNowTotalAmount; ?>) || 0;

        // Calculate the new total price
        var newTotalPrice = initialTotalPrice + acharyaValue + generalValue;

        // Update the total price element
        $totalPrice.text('<?= $currencySymbol ?> ' + newTotalPrice.toFixed(2));
      }

      // Call updateTotalPrice once to include the initial total price
      updateTotalPrice();


      <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
        // Disable arrow key inputs
        $acharyaInput.on('keydown', function(e) {
          if (e.which === 38 || e.which === 40) {
            e.preventDefault();
          }
        });
        // Add validation to prevent input of negative values
        $acharyaInput.on('keydown', function(e) {
          if (e.key === '-' || e.key === '+') {
            e.preventDefault();
          }
        });

        // Add validation to prevent input of "+" and "e" characters
        $acharyaInput.on('input', function() {
          $acharyaInput.val($acharyaInput.val().replace(/[+e]/gi, ''));
        });
      <?php } ?>
      <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
        $generalInput.on('keydown', function(e) {
          if (e.which === 38 || e.which === 40) {
            e.preventDefault();
          }
        });

        $generalInput.on('keydown', function(e) {
          if (e.key === '-' || e.key === '+') {
            e.preventDefault();
          }
        });

        $generalInput.on('input', function() {
          $generalInput.val($generalInput.val().replace(/[+e]/gi, ''));
        });
      <?php } ?>

    });
    /*Acharya sambhawana And General Donation  End*/


    var tokenpay = TokenPay('<?= $TokenPay ?>');
    tokenpay.initialize({
      dataElement: '#card',
      errorElement: '#errorMessage',
      amountElement: '#amount',
      useStyles: false,
      useACH: false,
      disableZip: true,
      disableCvv: false
    });

    var form = document.getElementById('paymentForm');
    form.addEventListener('submit', function(event) {


      loader.on();

      <?php if ($isIncludeSankalpam_result == 'YES') { ?>

        var familyMembers = [];
        var nakshtras = [];
        var rashi = [];
        var relationship = [];
        var dob = [];
        var anniversaryDate = [];


        $("input[name='family_member[]']").each(function() {
          var value = $(this).val();
          familyMembers.push(value);
        });

        $("select[name='nakshtra[]']").each(function() {
          var value = $(this).val();
          nakshtras.push(value);
        });

        $("input[name='dob[]']").each(function() {
          var value = $(this).val();
          dob.push(value);
        });

        $("select[name='rashi[]']").each(function() {
          var value = $(this).val();
          rashi.push(value);
        });

        $("select[name='relationship[]']").each(function() {
          var value = $(this).val();
          relationship.push(value);
        });

        $("input[name='anniversaryDate[]']").each(function() {
          var value = $(this).val();
          anniversaryDate.push(value);
        });


        var fname = $("#fname").val();
        var lname = $("#lname").val();
        var gothram = $("#gothram").val();
        var stars = $("#stars").val();


        var spouseName = $("#spouseName").val();
        var spouseStars = $("#spouseStars").val();


        var No_Family_Member = $("#No_Family_Member").val();
        var No_Spouse = $("#No_Spouse").val();


        $.ajax({
          url: "<?= base_url('UpdateProfileGlobal/UpdateProfile') ?>",
          type: "POST",
          dataType: "json",
          data: {

            'familyMembers': familyMembers,
            'nakshtras': nakshtras,
            'dob': dob,
            'rashi': rashi,
            'relationship': relationship,
            'anniversaryDate': anniversaryDate,
            'fname': fname,
            'lname': lname,
            'gothram': gothram,
            'stars': stars,
            'spouseName': spouseName,
            'spouseStars': spouseStars,
            "noSpouse": No_Spouse,
            "noFamily": No_Family_Member
          },
          success: function(response) {


            console.log(response);

          }
        });

      <?php } ?>




      event.preventDefault();
      tokenpay.createToken(function(result) {

        console.log(result);


        var totalPriceText = $("#total-price").text();
        var mpi_zipcode = $("#zipcode").val();
        var mpi_fname = $("#fname").val();
        var mpi_address = $("#address").val();

        var numericValue = totalPriceText.replace(/[^0-9.]/g, '');
        var numericAmount = parseFloat(numericValue);

        var totolAmt = numericAmount;


        if (result.status == 'auth_success') {
          var cart_data = '<?= json_encode($cart_items) ?>';

          $.ajax({
            url: "<?= base_url('MPI_Payments/Paynow') ?>",
            type: "POST",
            dataType: "json",
            data: {
              'token': result.token,
              'totolAmt': totolAmt,
              'name': mpi_fname,
              'address': mpi_address,
              'zipcode': mpi_zipcode,
              'cart_data' : cart_data
            },
            success: function(mpicardpayment_response) {

              console.log(mpicardpayment_response.data);
              var paymentSource = 'MPI';

              var status = 'TEMP';

              var totalPrice = totolAmt;

              var acharya_sambhavana = parseFloat($('#acharya-sambhavana-input').val()) || 0;
              var general_donation = parseFloat($('#general-donation-input').val()) || 0;



              var cart_data = '<?= json_encode($cart_items) ?>';


              if (mpicardpayment_response.data.responseCode == 00000) {


                $.ajax({
                  url: "<?= base_url('Services/AddToCart') ?>",
                  type: "POST",
                  dataType: "json",
                  data: {

                    'status': status,
                    'paymentSource': paymentSource,
                    'totalPrice': totalPrice,
                    'acharya_sambhavana': acharya_sambhavana,
                    'general_donation': general_donation,
                    'cart_data': cart_data,
                  },
                  success: function(addtocart_response) {

                    console.log(mpicardpayment_response);

                    if (addtocart_response.statusCode == 1) {

                      var status = 'COMPLETED';
                      var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;

                      function responces() {
                        var status = 'COMPLETED';
                        var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;
                      }

                      $.ajax({
                        url: "<?= base_url('Services/updateTransactionStatus') ?>",
                        type: "POST",
                        dataType: "json",
                        data: {

                          'status': status,
                          'transaction_id': trnxId,
                          'paymentDescription': mpicardpayment_response
                        },
                        success: function(update_transactionstatus_response) {
                          if (update_transactionstatus_response.statusCode == 1) {


                            swal({
                              html: true,
                              title: "Service Booking Confirmed!",
                              text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
                              type: "success",
                              confirmButtonText: 'OK',
                              confirmButtonColor: '#008080',
                            },
                            function() {
                              window.location.reload();
                            });

                            loader.off();
                          }

                        }
                      });

                    }
                  }
                });

              } else {

                $.ajax({
                  url: "<?= base_url('Services/AddToCart') ?>",
                  type: "POST",
                  dataType: "json",
                  data: {

                    'status': status,
                    'paymentSource': paymentSource,
                    'totalPrice': totalPrice,
                    'acharya_sambhavana': acharya_sambhavana,
                    'general_donation': general_donation,
                    'cart_data': cart_data,
                  },
                  success: function(addtocart_response) {

                    if (addtocart_response.statusCode == 1) {
                      var status = 'FAILED';
                      var trnxId = "Payment failed~0~" + mpicardpayment_response.message;

                      $.ajax({
                        url: "<?= base_url('Services/updateTransactionStatus') ?>",
                        type: "POST",
                        dataType: "json",
                        data: {

                          'status': status,
                          'transaction_id': trnxId,
                          'paymentDescription': mpicardpayment_response
                        },
                        success: function(update_transactionstatus_response) {
                          if (update_transactionstatus_response.statusCode == 1) {

                            var original_string = update_transactionstatus_response.message;
                            var substring_to_replace = "Payment failed~0~"

                            var new_string = original_string.replace(substring_to_replace, "");

                            swal({
                              html: true,
                              title: "Failed!",
                              text: "<span>" + new_string + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
                              type: "error",
                              confirmButtonText: 'OK',
                              confirmButtonColor: '#008080',
                            },
                            function() {
                              window.location.reload();
                            });

                            loader.off();
                          }

                        }
                      });

                    }
                  }
                });
              }

            }
          });
} else {
  alert('Please enter valid details');
}

}, function(result) {
  loader.off();
  console.log("error@@@: " + result.token);
});
});
</script>




<?php } ?>


<?php

if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE' && $paymentSeverOn == 1) { ?>

  <script type="text/javascript">
    /*Acharya sambhawana And General Donation  Start*/
    $(document).ready(function() {



      var $totalPrice = $('#total-price');
      var amountString = $('#total-price').text();
      var finalAmtWithoutDollar = amountString.replace("$", "");
      var finalAmt = parseInt(finalAmtWithoutDollar);




      var iframe = document.getElementById('paymentIframe');



      var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=<?=$CAW_MerchantId?>&TerminalId=<?=$CAW_TerminalId?>&Amount=" + finalAmt + "&Mode=0";
      

      // var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=27680&TerminalId=0001&Amount=" + finalAmt + "&Mode=0";



      iframe.src = url;



      <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
        var $acharyaInput = $('#acharya-sambhavana-input');
        $acharyaInput.on('input', updateTotalPrice);
      <?php } ?>

      <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
        var $generalInput = $('#general-donation-input');
        $generalInput.on('input', updateTotalPrice);
      <?php } ?>



      // Function to update the total price based on the input values
      function updateTotalPrice() {
        // Get the input values
        var acharyaValue = 0;
        var generalValue = 0;
        <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
          var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
        <?php } ?>
        <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
          var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
        <?php } ?>



        // Get the initial total price
        var initialTotalPrice = parseFloat(<?= @$s_total; ?>) || 0;

        // Calculate the new total price
        var newTotalPrice = initialTotalPrice + acharyaValue + generalValue;

        // Update the total price element
        $totalPrice.text('<?= $currencySymbol ?> ' + newTotalPrice.toFixed(2));


        var iframe = document.getElementById('paymentIframe');
        var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=<?=$CAW_MerchantId?>&TerminalId=<?=$CAW_TerminalId?>&Amount=" + newTotalPrice.toFixed(2) + "&Mode=0";



        iframe.src = url;

      }

      // Call updateTotalPrice once to include the initial total price
      updateTotalPrice();


      <?php if (@$GeneralSettings['AcharyaSambhavana'] == 1) { ?>
        // Disable arrow key inputs
        $acharyaInput.on('keydown', function(e) {
          if (e.which === 38 || e.which === 40) {
            e.preventDefault();
          }
        });
        // Add validation to prevent input of negative values
        $acharyaInput.on('keydown', function(e) {
          if (e.key === '-' || e.key === '+') {
            e.preventDefault();
          }
        });

        // Add validation to prevent input of "+" and "e" characters
        $acharyaInput.on('input', function() {
          $acharyaInput.val($acharyaInput.val().replace(/[+e]/gi, ''));
        });
      <?php } ?>
      <?php if (@$GeneralSettings['GeneralDonationAmount'] == 1) { ?>
        $generalInput.on('keydown', function(e) {
          if (e.which === 38 || e.which === 40) {
            e.preventDefault();
          }
        });

        $generalInput.on('keydown', function(e) {
          if (e.key === '-' || e.key === '+') {
            e.preventDefault();
          }
        });

        $generalInput.on('input', function() {
          $generalInput.val($generalInput.val().replace(/[+e]/gi, ''));
        });
      <?php } ?>

    });
    /*Acharya sambhawana And General Donation  End*/


    window.addEventListener('message', handleMessage, false);
    window.addEventListener('message', chargeanywher, false);

    function handleMessage(event) {

      if (event.origin != "https://www.chargeanywhere.com") {
        return;
      }

      var customData = event.data;


    }



    function chargeanywher(event) {

      loader.on();

      if (event.origin != "https://www.chargeanywhere.com") {
        return;
      }

      // console.log(event);

      var customData = event.data;


      console.log(customData);


      var cart_data = '<?= json_encode($cart_items) ?>';
      var paymentSource = 'CREDIT CARD';


      var grand_totalPrice = customData.GrandTotal;

      totalPrice = parseFloat(grand_totalPrice);


      var acharya_sambhavana = parseFloat($('#acharya-sambhavana-input').val()) || 0;
      var general_donation = parseFloat($('#general-donation-input').val()) || 0;


      if (customData.ResponseCode === "000") {

        var status = 'COMPLETED';

        <?php if ($isIncludeSankalpam_result == 'YES') { ?>

          var familyMembers = [];
          var nakshtras = [];
          var rashi = [];
          var relationship = [];
          var dob = [];
          var anniversaryDate = [];


          $("input[name='family_member[]']").each(function() {
            var value = $(this).val();
            familyMembers.push(value);
          });

          $("select[name='nakshtra[]']").each(function() {
            var value = $(this).val();
            nakshtras.push(value);
          });

          $("input[name='dob[]']").each(function() {
            var value = $(this).val();
            dob.push(value);
          });

          $("select[name='rashi[]']").each(function() {
            var value = $(this).val();
            rashi.push(value);
          });

          $("select[name='relationship[]']").each(function() {
            var value = $(this).val();
            relationship.push(value);
          });

          $("input[name='anniversaryDate[]']").each(function() {
            var value = $(this).val();
            anniversaryDate.push(value);
          });


          var fname = $("#fname").val();
          var lname = $("#lname").val();
          var gothram = $("#gothram").val();
          var stars = $("#stars").val();


          var spouseName = $("#spouseName").val();
          var spouseStars = $("#spouseStars").val();


          var No_Family_Member = $("#No_Family_Member").val();
          var No_Spouse = $("#No_Spouse").val();


          $.ajax({
            url: "<?= base_url('UpdateProfileGlobal/UpdateProfile') ?>",
            type: "POST",
            dataType: "json",
            data: {

              'familyMembers': familyMembers,
              'nakshtras': nakshtras,
              'dob': dob,
              'rashi': rashi,
              'relationship': relationship,
              'anniversaryDate': anniversaryDate,
              'fname': fname,
              'lname': lname,
              'gothram': gothram,
              'stars': stars,
              'spouseName': spouseName,
              'spouseStars': spouseStars,
              "noSpouse": No_Spouse,
              "noFamily": No_Family_Member
            },
            success: function(response) {


              console.log(response);

            }
          });

        <?php } ?>


        $.ajax({
          url: "<?= base_url('Services/AddToCart') ?>",
          type: "POST",
          dataType: "json",
          data: {

            'status': status,
            'paymentSource': paymentSource,
            'totalPrice': totalPrice,
            'acharya_sambhavana': acharya_sambhavana,
            'general_donation': general_donation,
            'cart_data': cart_data,
          },
          success: function(addtocart_response) {

            console.log(addtocart_response);



            if (addtocart_response.statusCode == 1) {

              var status = 'COMPLETED';

              var cardTypeCode = customData.CardType; 
              var cardTypeName = getCardTypeName(cardTypeCode);

              var trnxId = "Payment completed~" + customData.ReferenceNumber + "~" + cardTypeName + "~" + customData.CardNumber;
              $.ajax({
                url: "<?= base_url('Services/updateTransactionStatus') ?>",
                type: "POST",
                dataType: "json",
                data: {

                  'status': status,
                  'transaction_id': trnxId,
                  'paymentDescription': customData
                },
                success: function(update_transactionstatus_response) {
                  if (update_transactionstatus_response.statusCode == 1) {


                    swal({
                      html: true,
                      title: "Service Booking Confirmed!",
                      text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
                      type: "success",
                      confirmButtonText: 'OK',
                      confirmButtonColor: '#008080',
                    },
                    function() {
                      window.location.reload();
                    });

                    loader.off();
                  }

                }
              });

            }
          }
        });



      } else {

        $.ajax({
          url: "<?= base_url('Services/AddToCart') ?>",
          type: "POST",
          dataType: "json",
          data: {

            'status': 'TEMP',
            'paymentSource': paymentSource,
            'totalPrice': totalPrice,
            'acharya_sambhavana': acharya_sambhavana,
            'general_donation': general_donation,
            'cart_data': cart_data,
          },
          success: function(addtocart_response) {
            console.log(addtocart_response);

            if (addtocart_response.statusCode == 1) {
              var status = 'FAILED';

              var cardTypeCode = customData.CardType;
              var cardTypeName = getCardTypeName(cardTypeCode);


              var trnxId = "Payment failed~0~" + customData.ResponseText + "~" + cardTypeName + "~" + customData.CardNumber;


              $.ajax({
                url: "<?= base_url('Services/updateTransactionStatus') ?>",
                type: "POST",
                dataType: "json",
                data: {

                  'status': status,
                  'transaction_id': trnxId,
                  'paymentDescription': customData
                },
                success: function(update_transactionstatus_response) {
                  if (update_transactionstatus_response.statusCode == 1) {

                    var original_string = update_transactionstatus_response.message;
                    var substring_to_replace = "Payment failed~0~"

                    var new_string = original_string.replace(substring_to_replace, "");

                    swal({
                      html: true,
                      title: "Failed!",
                      text: "<span>" + new_string + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
                      type: "error",
                      confirmButtonText: 'OK',
                      confirmButtonColor: '#008080',
                    },
                    function() {
                      window.location.reload();
                    });

                    loader.off();
                  }

                }
              });

            }
          }
        });
      }


      // alert(JSON.stringify(customData, null, 2));
    }
  </script>

<?php } ?>





<script type="text/javascript">
  $(document).ready(function() {
    // Add an event handler for the change event on elements with class "is_paynow"
    $('.is_paynow').change(function() {


      var selectedOptionsArray = [];
      var selectedOptionsIdsArray = [];
      var selectedOptionValueArray = [];
      var isServicePaid = '';
      // Loop through all elements with class "is_paynow" to gather selected values
      $('.is_paynow').each(function() {
        var selectedOptionValue = $(this).val();

        if (selectedOptionValue > 0) {
          isServicePaid = 'YES';
        } else {
          isServicePaid = 'NO';
        }

        selectedOptionsArray.push(isServicePaid);
        selectedOptionValueArray.push(selectedOptionValue);



        var selectId = $(this).attr('id');
        selectedOptionsIdsArray.push(selectId);
      });


      // Get the selected option value
      var selectedOptionValue = $(this).val();

      // Get the ID of the select element
      var selectId = $(this).attr('id');
      var realAmount = $('option:selected', this).attr('real-value');

      // alert(realAmount);

      // Build the ID of the corresponding amount element
      var amountElementId = 'amount_' + selectId;

      // Get the current sub-total and sale total
      var subtoltal = parseFloat($("#subtle").text().replace('$', '').trim()) || 0;
      var saletoltal = parseFloat($("#saletle").text().replace('$', '').trim()) || 0;
      var totalprice = parseFloat($("#total-price").text().replace('$', '').trim()) || 0;

      $('#' + amountElementId).text('$ ' + parseFloat(selectedOptionValue).toFixed(2));

      // Update sub-total and sale total based on the selected option value
      if (selectedOptionValue == 0) {
        $("#subtle").text('$ ' + (subtoltal - parseFloat(realAmount)).toFixed(2));
        $("#saletle").text('$ ' + (saletoltal - parseFloat(realAmount)).toFixed(2));
        $("#total-price").text('$ ' + (saletoltal - parseFloat(realAmount)).toFixed(2));
        var isServicePaid = 'NO';
      } else {
        $("#subtle").text('$ ' + (parseFloat(realAmount) + subtoltal).toFixed(2));
        $("#saletle").text('$ ' + (parseFloat(realAmount) + saletoltal).toFixed(2));
        $("#total-price").text('$ ' + (parseFloat(realAmount) + saletoltal).toFixed(2));
        var isServicePaid = 'YES';
      }



      $.ajax({
        url: "<?= base_url('Services/updateCart') ?>",
        type: "POST",
        dataType: "json",
        data: {

          'service_id': selectedOptionsIdsArray,
          'isServicePaid': selectedOptionsArray
        },
        success: function(response) {

          console.log(response);

        }
      });


    });
    // $('.is_paynow').eq(1).trigger('change');

  });
</script>
<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>
<!-- ==========Language Translator Code============= -->
<div class="ldld full" style="    z-index: 999;"></div>
