<?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'); ?>">
<style>
  .servicesTr {
    border-bottom: 1px solid #c8c8c8 !important;
  }

  .servicesTr td {
    padding-bottom: 5px !important;
  }

  .row {
    margin-left: 0px !important;
    margin-right: 0px !important;
  }

  .padding-5 {
    padding: 3rem;
  }

  @media only screen and (max-width:767px) {
    .padding-5 {
      padding: 1rem;
    }
  }





  :root {
    --main-color-new-theme: #76020f;
    --main-color-new-theme-light: #ebd503;
  }

  .card-title {
    font-size: 1rem !important;
    margin-bottom: 0rem !important;
    line-height: 1 !important;
  }

  .card-text {
    font-size: 1rem !important;
    font-weight: bolder !important;
  }

  h4,
  .h4 {
    font-size: calc(.7rem + 0.3vw) !important;
    font-weight: 900 !important;
  }

  .btn-toggle {
    display: inline-block;
    padding: 8px 16px;
    background-color: var(--main-color-new-theme);
    /* Bootstrap red */
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  input[type="checkbox"]:checked+label.btn-toggle {
    background-color: #28a745;
    /* Bootstrap green */
  }

  .btn-toggle i {
    margin-right: 5px;
  }

  .body,
  p,
  label,
  span {
    font-family: sans-serif !important;
    /* color: black !important; */
  }

  .mdtp__time_holder span,
  .mdtp__digit.active span,
  .mdtp__am.active,
  .mdtp__pm.active {
    color: white !important;
  }

  label {
    font-weight: 600 !important;
    font-size: 16px;
  }

  h4 {
    font-family: sans-serif !important;
    font-weight: 700 !important;
    color: black !important;
    font-size: 16px !important;
  }

  .form-control {
    border: 1px solid #80808045 !important;
  }

  .hidden-div {
    display: none;
  }

  .form-control:disabled,
  .form-control[readonly] {
    /* background-color: #dbdbdb !important; */
    opacity: 1;
  }

  .btn-toggle {
    font-weight: 600 !important;
    font-size: 14px;
    color: white !important;
  }

  .card-title {
    font-family: sans-serif !important;
  }

  .form-select {
    color: #000000 !important;
  }
</style>
<?php

$header_data = getWebSyncsData('Header Settings', 'headerSettings', '');

$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'];

$membershipDetails = membershipStatusCheck();
$setting = SettingsApi();
$weekOffDayArr = @$setting['result']['data'][0]['prasadamKioskSettings']['WeekOffDays'];
$weekendDaysArr = @$setting['result']['data'][0]['prasadamKioskSettings']['weekendDays'];
$kitchenClosingWeekendTimeFrom = @$setting['result']['data'][0]['prasadamKioskSettings']['kitchenClosingWeekendTimeFrom'];
$kitchenClosingWeekendTimeTo = @$setting['result']['data'][0]['prasadamKioskSettings']['kitchenClosingWeekendTimeTo'];
$kitchenClosingWeekDayTimeFrom = @$setting['result']['data'][0]['prasadamKioskSettings']['kitchenClosingWeekDayTimeFrom'];
$kitchenClosingWeekDayTimeTo = @$setting['result']['data'][0]['prasadamKioskSettings']['kitchenClosingWeekDayTimeTo'];
$kitchenOpenTime = @$setting['result']['data'][0]['prasadamKioskSettings']['kitchenOpenTime'];
$KitchenCloseTime = @$setting['result']['data'][0]['prasadamKioskSettings']['KitchenCloseTime'];
// $formAction         = $setting['result']['data'][0]['serviceRequestSettings']['bookingTypes'];
// $formAction         = 'REQUEST WITH PAYMENT';
$membershipDiscount = $setting['result']['data'][0]['membershipSettings']['membershipDiscount'];
$discountType       = $setting['result']['data'][0]['membershipSettings']['discountType'];
$pickupTime = @$setting['result']['data'][0]['prasadamKioskSettings']['pickupTime'];
$formAction = @$setting['result']['data'][0]['cateringKioskSettings']['bookingTypes'];
$cateringAdvance = @$setting['result']['data'][0]['cateringKioskSettings']['cateringAdvance'];
$cateringAdvanceType = @$setting['result']['data'][0]['cateringKioskSettings']['Type'];

$addressLine1 = @$userDetails->addressLine1;
$addressLine2 = @$userDetails->addressLine2;
$cityTypes    = @$userDetails->cityTypes;
$county       = @$userDetails->county;
$stateTypes   = @$userDetails->stateTypes;
$zip          = @$userDetails->zip;
?>
<main id="main">
  <section style="background-size: auto;">


    <h2 class="text-center mb-0" style="font-weight:bold!important;font-size: 25px!important;"> CHECKOUT<br><img src="<?= base_url('assets/img/border.png'); ?>" class="img-fluid" style="width: 15%;max-width: 15%;"></h2>

    <!-- <button onclick="window.history.back()">Go Back</button> -->
    <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:var(--main-color-new-theme);">
                <a href="javaScript:void(0)" class="btn" onclick="window.history.back()" style="background-color:var(--main-color-new-theme);color: white!important;border-radius: 1px!important;display:none;">← Back</a>
                <?php
                $redirectURL = 'akshaya-patra/list';
                $redirectURL2 = 'akshaya-patra';
                $redirectURL3 = 'akshaya-patra/list';
                ?>
                <a href="<?= base_url($redirectURL) ?>" class="btn" style=";background-color:#e78b00;color: var(--main-color-new-theme)!important;border-radius: 1px!important;">Close X</a>
              </div>
              <?php
              $service_cart_items = @$this->session->userdata('akshaya_patra_cart');

              $totalItemsCount = 0;

              $totalItemsCount += !empty($service_cart_items) && isset($service_cart_items['ids']) ? count($service_cart_items['ids']) : 0;

              $phone_html = '';
              $payNowTotalAmount = 0;
              $s_total = 0;
              ?>
              <?php

              $currencySymbol = isset($GeneralSettings['currencySymbol']) ? (CheckEmptyNullVar($GeneralSettings['currencySymbol']) != '' ? $GeneralSettings['currencySymbol'] : '$') : '$';

              if (isset($this->session->userdata('akshaya_patra_cart')['ids']) && $totalItemsCount > 0) { ?>


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

                      <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3 class="fw-bold mb-0 text-black">Order Summary</h3>

                        <h6 class="mb-0 text-muted d-none d-md-block"><?= $totalItemsCount; ?> items</h6>
                      </div>
                      <hr class="my-4">
                      <!-- ============================================= -->
                      <div class="d-none d-md-block">
                        <div class="table-responsive">
                          <table style="width:100%">
                            <thead>
                              <tr>
                                <th style="width:60%" class="text-start">Service Name</th>
                                <th style="width:5%" class="text-center">Qty.</th>
                                <th style="width:15%" class="text-end">Total.</th>
                                <th></th>
                              </tr>
                            </thead>
                            <tbody>

                              <?php



                              //Events====================================================
                              if (!empty($service_cart_items) && isset($service_cart_items['ids'])) {
                                foreach ($service_cart_items['ids'] as $key => $value) {
                                  if ($service_cart_items['serviceAmount'][$key] > 0) {
                                    $payNowTotalAmount += ($service_cart_items['serviceAmount'][$key] * $service_cart_items['qty'][$key]);
                                  }
                                  $discounted_price = '';
                                  $is_membership_discount = @$service_cart_items['is_membership_discount'][$key];
                                  if ($membershipDetails['membershipStatus'] == "ACTIVE" && $is_membership_discount == 'YES') {
                                    if ($discountType == 'FLAT') {

                                      if ($service_cart_items['serviceAmount'][$key] > $membershipDiscount) {
                                        $diacountHtml = '<small style="color:green;">( ' . $currencySymbol . ' ' . $membershipDiscount . ' OFF )</small>';
                                        $discounted_price = $service_cart_items['serviceAmount'][$key] - $membershipDiscount;
                                      }
                                    } else if ($discountType == 'SERVICE LEVEL') {
                                      $membershipDiscount = (float)$service_cart_items['membership_discount_amt'][$key];
                                      if ($membershipDiscount > 0) {
                                        $diacountHtml = '<small style="color:green;">( ' . $currencySymbol . ' ' . $membershipDiscount . ' OFF )</small>';
                                      }
                                      // $discounted_price = $service_cart_items['serviceAmount'][$key] - $membershipDiscount;
                                      $discounted_price = $membershipDiscount > 0 ? $membershipDiscount : $service_cart_items['serviceAmount'][$key];
                                    } else {
                                      $diacountHtml = '<small style="color:green;">( ' . $membershipDiscount . ' %OFF )</small>';
                                      $discounted_price = $service_cart_items['serviceAmount'][$key] - ($service_cart_items['serviceAmount'][$key] * $membershipDiscount) / 100;
                                    }
                                  }

                                  $final_price = $discounted_price ? $discounted_price : ($service_cart_items['serviceAmount'][$key] * $service_cart_items['qty'][$key]);


                                  $s_total += $final_price;
                              ?>
                                  <tr class="servicesTr">
                                    <td class="text-start">
                                      <p class="mb-0">
                                        <img src="<?php echo ApiBaseUrl()['url'] . $service_cart_items['image'][$key] ?>"
                                          class="img-fluid rounded"
                                          alt="<?php echo $service_cart_items['serviceName'][$key] ?>"
                                          style="max-width: 40px;">
                                        <?= $service_cart_items['serviceName'][$key]; ?>
                                      </p>
                                      <?= @$service_cart_items['trayType'][$key] ? '<b>Tray Type: </b>' . $service_cart_items['trayType'][$key] . '<br>' : ''; ?>
                                      <?= @$service_cart_items['startDate'][$key] && !empty(trim(@$service_cart_items['startDate'][$key])) ? '<b>Date: </b> ' . date('n/j/Y', strtotime($service_cart_items['startDate'][$key])) : '' ?>
                                    </td>

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


                                      <?php

                                      if ($discounted_price != '') { ?>
                                        <?= '<span style="font-weight: bold;font-size: larger;color: #b00000;">' . $currencySymbol . '&nbsp;' . number_format($service_cart_items['serviceAmount'][$key] * $service_cart_items['qty'][$key], 2) . '</span>'; ?>

                                      <?php
                                        $service_cart_items['discountedAmount'][$key] = (float)$service_cart_items['serviceAmount'][$key] - (float)$discounted_price;
                                        $service_cart_items['oldServiceAmount'][$key] = (float)$service_cart_items['serviceAmount'][$key];
                                        $service_cart_items['serviceAmount'][$key] = $discounted_price;
                                      } else { ?>

                                        <?= '<span>' . $currencySymbol . '&nbsp;' . number_format($service_cart_items['serviceAmount'][$key] * $service_cart_items['qty'][$key], 2) . '</span>'; ?>

                                      <?php
                                        $service_cart_items['discountedAmount'][$key] = '';
                                        $service_cart_items['oldServiceAmount'][$key] = '';
                                      }
                                      ?>
                                    </td>
                                    <td style="width:5%;text-align: center;" class="actions" data-th="">
                                      <a href="javaScript:void(0)" class="text-danger btn-sm event-delete-row" data-row-id="<?= $service_cart_items['ids'][$key]; ?>" style="font-size:17px"><i class="fa fa-trash-o"></i></a>
                                    </td>
                                  </tr>
                              <?php
                                  $phone_html .= '<div style="border-bottom: 1px dashed #ccc; padding-bottom: 10px; margin-bottom: 10px;">
                                  <img src="' . ApiBaseUrl()['url'] . $service_cart_items['image'][$key] . '"
                                                                    class="img-fluid rounded"
                                                                    alt="' . $service_cart_items['serviceName'][$key] . '"
                                                                    style="max-width: 40px;">
                                  <strong>' . htmlspecialchars($service_cart_items['serviceName'][$key]) . '</strong><br>';

                                  if (isset($service_cart_items['trayType'][$key])) {
                                    $phone_html .= '<span><b>Tray Type:</b> ' . htmlspecialchars($service_cart_items['trayType'][$key]) . '</span><br>';
                                  }

                                  if (isset($service_cart_items['startDate'][$key])) {
                                    $phone_html .= '<b>Service Date:</b> ' . date('n/j/Y', strtotime($service_cart_items['startDate'][$key])) . '<br>';
                                  }


                                  $phone_html .= '<span><b>Qty:</b> ' . $service_cart_items['qty'][$key] . '</span><br><span><b>Amount:</b> ' . $currencySymbol . '&nbsp;' . number_format($service_cart_items['serviceAmount'][$key] * $service_cart_items['qty'][$key], 2) . '</span><br>';


                                  $phone_html .= '<a href="javascript:void(0)" class="text-danger btn-sm event-delete-row" data-row-id="' . $service_cart_items['ids'][$key] . '"><i class="fa fa-trash-o"></i> Delete</a></div>';
                                }
                              }
                              ?>

                            </tbody>
                          </table>
                        </div>
                      </div>
                      <!--phone view-->
                      <div class="d-block d-md-none">


                        <?= $phone_html ?>

                      </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 ?> <?= number_format((price_format($service_cart_items['totalPrice'], 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100, 2); ?></span></div>

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

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

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

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

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


                        </div>

                      </div>



                      <?php
                      if ($payNowTotalAmount > $s_total) {
                      ?>
                        <div class="row mt-3">
                          <div class="col-md-6">
                            <h5 class="mb-0" style="font-weight:bold!important;font-size: 16px;color:#b00000;"> Membership Discount Applied (
                              <?php
                              if ($discountType == 'SERVICE LEVEL' || $discountType == 'FLAT') {
                                echo $currencySymbol . ' ' . number_format($payNowTotalAmount - $s_total, 2);
                              } else {
                                echo $membershipDiscount . '%';
                              }
                              ?>
                              )</h5>
                          </div>

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


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

                          </div>

                        </div>

                      <?php
                      }

                      ?>


                      <hr class="my-4">

                      <div class="row pt-3 pb-3" style="background-color:#dbdbdb">
                        <div class="col-12 col-md-8 text-start">
                          <h4 class="text-dark" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;font-size: 20px!important;">Sale Total</h4>
                        </div>
                        <div class="col-12 col-md-4 text-start text-md-end">

                          <h4 class="text-dark  text-start text-md-end" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;font-size: 20px!important;" id="saletle"><?= $currencySymbol ?>&nbsp;<?= number_format(($s_total + @$taxAmt), 2); ?>
                          </h4>
                        </div>
                      </div>


                    </div>
                  </div>
                  <div class="col-lg-5">
                    <div class="padding-5">
                      <div class="row">

                        <div class="col-md-12 fw-bold text-start">
                          <h5 class="mb-2" style="color:var(--main-color-new-theme)!important">
                            <div class="row p-0">
                              <div class="col-sm-7 p-0">
                                <?php

                                if ($membershipDetails['membershipStatus'] == "ACTIVE") {

                                ?>
                                  <img src="<?= base_url('admin_assets/img/membership.png') ?>" alt="Membership Icon" height="20"> <?php
                                                                                                                                  }
                                                                                                                                    ?> <span class="fw-bold" style="word-wrap:none ;color:var(--main-color-new-theme)!important"><?= @$this->session->userdata('refDataName'); ?></span>
                              </div>
                              <div class="col-sm-5 p-0">
                                <span class="fw-bold" style="word-wrap:none ;color:var(--main-color-new-theme)!important">

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

                                </span>
                              </div>
                              <div class="col-sm-12 p-0"> <span><?= @base64_decode($this->session->userdata('email')); ?></span></div>
                            </div>

                          </h5>

                        </div>


                        <?php
                        if ($membershipDetails['membershipStatus'] == "ACTIVE") {
                        ?>

                          <div class="col-md-12 fw-bold text-start">
                            <h5 class="mb-2" style="color:var(--main-color-new-theme)!important">
                              <div class="row p-0">

                                <div class="col-sm-7 p-0">
                                  <span class="fw-bold" style="word-wrap:none ;color: #b00000;">Membership Type: </span>
                                </div>
                                <div class="col-sm-5 p-0">
                                  <span class="fw-bold" style="word-wrap:none ;color: #b00000;">

                                    <?= $membershipDetails['membershipType']; ?>

                                  </span>
                                </div>
                              </div>

                            </h5>
                          </div>
                        <?php
                        }
                        ?>

                        <div class="col-sm-12">
                          <hr>
                          <h3 class="" style="font-size: 17px;color:black;"><b>Home Address</b></h3>
                          <p style="font-size: 16px !important;line-height: 1 !important; margin-bottom: .5rem !important;"><?php echo @$userDetails->addressLine1 ?><?php echo @$userDetails->addressLine2 ? ', ' . $userDetails->addressLine2 : '' ?></p>
                          <p style="font-size: 16px !important; line-height: 1 !important; margin-bottom: .5rem !important;"><?php echo @$userDetails->cityTypes ?> <?php echo @$userDetails->stateTypes ? ', ' . $userDetails->stateTypes : '' ?> <?php echo @$userDetails->zip ? ', ' . @$userDetails->zip : '' ?></p>

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


                      <?php
                      // var_dump(@$CheckoutDonationSettings);
                      // $CheckoutDonationSettings['acharyasanbhavana'] = 1;
                      if (@$CheckoutDonationSettings['acharyasanbhavana'] == 1) { ?>
                        <hr class="my-2">
                        <div class="row p-3" style="background-color:#dbdbdb">
                          <div class="col-md-9">
                            <h6 class="fw-bold fontSize" style="margin-top:7px!important;margin-bottom:auto;"><?= @$CheckoutDonationSettings['AsDisplayTitle'] ?> (<?= $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 fontSize" id="acharya-sambhavana-input" onchange="AcharyaSambhavanaPriceFormate(this)">
                          </div>

                        </div>
                      <?php } ?>

                      <?php if (@$CheckoutDonationSettings['generalDonation'] == 1) { ?>
                        <div class="row p-3" style="background-color:#dbdbdb">
                          <div class="col-md-9">
                            <h6 class="fw-bold fontSize" style="margin-top:7px!important;margin-bottom:auto;"><?= @$CheckoutDonationSettings['DonationDisplayTitle'] ?> (<?= $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 fontSize" id="general-donation-input" onchange="AcharyaSambhavanaPriceFormate(this)">
                          </div>

                        </div>
                        <hr class="my-4">
                      <?php } ?>


                      <div class="row p-3 d-none" style="background-color:#dbdbdb">
                        <div class="col-md-12">
                          <!-- <h6 class="fw-bold fontSize" style="margin-top:7px!important;margin-bottom:auto;">Notes</h6> -->


                          <textarea name="creditCardRemark" placeholder="Enter notes here....." class="form-control form-control-sm fontSize" id="creditCardRemark"></textarea>
                        </div>

                      </div>
                      <hr class="">

                      <?php
                      if (empty($membershipDetails['membershipStatus'])) {

                      ?>
                        <div class="row mt-3">
                          <div class="col-md-12">
                            <h5 class="mb-0 fontSize text-center" style="font-weight:bold!important;font-size: 16px;color:#b00000;">
                              <a href="<?= base_url('membership-form?page=' . $redirectURL2) ?>" class="text-danger">** Become an annual member to avail discounts? Click here **</a>
                            </h5>
                          </div>
                        </div>
                      <?php
                      }
                      ?>
                      <div class="p-3 bg-white rounded-bottom">
                        <div class="mb-2">
                          <label for="etKitchenTIp" class="form-label">Donation to Akshay Patra</label>
                          <div class="d-flex"><span style="font-size: 20px!important;"><b><?= $currencySymbol ?></b></span>&nbsp;
                            <input type="text" class="form-control" name="etKitchenTIp" placeholder="0.00" id="etKitchenTIp">
                          </div>
                        </div>

                        <input type="hidden" name="totalPrice" id="totalPrice" value="<?php echo $s_total ?>">
                        <h5 class="text-end mb-4" id="totalPriceH">
                          <?php
                          if ($cateringAdvance > 0 && !empty($cateringAdvanceType)) {
                            if ($cateringAdvanceType == 'PERCENT') {
                              $advanceAmt = ($s_total * $cateringAdvance) / 100;
                            } else {
                              $advanceAmt = $cateringAdvance;
                            }

                            $advanceFacilityAmt = sprintf("%.2f", $advanceAmt);
                          } else {
                            $advanceFacilityAmt = sprintf("%.2f", $s_total);
                          }
                          $advanceUpdateAmt = 0;

                          ?>
                          <input type="hidden" style="width: 70px;" min="<?= $advanceFacilityAmt ?>" max="<?= sprintf("%.2f", $s_total) ?>" value="<?= $advanceFacilityAmt ?>" step="0.1" id="advanceAmtMain" name="advanceAmtMain">

                          <!-- <strong>Total: <?php echo $currencySymbol . price_format($s_total, 2) ?></strong> -->
                          <span id="sub-total1" style="float: right; font-weight: 600; color: var(--main-color-new-theme)!important; padding-right: 10px;font-size: 20px!important;">Total: <?=$currencySymbol?>&nbsp;<input type="number" style="width: 100px;
    font-size: 20px!important;
    font-weight: 800;
    padding-left: 5px !important;
    border-radius: 10px;" min="<?= $advanceFacilityAmt ?>" max="<?= sprintf("%.2f", $s_total) ?>" value="<?= $advanceFacilityAmt ?>" step="0.1" onchange="validateMinimumPay(this)" id="advanceAmt" name="advanceAmt"></span>

                        </h5>

                      </div>
<hr>

                      <div class="row" style="width: 100%!important;">
                        <div class="col-sm-12">
                          <div class="mb-3">
                            <label for="delivery">Pickup/Delivery:</label>
                            <input type="radio" class="form-radio" name="delivery" checked value="Carry Out" required> <span>Carry Out</span>&nbsp;
                            <input type="radio" class="form-radio d-none" name="delivery" value="Delivery" required> <span class="d-none">Delivery</span>
                          </div>
                        </div>
                        <div class="col-sm-6">

                          <label for="deliveryDate">Pickup Date <span class="text-danger">*</span> </label>
                          <!-- <label for="deliveryDate">Pickup/Delivery Date <span class="text-danger">*</span> </label> -->
                          <input type="text" class="form-control datepicker" readonly id="deliveryDate" placeholder="Pickup Date" name="deliveryDate" required>

                        </div>
                        <div class="col-sm-6">

                          <label for="deliveryTime">Pickup Time <span class="text-danger">*</span></label>
                          <!-- <label for="deliveryTime">Pickup/Delivery Time <span class="text-danger">*</span></label> -->
                          <!-- <input type="text" class="form-control" id="deliveryTime" placeholder="Pickup Time" name="deliveryTime" required> -->
                          <select name="deliveryTime" id="deliveryTime" class="form-control" style="padding: 0rem .75rem .375rem .75rem!important;">
                            <option value="" selected disabled>
                              --Pickup Time--
                            </option>
                            <?php
                            foreach ($pickupTime as $ptime) {
                              echo '<option value="' . $ptime . '">' . $ptime . '</option>';
                            }
                            ?>
                          </select>

                        </div>
                        <div class="col-sm-12 hidden-div">
                          <div class="mb-3 mt-3">
                            <label for="Copyhomeadd">Copy Home address from Delivery:</label>
                            <input type="radio" class="form-radio" name="Copyhomeadd" value="Yes"> <span>Yes</span>&nbsp;
                            <input type="radio" class="form-radio" name="Copyhomeadd" value="No"> <span>No</span>
                          </div>
                        </div>

                        <div class="col-sm-6  mt-2 hidden-div">

                          <label for="address">Address <span class="text-danger">*</span> </label>
                          <input type="text" class="form-control" id="address" placeholder="Address" name="address" style="height: 37px!important;">

                        </div>


                        <div class="col-sm-6  mt-2  hidden-div">

                          <label for="state">State <span class="text-danger">*</span> </label>
                          <!-- <input type="text" class="form-control" id="state" placeholder="State" name="state"> -->
                          <select class="form-control select2 rounded form-select pt-0" name="state" id="state">
                            <option value="" selected>Select State</option>
                            <?php

                            // print_r($userDetails);

                            $keys = array_column($GetState, 'refDataName'); /// Multidiamensional array sort by key
                            array_multisort($keys, SORT_ASC, $GetState);

                            foreach ($GetState as $state) { ?>
                              <option value="<?= strtoupper(@replaceSingleQuotesWithBackticks($state->refDataName)) ?>"><?= strtoupper(@replaceSingleQuotesWithBackticks($state->refDataName)) ?></option>
                            <?php } ?>
                          </select>
                          <?php strtoupper(@replaceSingleQuotesWithBackticks($state->refDataName)) == strtoupper(@replaceSingleQuotesWithBackticks($userDetails->stateTypes)) ? 'selected' : ''; ?>
                        </div>

                        <div class="col-sm-6  mt-2 hidden-div">

                          <label for="city">City <span class="text-danger">*</span></label>
                          <!-- <input type="text" class="form-control" id="city" placeholder="City" name="City"> -->
                          <select class="form-control rounded select3 form-select pt-0" name="city" id="city">
                            <option value="" selected disabled>Select City</option>
                          </select>

                        </div>

                        <div class="col-sm-6  mt-2  hidden-div">

                          <label for="zipcode">Zip Code <span class="text-danger">*</span></label>
                          <input type="text" class="form-control" id="zipcode" placeholder="Zipcode" name="zipcode" style="height: 37px!important;">

                        </div>
                        <div class="col-sm-12 mt-3 text-center">
                          <button type="button" onclick="submitForm();" class="btn" style="background:var(--main-color-new-theme);color:white;">Proceed To Checkout</button>
                        </div>
                      </div>

                      <!-- <div class="text-center my-3">
                        <div class="d-flex flex-column flex-md-row justify-content-between my-4 text-start text-md-end">
                          <h3 class="fw-bold mb-2 mb-md-0" style="font-size: 25px;">
                            Amount to Pay:
                          </h3>
                          <h3 class="fw-bold" style="font-size: 25px; border: 2px solid #dbdbdb; border-radius: 9px; padding: 3px;" id="total-price">
                            <?= $currencySymbol ?>&nbsp;<?= number_format($s_total, 2); ?>
                          </h3>
                        </div>

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



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

                            <style>
                              #amount {
                                width: 75px;
                              }

                              #card {
                                background: #ffffffa3;
                                height: 100px;
                                padding: 10px 12px;
                                border-radius: 5px;
                                border: 1px solid #84a6ae;
                                box-sizing: border-box;
                                line-height: 0;
                                margin: 9px 0px;
                                width: 500px;
                              }

                              .input-style {
                                color: #32a866;
                              }

                              .input-hint {
                                color: #5e95a1;
                                border-color: #9ac0c8;
                              }

                              /* All fields in form */
                              .form-wrapper {
                                width: 400px;
                              }

                              /* Credit Card Number */
                              .input-wrapper {
                                width: 200px;
                              }

                              /* Expiry Date */
                              .sub-wrapper {
                                width: 100px;
                              }

                              .valid-class {
                                color: #217195;
                              }

                              .invalid-class {
                                color: #b05826;
                              }

                              * {
                                box-sizing: border-box;
                              }

                              .row {
                                display: -ms-flexbox;
                                /* IE10 */
                                display: flex;
                                -ms-flex-wrap: wrap;
                                /* IE10 */
                                flex-wrap: wrap;
                                margin: 0 -16px;
                              }

                              .col-25 {
                                -ms-flex: 25%;
                                /* IE10 */
                                flex: 25%;
                              }

                              .col-50 {
                                -ms-flex: 50%;
                                /* IE10 */
                                flex: 50%;
                              }

                              .col-30 {
                                -ms-flex: 30%;
                                /* IE10 */
                                flex: 30%;
                              }

                              .col-75 {
                                -ms-flex: 75%;
                                /* IE10 */
                                flex: 75%;
                              }

                              .col-25,
                              .col-50,
                              .col-75 {
                                padding: 0 16px;
                              }


                              .form-control:focus {
                                color: #495057;
                                background-color: #fff;
                                border-color: #000408;
                                outline: 0;
                                box-shadow: 0 0 0 0.04rem rgb(0 0 0);
                              }


                              .icon-container {
                                margin-bottom: 20px;
                                padding: 7px 0;
                                font-size: 24px;
                              }




                              hr {
                                border: 1px solid lightgrey;
                              }

                              span.price {
                                float: right;
                                color: grey;
                              }
                            </style>
                            <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>
                                  <p for="fname" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">Name on Card <span class="text-danger">*</span></p>

                                  <input type="text" class="form-control fontSize" id="fname" name="firstname" placeholder="Enter Your Full Name*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->refDataName; ?>" required>
                                  <input type="email" id="email" class="form-control d-none" name="email" placeholder="Enter Your Email Address" 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); ?>" oninput="this.value = this.value.toLowerCase();">
                                  <input type="text" class="form-control d-none" 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 . ' ' . @$current_user->addressLine2; ?>">
                                  <p for="zipcode" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">ZIP Code <span class="text-danger">*</span></p>

                                  <input type="number" class="form-control fontSize" 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; ?>" onKeyPress="if(this.value.length==5) return false;" required>

                                  <div class="row m-0 p-0 d-none">
                                    <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>

                            </form>
                          <?php } else if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE') { ?>
                            <iframe id="paymentIframe" title="Payment Page" width="100%" height="600px"></iframe>

                            <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 } ?>
                      </div> -->
                    </div>
                  </div>
                </div>
                <!-- <input type="hidden" id="totalDonation" value="<?= price_format($service_cart_items['totalPrice'], 2); ?>"> -->
                <input type="hidden" id="totalDonation" value="<?= price_format($s_total, 2); ?>">
              <?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($redirectURL) ?>" class='btn text-center btn-primary btn-sm checkoutbtn' style='background: #910301; border: 1px solid yellow;'>Go to <?= $redirectURL3 ?></a>
                </div>

              <?php } ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</main>
<div class="modal fade" id="membershipModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">


      <div class="modal-header text-center">
        <h5 class="modal-title bottomborder modatTitle">CHECKOUT</h5>
        <button type="button" class="btn-close modalCloseBtn <?php echo @$modalClbtn; ?>" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="container">
          <img src="<?php echo ApiBaseUrl()['url'] . @$header_data[0]['leftImage'] ?>" class="img-fluid mb-4" height="100px" width="100px" style="display: block;margin-left: auto;margin-right: auto;">
          <div class="row d-flex justify-content-center align-items-center">
            <div class="col-xl-12">
              <div class="row g-0">
                <div class="col-xl-12">
                  <div class="row">
                    <div class="col-md-12 mb-4">
                      <table class="table table-responsive table-bordered text-center">
                        <thead>
                          <tr>
                            <th>
                              <h5 class="h5-title">Service Name</h5>
                            </th>
                            <th>
                              <h5 class="h5-title">Amount to Pay</h5>
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td id="serviceNameedittable">

                            </td>

                            <td id="edittable">

                            </td>
                          </tr>

                        </tbody>
                      </table>
                    </div>
                    <div class="col-sm-12" id="serviceNameedittableBody">

                    </div>
                  </div>

                  <div class="">
                    <div class="row">

                      <div class="col-md-12">


                        <?php
                        // $paymentSetting = 'MPITEST';
                        if (isset($paymentSetting) && $paymentSetting == 'PAYPAL' && $paymentSeverOn == 1) { ?>

                          <div class="oooooookkakak" id="paypal-button-container-membership"></div>

                        <?php } else if (isset($paymentSetting) && ($paymentSetting == 'MPI' || $paymentSetting == 'MPITEST') && $paymentSeverOn == 1) { ?>


                          <link rel="stylesheet" href="<?php echo base_url('assets/css/mpi-form.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="mpi_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="<?php echo @$userDetails->refDataName ?>">

                                <input type="number" class="form-control" id="mpi_zipcode" name="mpi_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="<?php echo @$userDetails->zip ?>">



                                <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>

                          </form>



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


                          <iframe id="paymentIframe" title="Payment Page" width="100%" height="600px"></iframe>

                        <?php } ?>

                        <button type="button" class="btn PaymentClosebtn btn-danger ms-2" data-dismiss="modal" hidden>CLOSE</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

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

<!-- Modal T&C -->
<div class="modal modal-lg fade" id="term_and_conditions" tabindex="-1" aria-labelledby="term_and_conditionsLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-body">

        <div id="rules-regulations">
          <h2>Terms and Conditions for Use of <?= camelcase(GetProjectName()); ?>'s Akshaya Patra</h2>
          <ol>
            <li>
              Cancellation allowed online until 24 hours before pickup time. Cancellation email should be sent to customer and us. Customer has to call us to cancel within 24 hours of order pickup time. For some items, preparation starts at least 24 hours ahead. So, they have to call us to discuss cancellation within 24 hours of order pickup.
            </li>


        </div>
        <div class="modal-footer">
          <div class="row" style="width: 100%;">

            <div class="col-sm text-start" style="width: 50%;">
              <input type="button" name="next" class="btn btn-danger" style="width: 100px;height: 45px;border-radius: 5px !important;" id="cancel" value="Cancel" />
            </div>
            <div class="col-sm text-end" style="width: 50%;">
              <input type="button" name="next" class="btn btn-success" id="accept" style="width: 100px;height: 45px;background-color: #198754 !important;border-radius: 5px !important;" value="Accept" />

            </div>
          </div>



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

</div>

<!-- Live Client Id -->
<script>
  var addressLine1 = '<?php echo $addressLine1 ?>';
  var addressLine2 = '<?php echo $addressLine2 ?>';
  var address = addressLine1 + ', ' + addressLine2;
  var cityTypes = '<?php echo $cityTypes ?>';
  var county = '<?php echo $county ?>';
  var stateTypes = '<?php echo $stateTypes ?>';
  var zip = '<?php echo $zip ?>';
  $(document).ready(function() {

    $('input[name="delivery"]').on('change', function() {
      console.log("etKitchenTIp");
      if ($(this).val() === 'Delivery') {

        $('.hidden-div').css("display", "block");
      } else {
        $('.hidden-div').css("display", "none");
      }
    });

    $('input[name="Copyhomeadd"]').on('change', function() {
      if ($(this).val() === 'Yes') {
        // $('#stateSelect').change();
        $('#state').val(stateTypes).trigger('change');
        $("#address").val(address);
        // $("#address").attr("readonly", true);
        // $("#state").removeAttr("required");
        $("#address").attr("required", true);
        $("#city").attr("required", true);
        $("#state").attr("required", true);
        $("#zipcode").attr("required", true);
        // $("#city").val(cityTypes);
        // $("#city").attr("readonly", true);
        // $("#state").removeAttr("readonly");

        // $("#state").val(stateTypes);
        // $("#state").attr("readonly", true);
        // $("#state").removeAttr("required");

        $("#zipcode").val(zip);
        // $("#zipcode").attr("readonly", true);
        // $("#state").removeAttr("required");
      } else {
        $("#address").val('');
        $("#address").attr("required", true);
        // $("#address").removeAttr("readonly");

        $("#state").val('');
        $("#state").attr("required", true);
        // $("#state").removeAttr("readonly");

        $('#city').val('').trigger('change');
        $("#city").attr("required", true);
        // $("#city").removeAttr("readonly");



        $("#zipcode").val('');
        $("#zipcode").attr("required", true);
        // $("#zipcode").removeAttr("readonly");
      }
    });
  });

  $('#state').change(function() {

    var stateCode = $(this).val();
    $.ajax({
      url: "<?= base_url('admin/getCityByState') ?>",
      type: "POST",
      // dataType: "json",
      data: {
        'stateCode': stateCode
      },
      success: function(data) {
        $("#city").html(data);
      }
    });

  });
  $(document).ready(function() {
    let baseTotal = parseFloat($('#totalPrice').val()) || 0;
    let advanceAmt = parseFloat($('#advanceAmt').val()) || 0;

    // Only allow numbers and one decimal point during input
    $('#etKitchenTIp').on('input', function() {
      this.value = this.value
        .replace(/[^0-9.]/g, '') // Remove non-numeric and non-dot
        .replace(/^(\d*\.?\d{0,2}).*$/, '$1'); // Limit to 2 decimal places
    });

    // Format to 2 decimals and update total when user leaves the field
    $('#etKitchenTIp').on('blur', function() {
      let tip = parseFloat(this.value) || 0;
      this.value = tip.toFixed(2); // Format tip to 2 decimals
      let advanceAmtN = parseFloat($('#advanceAmtMain').val()) || 0;
      console.log("tip: "+tip);
      let totalPrice = baseTotal + tip;
      let newTotal = advanceAmtN + tip;

      $('#totalPrice').val(totalPrice.toFixed(2)); // hidden input
      $("#advanceAmt").val(newTotal.toFixed(2));
      // $("#advanceAmtMain").val(advanceAmtN);
      // $('#totalPriceH').html('<strong>Total: <?php echo $currencySymbol ?>' + newTotal.toFixed(2) + '</strong>'); // visible text
    });

    $(".datepicker").datepicker({
      dateFormat: 'mm/dd/yy', // Month/Day format
      changeMonth: true,
      changeYear: true, // Disable year change
      showButtonPanel: true,
      minDate: 0,

    });
    const weekOffDays = <?php echo json_encode($weekOffDayArr); ?>;
    const weekendDays = <?php echo json_encode($weekendDaysArr); ?>;

    const kitchenClosingWeekendTimeFrom = "<?php echo $kitchenClosingWeekendTimeFrom; ?>";
    const kitchenClosingWeekendTimeTo = "<?php echo $kitchenClosingWeekendTimeTo; ?>";

    const kitchenClosingWeekDayTimeFrom = "<?php echo $kitchenClosingWeekDayTimeFrom; ?>";
    const kitchenClosingWeekDayTimeTo = "<?php echo $kitchenClosingWeekDayTimeTo; ?>";

    const kitchenOpenTime = "<?php echo $kitchenOpenTime; ?>";
    const kitchenCloseTime = "<?php echo $KitchenCloseTime; ?>";

    /* $('#deliveryTimeInput').mdtimepicker();

    $("#deliveryTimeInput").off('timechanged').on('timechanged', function(e) {
      const selectedTime = e.time;
      if (!selectedTime) return;

      let selectedHour = 0,
        selectedMinute = 0;

      // Convert selectedTime to 24hr
      if (selectedTime.includes(" ")) {
        let [time, meridian] = selectedTime.split(" ");
        if (!meridian || !time) return;
        let [hh, mm] = time.split(":");
        hh = parseInt(hh);
        mm = parseInt(mm);

        if (meridian.toLowerCase() === 'pm' && hh !== 12) hh += 12;
        if (meridian.toLowerCase() === 'am' && hh === 12) hh = 0;
        selectedHour = hh;
        selectedMinute = mm;
      } else {
        let [hh, mm] = selectedTime.split(":");
        selectedHour = parseInt(hh);
        selectedMinute = parseInt(mm);
      }

      const selectedTotalMinutes = selectedHour * 60 + selectedMinute;

      // Selected date
      const selectedDate = new Date($('#deliveryDate').val());
      const today = new Date();

      const formatDate = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      const isToday = formatDate(selectedDate) === formatDate(today);

      // ✅ Check week off
      const dayIndex = selectedDate.getDay(); // 0=Sun, 6=Sat
      let customDayIndex = (dayIndex === 0 ? 7 : dayIndex);
      if (weekOffDays.includes(customDayIndex)) {
        swal({
          title: "Oops",
          text: "kiosk is closed today (Week Off).",
          type: "warning",
          confirmButtonText: 'OK',
          confirmButtonColor: 'var(--main-color-new-theme)',
        });

        $("#deliveryDate").val('');
        $("#deliveryTime").val('');
        return;
      }

      // ✅ Weekend or Weekday timings
      let minAllowed = convertTo24HourMinutes(kitchenOpenTime);
      let maxAllowed = convertTo24HourMinutes(kitchenCloseTime);
      let kitchenClosingWeekendTimeFromTime = convertTo24HourMinutes(kitchenClosingWeekendTimeFrom);
      let kitchenClosingWeekendTimeToTime = convertTo24HourMinutes(kitchenClosingWeekendTimeTo);
      let kitchenClosingWeekDayTimeFromTime = convertTo24HourMinutes(kitchenClosingWeekDayTimeFrom);
      let kitchenClosingWeekDayTimeToTime = convertTo24HourMinutes(kitchenClosingWeekDayTimeTo);

      // if (weekendDays.includes(customDayIndex)) {
      //   minAllowed = convertTo24HourMinutes(kitchenClosingWeekendTimeFrom);
      //   maxAllowed = convertTo24HourMinutes(kitchenClosingWeekendTimeTo);
      // } else {
      //   minAllowed = convertTo24HourMinutes(kitchenClosingWeekDayTimeFrom);
      //   maxAllowed = convertTo24HourMinutes(kitchenClosingWeekDayTimeTo);
      // }

      // ✅ Current day check
      if (isToday) {
        const now = new Date();
        const currentMinutes = now.getHours() * 60 + now.getMinutes();
        if (selectedTotalMinutes <= currentMinutes) {

          swal({
            title: "Oops",
            text: "Please select a time after the current time.",
            type: "warning",
            confirmButtonText: 'OK',
            confirmButtonColor: 'var(--main-color-new-theme)',
          });
          $("#deliveryTime").val('');
          return;
        }
      }

      // ✅ Final validation
      if (selectedTotalMinutes < minAllowed || selectedTotalMinutes > maxAllowed) {
        swal({
          title: "Oops",
          text: `Please select a time between ${formatTime(minAllowed)} and ${formatTime(maxAllowed)}.`,
          type: "warning",
          confirmButtonText: 'OK',
          confirmButtonColor: 'var(--main-color-new-theme)',
        });
        $("#deliveryTime").val('');
        return;
      } else if (
        weekendDays.includes(customDayIndex) &&
        (selectedTotalMinutes >= convertTo24HourMinutes(kitchenClosingWeekendTimeFromTime) &&
          selectedTotalMinutes <= convertTo24HourMinutes(kitchenClosingWeekendTimeToTime))
      ) {
        swal({
          title: "Oops",
          text: `On weekends, delivery/pickup time must be between ${kitchenClosingWeekendTimeFromTime} and ${kitchenClosingWeekendTimeToTime}.`,
          type: "warning",
          confirmButtonText: 'OK',
          confirmButtonColor: 'var(--main-color-new-theme)',
        });
        $("#deliveryTime").val('');
        return;
      } else if (
        (selectedTotalMinutes >= convertTo24HourMinutes(kitchenClosingWeekDayTimeFromTime) &&
          selectedTotalMinutes <= convertTo24HourMinutes(kitchenClosingWeekDayTimeToTime))
      ) {
        swal({
          title: "Oops",
          text: `On weekdays, delivery/pickup time must be between ${kitchenClosingWeekendTimeFrom} and ${kitchenClosingWeekDayTimeTo}.`,
          type: "warning",
          confirmButtonText: 'OK',
          confirmButtonColor: 'var(--main-color-new-theme)',
        });
        $("#deliveryTime").val('');
        return;
      }


    });
*/
    // Helper function: convert HH:MM AM/PM → total minutes
    function convertTo24HourMinutes(timeStr) {
      if (!timeStr) return 0;

      // अगर पहले से number है (minutes में)
      if (typeof timeStr === "number") {
        return timeStr;
      }

      // अगर string है तो ही split करो
      if (typeof timeStr === "string") {
        let [time, meridian] = timeStr.trim().split(" ");
        let [hh, mm] = time.split(":").map(Number);

        if (meridian) {
          if (meridian.toLowerCase() === "pm" && hh !== 12) hh += 12;
          if (meridian.toLowerCase() === "am" && hh === 12) hh = 0;
        }

        return hh * 60 + mm;
      }

      return 0;
    }


    // Helper: format minutes → hh:mm AM/PM
    function formatTime(totalMinutes) {
      let hh = Math.floor(totalMinutes / 60);
      let mm = totalMinutes % 60;
      let meridian = hh >= 12 ? "PM" : "AM";
      if (hh === 0) hh = 12;
      else if (hh > 12) hh -= 12;
      return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')} ${meridian}`;
    }




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


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

		<?php } ?>

		<?php if (@$CheckoutDonationSettings['generalDonation'] == 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 (@$CheckoutDonationSettings['acharyasanbhavana'] == 1) { ?>
				var acharyaValue = parseFloat($acharyaInput.val().replace(/[^\d.-]/g, '')) || 0;
			<?php } ?>
			<?php if (@$CheckoutDonationSettings['generalDonation'] == 1) { ?>
				var generalValue = parseFloat($generalInput.val().replace(/[^\d.-]/g, '')) || 0;
			<?php } ?>



			// Get the initial total price
			// var initialTotalPrice = parseFloat(<?= @$payNowTotalAmount; ?>) || 0;
			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));
		}

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


		<?php if (@$CheckoutDonationSettings['acharyasanbhavana'] == 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 (@$CheckoutDonationSettings['generalDonation'] == 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 } ?>

	});*/

  function AcharyaSambhavanaPriceFormate(element) {
    // Wrap element in jQuery to ensure it has jQuery functions like val()
    let $element = $(element);

    // Parse the input value as a float, apply toFixed(2), and set it back to the input
    let value = parseFloat($element.val());
    console.log(value);
    if (!isNaN(value)) {
      $element.val(value.toFixed(2));
    }
  }
</script>


<?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>



<!-- ==========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: 9999;"></div>

<?php $this->load->view('includes/script') ?>
<script>
  $(document).on('click', '.event-delete-row', function(e) {
    e.preventDefault();
    var row_id = $(this).data('row-id');
    var selected_date = $(this).data('selected-date');
    var current_row = $(this).closest('tr');
    var confirmDelete = confirm('Do you want to delete this service from your cart?');

    if (confirmDelete) {
      loader.on();
      $.ajax({
        url: '<?= base_url('AkshayPatra/delete_cart_row') ?>',
        method: 'POST',
        data: {
          row_id: row_id,
          selected_date: selected_date
        },
        dataType: 'json',
        success: function(response) {
          if (response.status == 'success') {
            current_row.remove();
            // var updated_amount = response.updated_amount;
            // $('#cart-amount').text(updated_amount);
            location.reload();
          }
        },
        error: function() {
          loader.off();
          alert('Error deleting cart row. Please try again.');
        }
      });
    }
  });


  function submitForm() {
    // ValidateCheckout();
    let isValid = true;
    let msg = '';
    let address = $("#address").val();
    let city = $("#city").val();
    let zipcode = $("#zipcode").val();
    let state = $("#state").val();
    let deliveryDate = $("#deliveryDate").val();
    let deliveryTime = $("#deliveryTime").val();
    let advanceAmt = $("#advanceAmt").val();
if(advanceAmt<=0){
isValid = false;
      msg = 'Please enter amount';
      $('[name="advanceAmt"]').first().focus();
}else if ($('[name="delivery"]:checked').length == 0) {
      isValid = false;
      msg = 'Please select Pickup/Delivery';
      $('[name="delivery"]').first().focus();
    } else {
      if (deliveryDate.length == 0) {
        isValid = false;
        msg = 'Please select Pickup Date';
        // msg = 'Please select Pickup/Delivery Date';
        $("#deliveryDate").focus();
      } else if (deliveryTime == null) {
        isValid = false;
        msg = 'Please select Pickup Time';
        // msg = 'Please select Pickup/Delivery Time';
        $("#deliveryTime").focus();
      } else if ($('[name="delivery"]:checked').val() == 'Delivery') {
        if (address.length == 0) {
          isValid = false;
          msg = 'Please fill address';
          $("#address").focus();
        } else if (city.length == 0) {
          isValid = false;
          msg = 'Please fill city';
          $("#city").focus();
        } else if (state.length == 0) {
          isValid = false;
          msg = 'Please fill state';
          $("#state").focus();
        } else if (zipcode.length == 0) {
          isValid = false;
          msg = 'Please fill zipcode';
          $("#zipcode").focus();
        }
      }
    }




    if (isValid) {
      $('#term_and_conditions').modal('show');


      $('#accept').click(function() {
        $('#term_and_conditions').modal('hide');
        loader.on();
        $.ajax({
          url: '<?php echo base_url('validate_akshaya_patra_checkout') ?>', // PHP file that checks profile
          method: 'POST',
          dataType: 'json',
          success: function(response) {
            if (!response) {
              loader.off();




              swal({
                title: "Oops",
                text: "Minimum order value must be $10!",
                type: "warning",
                confirmButtonText: 'OK',
                confirmButtonColor: 'var(--main-color-new-theme)',
              });
            } else {

              const formAction = "<?php echo $formAction ?>"; // Adjust this as needed
              if (formAction == "REQUEST WITH PAYMENT" || formAction == "BOOKING WITH PAYMENT") {
                loader.off();
             
                var amt = $("#totalPrice").val();
                var oldAmt = $("#totalPrice").val();
                var distAmt = 0;


                  var advanceAmt = parseFloat($("#advanceAmt").val());
        // var pendingAmount = totolAmt - advanceAmt;
        <?php
        if ($advanceUpdateAmt > 0) {
        ?>
          // var pendingAmount = 0;
          var advanceUpdateAmt = parseFloat(<?= @$advanceUpdateAmt; ?>)
        <?php } else {
        ?>
          // var pendingAmount = totolAmt - advanceAmt;
          var advanceUpdateAmt = advanceAmt;
        <?php
        }
        ?>


                var serviceName = 'Amount To Pay';
                console.log("serviceName: " + serviceName);
                $("#serviceNameedittable").html('<h4 id="serviceType">' + serviceName + '</h4><input type="hidden" name="" value="' + serviceName + '" id="serviceType">');
                $("#edittable").html('<h4 id="servicePrice">$ ' + parseFloat(advanceUpdateAmt).toFixed(2) + '</h4><input type="hidden" name="" value="' + advanceUpdateAmt + '" id="serviceAmt"><input type="hidden" name="" value="' + serviceName + '" id="serviceType">');
                if (oldAmt > amt) {
                  var distType = '( ' + <?php echo $membershipDiscount ?> + '% )';
                  if ('<?php echo $discountType ?>' == 'FLAT' || '<?php echo $discountType ?>' == 'SERVICE LEVEL') {
                    distType = '( $ ' + parseFloat(distAmt).toFixed(2) + ' )';
                  }
                  var newRow = '<div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;">Subtotal</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;" id="subtle"><?php echo $currencySymbol ?>&nbsp;' + parseFloat(oldAmt).toFixed(2) + '</span></div></div>'
                  newRow += '<hr><div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;font-size: 16px;color:#b00000;"> Membership Discount Applied ' + distType + '</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;color:#b00000;" id="subtle"><?php echo $currencySymbol ?>&nbsp;' + parseFloat(distAmt).toFixed(2) + '</span></div></div>';
                  newRow += '<hr><div class="row"><div class="col-md-6"><h5 class="mb-0" style="font-weight:bold!important;font-size: 20px!important;">Sale Total</h5></div><div class="col-md-6 text-end"><span style="font-weight:bold!important;color:#b00000;font-size: 20px!important;" id="subtle"><?php echo $currencySymbol ?>&nbsp;' + parseFloat(amt).toFixed(2) + '</span></div></div><hr>';

                  $("#serviceNameedittableBody").empty().append(newRow);
                }
                $("#membershipModal").modal("show");
              } else {
                // $("#addForm").submit();
                submitAddForm();
              }
            }
          }
        });
      });
    } else {
      $.notify(msg, 'error');
    }

  }

  $('#cancel').click(function() {

    $('#term_and_conditions').modal('hide');
  });
</script>

<?php

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

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



  <?php $mpiTokenPayId = @getclientInfoById()['data'][0]['MPItokenPay'];
  $MpiPayUrl               = base_url('MPI_Payments/Paynow');
  if (isset($mpiTokenPayId) && $mpiTokenPayId != '' && $paymentSetting == 'MPI') {
    $TokenPay = $mpiTokenPayId;
  ?>
    <script type="text/javascript" src="https://www.bridgepaynetsecuretx.com/Bridgepay.WebSecurity/TokenPay/js/tokenPay.js"></script>
  <?php
  } else {
    $TokenPay  = 'tokenpay10579api20211508121542285';
    $MpiPayUrl = base_url('MPI_Payments/PaynowTest');
  ?>
    <script type="text/javascript" src="https://www.bridgepaynetsecuretest.com/WebSecurity/TokenPay/js/tokenPay.js"></script>
  <?php
  }

  ?>
  <script>
    var tokenpay = TokenPay('<?php echo $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();

      const formAction = "<?php echo $formAction ?>";
      console.log("formAction");
      console.log(formAction);

      var formData1 = $("#addForm").serializeArray();
      console.log("Serialized Form Data:", formData1);
      let address = $("#address").val();
      let city = $("#city").val();
      let zipcode = $("#zipcode").val();
      let state = $("#state").val();
      let deliveryDate = $("#deliveryDate").val();
      let deliveryTime = $("#deliveryTime").val();
      let etKitchenTIp = $("#etKitchenTIp").val();
      let delivery = $('[name="delivery"]:checked').val();


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

        console.log(result);


        var totalPriceText = $("#totalPrice").val();
        var mpi_zipcode = $("#mpi_zipcode").val();
        var mpi_fname = $("#mpi_fname").val();
        var mpi_address = $("#address").val();

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

        var totolAmt = numericAmount;

        var advanceAmt = parseFloat($("#advanceAmt").val());
        var advanceAmtMain = parseFloat($("#advanceAmtMain").val());
        // var pendingAmount = totolAmt - advanceAmt;
        <?php
        if ($advanceUpdateAmt > 0) {
        ?>
          // var pendingAmount = 0;
          var advanceUpdateAmt = parseFloat(<?= @$advanceUpdateAmt; ?>)
        <?php } else {
        ?>
          // var pendingAmount = totolAmt - advanceAmt;
          var advanceUpdateAmt = advanceAmtMain;
        <?php
        }
        ?>
        if (result.status == 'auth_success') {


          var cart_data = '<?php echo json_encode($service_cart_items, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>';

          // console.log("cart_data");
          // console.log(cart_data);
          $.ajax({
            url: "<?php echo $MpiPayUrl ?>",
            type: "POST",
            dataType: "json",
            data: {
              'token': result.token,
              // 'totolAmt': totolAmt,
              'totolAmt': advanceUpdateAmt,
              'name': mpi_fname,
              'address': mpi_address,
              'zipcode': mpi_zipcode,
              'cart_data': cart_data
            },
            success: function(mpicardpayment_response) {

              console.log(mpicardpayment_response.data);
              // console.log(mpicardpayment_response.data[0].invoiceNo);
              var paymentSource = 'MPI';

              var status = 'TEMP';

              var totalPrice = totolAmt;




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

                // var status = 'COMPLETED';
                if (advanceAmtMain == totolAmt) {
                  status = 'COMPLETED';
                } else {
                  status = 'PARTIALLY_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: "<?php echo base_url('AkshayPatra/AddToCart') ?>",
                  type: "POST",
                  dataType: "json",
                  data: {

                    'status': status,
                    'paymentSource': paymentSource,
                    'paymentStatus': status,
                    'transaction_id': trnxId,
                    'totalPrice': totalPrice,
                    'etKitchenTIp': etKitchenTIp,
                    'acharya_sambhavana': 0,
                    'general_donation': 0,
                    'deliveryTime': deliveryTime,
                    'deliveryDate': deliveryDate,
                    'delivery': delivery,
                    'address': address,
                    'City': city,
                    'state': state,
                    'zipcode': zipcode,
                    formAction: formAction
                  },
                  success: function(addtocart_response) {

                    console.log(mpicardpayment_response);
                    // console.log(mpicardpayment_response.data[0].invoiceNo);

                    if (addtocart_response.statusCode == 1) {



                      // var status = 'COMPLETED';
                      var status = '';
                      if (advanceAmtMain == totolAmt) {
                        status = 'COMPLETED';
                      } else {
                        status = 'PARTIALLY_COMPLETED';
                      }
                      <?php
                      if ($advanceUpdateAmt > 0) {
                      ?>
                        var pendingAmount = 0;
                      <?php } else {
                      ?>
                        var pendingAmount = totolAmt - advanceAmtMain;
                      <?php
                      }
                      ?>
                      var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;

                      $.ajax({
                        url: "<?= base_url('AkshayPatra/updateTransactionStatus') ?>",
                        type: "POST",
                        dataType: "json",
                        data: {
                          'status': status,
                          'transaction_id': trnxId,
                          'paymentDescription': mpicardpayment_response,
                          'advanceAmount': advanceAmt,
                          'pendingAmount': pendingAmount,
                          'totalAmount': advanceAmt,
                        },
                        success: function(update_transactionstatus_response) {
                          if (update_transactionstatus_response.statusCode == 1) {


                            loader.off();
                            swal({
                                html: true,
                                title: "Payment Successfully Processed!",
                                text: "<span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + update_transactionstatus_response.envoiceNo + "</span>",
                                type: "success",
                                confirmButtonText: 'OK',
                                confirmButtonColor: 'var(--main-color-new-theme)',
                              },
                              function() {
                                // window.location.reload();
                                loader.on();
                                window.location.href = "<?php echo base_url() . 'akshaya-patra' ?>";


                              });

                          }

                        }
                      });



                    } else {
                      swal({
                          html: true,
                          title: "Something went wrong!",
                          text: "",
                          type: "error",
                          confirmButtonText: 'OK',
                          confirmButtonColor: 'var(--main-color-new-theme)',
                        },
                        function() {

                        });

                      loader.off();
                    }
                  }
                });

              } else {


                loader.off();

                swal({
                    html: true,
                    title: "Failed!",
                    text: "<span>" + mpicardpayment_response.message + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Receipt #: " + update_transactionstatus_response.envoiceNo + "</span>",
                    type: "error",
                    confirmButtonText: 'OK',
                    confirmButtonColor: 'var(--main-color-new-theme)',
                  },
                  function() {
                    loader.on();
                    window.location.reload();
                  });



              }

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

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




<?php } ?>

<script>
  function validateMinimumPay(inputElement) {
    // Get the current value, min, and max from the input element
    let value = parseFloat(inputElement.value);
    let minValue = parseFloat(inputElement.min);
    let maxValue = parseFloat($("#totalPrice").val());

    // Ensure the value has 2 decimal places, but only if it's not NaN
    if (!isNaN(value)) {
      value = parseFloat(value).toFixed(2);
    }

    // Check if the value is valid (not blank, within min and max range)
    if (isNaN(value) || value < minValue || value > maxValue || inputElement.value === "") {
      alert("Please enter a valid value between " + minValue.toFixed(2) + " and " + maxValue.toFixed(2));
      inputElement.value = ""; // Clear the input if invalid
      document.getElementById('paynowbtn').disabled = true; // Disable button
    } else {
      inputElement.value = value; // Set the value back with 2 decimal places
        $("#advanceAmtMain").val(value);
      document.getElementById('paynowbtn').disabled = false; // Enable button
    }
  }
</script>