<?php
require('connection.inc.php');
require('security.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);


if (!isset($_SESSION['user_id'])) {
    header("Location: log-in.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// Check if cart is empty
$sql = "SELECT COUNT(*) FROM cart WHERE user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($cartCount);
$stmt->fetch();
$stmt->close();

if ($cartCount == 0) {
    $_SESSION['error_message'] = "Your cart is empty. Please add items to the cart first.";
    header("Location: cart.php");
    exit;
}

// Get cart items
$sql = "SELECT 
            cart.id AS cart_id,
            cart.quantity,
            products.product_id,
            products.product_name,
            products.product_url_name,  
            (
                SELECT product_img 
                FROM product_imgs 
                WHERE product_imgs.product_id = products.product_id 
                AND deleted_at IS NULL 
                ORDER BY img_id ASC 
                LIMIT 1
            ) AS product_img,
            product_units.unit_id,
            product_units.unit_name,
            product_units.unit_price
        FROM cart
        JOIN products ON cart.product_id = products.product_id
        JOIN product_units ON cart.unit_id = product_units.unit_id
        WHERE cart.user_id = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
}

$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$cartItems = [];
$cartSubtotal = 0;

while ($row = $result->fetch_assoc()) {
    $cartItems[] = $row;
    $cartSubtotal += $row['unit_price'] * $row['quantity'];
}
$stmt->close();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $country = isset($_POST['country']) ? trim($_POST['country']) : '';
    $first_name = isset($_POST['first_name']) ? trim($_POST['first_name']) : '';
    $last_name = isset($_POST['last_name']) ? trim($_POST['last_name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';
    $state = isset($_POST['state']) ? trim($_POST['state']) : '';
    $postcode = isset($_POST['postcode']) ? trim($_POST['postcode']) : '';

    // Validate postcode
    if ($postcode === '') {
        $_SESSION['error_message'] = "Postcode is required.";
        header("Location: checkout.php");
        exit;
    }

    $apiResponse = @file_get_contents("https://api.postalpincode.in/pincode/$postcode");
    $pincodeData = json_decode($apiResponse, true);

    if (!$pincodeData || $pincodeData[0]['Status'] !== 'Success') {
        $_SESSION['error_message'] = "Invalid Pincode. Please go back and enter a valid one.";
        header("Location: checkout.php");
        exit;
    }

    // Generate order ID
    $prefix = "lovebri";
    $lastOrderQuery = "SELECT order_id FROM orders WHERE order_id LIKE ? ORDER BY id DESC LIMIT 1";
    $stmt = $conn->prepare($lastOrderQuery);
    $likeParam = $prefix . '%';
    $stmt->bind_param("s", $likeParam);
    $stmt->execute();
    $stmt->bind_result($last_order_id);
    $stmt->fetch();
    $stmt->close();

    $new_number = ($last_order_id) ? ((int) str_replace($prefix, '', $last_order_id)) + 1 : 1001;
    $order_id = $prefix . $new_number;

    // Insert order
    $stmt = $conn->prepare("INSERT INTO orders (order_id, user_id, first_name, last_name, email, phone, country, address, city, state, postcode, subtotal) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sisssssssssd", $order_id, $user_id, $first_name, $last_name, $email, $phone, $country, $address, $city, $state, $postcode, $cartSubtotal);
    if (!$stmt->execute()) {
        die("Order insert failed: " . $stmt->error);
    }
    $stmt->close();

    // Insert order items
    $stmt = $conn->prepare("SELECT cart.product_id, cart.unit_id, cart.quantity, product_units.unit_price FROM cart JOIN product_units ON cart.unit_id = product_units.unit_id WHERE cart.user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $product_id = $row['product_id'];
        $unit_id = $row['unit_id'];
        $quantity = $row['quantity'];
        $unit_price = $row['unit_price'];
        $total_price = $quantity * $unit_price;

        $stmt2 = $conn->prepare("INSERT INTO order_items (order_id, product_id, unit_id, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt2->bind_param("siiidd", $order_id, $product_id, $unit_id, $quantity, $unit_price, $total_price);
        $stmt2->execute();
        $stmt2->close();
    }
    $stmt->close();

    // Instamojo Payment Integration
    $api_key = "3e00176dda2a0930711d07988a634f4f";
    $auth_token = "8d8a37a3003f12e5f4a7b83ed78e8caa";
    $endpoint = "https://www.instamojo.com/api/1.1/payment-requests/";

    $payload = array(
        'purpose' => "Order $order_id",
        'amount' => $cartSubtotal,
        'buyer_name' => $first_name . ' ' . $last_name,
        'email' => $email,
        'phone' => $phone,
        'redirect_url' => "https://digitalcardwale.com/loveberi/payment-success.php?order_id=$order_id",
        'send_email' => true,
        'send_sms' => true,
        'allow_repeated_payments' => false
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "X-Api-Key:$api_key",
        "X-Auth-Token:$auth_token"
    ));

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        die("Curl error: " . curl_error($ch));
    }

    curl_close($ch);
    $result = json_decode($response, true);

    if (isset($result['success']) && $result['success'] == true) {
        // Clear cart after payment request success
        $stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $stmt->close();

        $payment_url = $result['payment_request']['longurl'];
        header("Location: $payment_url");
        exit;
    } else {
        echo "Payment initialization failed. Please try again later.";
        exit;
    }
}
?>


<!doctype html>
<html class="no-js" lang="zxx">
<head>
      <meta charset="utf-8">
      <meta http-equiv="x-ua-compatible" content="ie=edge">
      <title>Lovebri </title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <!-- Place favicon.ico in the root directory -->
      <link rel="shortcut icon" type="image/x-icon" href="assets/img/allnew/logo.png">

      <!-- CSS here -->
      <link rel="stylesheet" href="assets/css/bootstrap.min.css">
      <link rel="stylesheet" href="assets/css/animate.css">
      <link rel="stylesheet" href="assets/css/swiper-bundle.css">
      <link rel="stylesheet" href="assets/css/slick.css">
      <link rel="stylesheet" href="assets/css/magnific-popup.css">
      <link rel="stylesheet" href="assets/css/spacing.css">
      <link rel="stylesheet" href="assets/css/meanmenu.css">
      <link rel="stylesheet" href="assets/css/nice-select.css">
      <link rel="stylesheet" href="assets/css/fontawesome.min.css">
      <link rel="stylesheet" href="assets/css/icon-dukamarket.css">
      <link rel="stylesheet" href="assets/css/jquery-ui.css">
      <link rel="stylesheet" href="assets/css/main.css">
   </head>
   <body>


      <!-- Scroll-top -->
      <button class="scroll-top scroll-to-target" data-target="html">
         <i class="icon-chevrons-up"></i>
      </button>
      <!-- Scroll-top-end-->


      <!-- header-area-start -->
      <?php 
      include 'header.php'
      ?>
      <!-- header-area-end -->

      <main>
          

         <!-- breadcrumb-area-start -->
         <div class="breadcrumb__area pt-5 pb-5">
            <div class="container">
               <div class="row">
                  <div class="col-lg-12">
                     <div class="tp-breadcrumb__content">
                        <div class="tp-breadcrumb__list">
                           <span class="tp-breadcrumb__active"><a href="index.html">Home</a></span>
                           <span class="dvdr">/</span>
                           <span>Checkout</span>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <!-- breadcrumb-area-end -->

         <!-- coupon-area start -->
         <!-- <section class="coupon-area pt-10 pb-30">
            <div class="container">
            <div class="row">
               <div class="col-md-6">
                  <div class="coupon-accordion">
                        <h3>Returning customer? <span id="showlogin">Click here to login</span></h3>
                        <div id="checkout-login" class="coupon-content">
                           <div class="coupon-info">
                              <p class="coupon-text">Quisque gravida turpis sit amet nulla posuere lacinia. Cras sed est
                                    sit amet ipsum luctus.</p>
                              <form action="#">
                                    <p class="form-row-first">
                                       <label>Username or email <span class="required">*</span></label>
                                       <input type="text" >
                                    </p>
                                    <p class="form-row-last">
                                       <label>Password <span class="required">*</span></label>
                                       <input type="text">
                                    </p>
                                    <p class="form-row">
                                       <button class="tp-btn tp-color-btn" type="submit">Login</button>
                                       <label>
                                          <input type="checkbox">
                                          Remember me
                                       </label>
                                    </p>
                                    <p class="lost-password">
                                       <a href="#">Lost your password?</a>
                                    </p>
                              </form>
                           </div>
                        </div>
                  </div>
               </div>
               <div class="col-md-6">
                  <div class="coupon-accordion">
                      
                        <h3>Have a coupon? <span id="showcoupon">Click here to enter your code</span></h3>
                        <div id="checkout_coupon" class="coupon-checkout-content">
                           <div class="coupon-info">
                              <form action="#">
                                    <p class="checkout-coupon">
                                       <input type="text" placeholder="Coupon Code">
                                       <button class="tp-btn tp-color-btn" type="submit">Apply Coupon</button>
                                    </p>
                              </form>
                           </div>
                        </div>
                      
                  </div>
               </div>
            </div>
            </div>
         </section> -->
      <?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger"><?= $_SESSION['error_message']; unset($_SESSION['error_message']); ?></div>
<?php endif; ?>


         <!-- checkout-area start -->
         <section class="checkout-area pb-50">
            <div class="container">
               <form action="#" method="post">
                  <div class="row">
                        <div class="col-lg-6 col-md-12">
                           <div class="checkbox-form">
                              <h3>Billing Details</h3>
                              <div class="row">
                                    <div class="col-md-12">
                                       <div class="country-select">
                                          <label>Country <span class="required">*</span></label>
                                          <label for="country">Select Country:</label>
                                             <input list="countries" id="country" name="country" class="form-select" placeholder="Start typing a country..." required>
                                             <datalist id="countries">
                                             <option value="Afghanistan">
                                             <option value="Albania">
                                             <option value="Algeria">
                                             <option value="Andorra">
                                             <option value="Angola">
                                             <option value="Antigua and Barbuda">
                                             <option value="Argentina">
                                             <option value="Armenia">
                                             <option value="Australia">
                                             <option value="Austria">
                                             <option value="Azerbaijan">
                                             <option value="Bahamas">
                                             <option value="Bahrain">
                                             <option value="Bangladesh">
                                             <option value="Barbados">
                                             <option value="Belarus">
                                             <option value="Belgium">
                                             <option value="Belize">
                                             <option value="Benin">
                                             <option value="Bhutan">
                                             <option value="Bolivia">
                                             <option value="Bosnia and Herzegovina">
                                             <option value="Botswana">
                                             <option value="Brazil">
                                             <option value="Brunei">
                                             <option value="Bulgaria">
                                             <option value="Burkina Faso">
                                             <option value="Burundi">
                                             <option value="Cabo Verde">
                                             <option value="Cambodia">
                                             <option value="Cameroon">
                                             <option value="Canada">
                                             <option value="Central African Republic">
                                             <option value="Chad">
                                             <option value="Chile">
                                             <option value="China">
                                             <option value="Colombia">
                                             <option value="Comoros">
                                             <option value="Congo (Congo-Brazzaville)">
                                             <option value="Costa Rica">
                                             <option value="Croatia">
                                             <option value="Cuba">
                                             <option value="Cyprus">
                                             <option value="Czech Republic">
                                             <option value="Democratic Republic of the Congo">
                                             <option value="Denmark">
                                             <option value="Djibouti">
                                             <option value="Dominica">
                                             <option value="Dominican Republic">
                                             <option value="Ecuador">
                                             <option value="Egypt">
                                             <option value="El Salvador">
                                             <option value="Equatorial Guinea">
                                             <option value="Eritrea">
                                             <option value="Estonia">
                                             <option value="Eswatini">
                                             <option value="Ethiopia">
                                             <option value="Fiji">
                                             <option value="Finland">
                                             <option value="France">
                                             <option value="Gabon">
                                             <option value="Gambia">
                                             <option value="Georgia">
                                             <option value="Germany">
                                             <option value="Ghana">
                                             <option value="Greece">
                                             <option value="Grenada">
                                             <option value="Guatemala">
                                             <option value="Guinea">
                                             <option value="Guinea-Bissau">
                                             <option value="Guyana">
                                             <option value="Haiti">
                                             <option value="Honduras">
                                             <option value="Hungary">
                                             <option value="Iceland">
                                             <option value="India">
                                             <option value="Indonesia">
                                             <option value="Iran">
                                             <option value="Iraq">
                                             <option value="Ireland">
                                             <option value="Israel">
                                             <option value="Italy">
                                             <option value="Ivory Coast">
                                             <option value="Jamaica">
                                             <option value="Japan">
                                             <option value="Jordan">
                                             <option value="Kazakhstan">
                                             <option value="Kenya">
                                             <option value="Kiribati">
                                             <option value="Kuwait">
                                             <option value="Kyrgyzstan">
                                             <option value="Laos">
                                             <option value="Latvia">
                                             <option value="Lebanon">
                                             <option value="Lesotho">
                                             <option value="Liberia">
                                             <option value="Libya">
                                             <option value="Liechtenstein">
                                             <option value="Lithuania">
                                             <option value="Luxembourg">
                                             <option value="Madagascar">
                                             <option value="Malawi">
                                             <option value="Malaysia">
                                             <option value="Maldives">
                                             <option value="Mali">
                                             <option value="Malta">
                                             <option value="Marshall Islands">
                                             <option value="Mauritania">
                                             <option value="Mauritius">
                                             <option value="Mexico">
                                             <option value="Micronesia">
                                             <option value="Moldova">
                                             <option value="Monaco">
                                             <option value="Mongolia">
                                             <option value="Montenegro">
                                             <option value="Morocco">
                                             <option value="Mozambique">
                                             <option value="Myanmar">
                                             <option value="Namibia">
                                             <option value="Nauru">
                                             <option value="Nepal">
                                             <option value="Netherlands">
                                             <option value="New Zealand">
                                             <option value="Nicaragua">
                                             <option value="Niger">
                                             <option value="Nigeria">
                                             <option value="North Korea">
                                             <option value="North Macedonia">
                                             <option value="Norway">
                                             <option value="Oman">
                                             <option value="Pakistan">
                                             <option value="Palau">
                                             <option value="Palestine State">
                                             <option value="Panama">
                                             <option value="Papua New Guinea">
                                             <option value="Paraguay">
                                             <option value="Peru">
                                             <option value="Philippines">
                                             <option value="Poland">
                                             <option value="Portugal">
                                             <option value="Qatar">
                                             <option value="Romania">
                                             <option value="Russia">
                                             <option value="Rwanda">
                                             <option value="Saint Kitts and Nevis">
                                             <option value="Saint Lucia">
                                             <option value="Saint Vincent and the Grenadines">
                                             <option value="Samoa">
                                             <option value="San Marino">
                                             <option value="Sao Tome and Principe">
                                             <option value="Saudi Arabia">
                                             <option value="Senegal">
                                             <option value="Serbia">
                                             <option value="Seychelles">
                                             <option value="Sierra Leone">
                                             <option value="Singapore">
                                             <option value="Slovakia">
                                             <option value="Slovenia">
                                             <option value="Solomon Islands">
                                             <option value="Somalia">
                                             <option value="South Africa">
                                             <option value="South Korea">
                                             <option value="South Sudan">
                                             <option value="Spain">
                                             <option value="Sri Lanka">
                                             <option value="Sudan">
                                             <option value="Suriname">
                                             <option value="Sweden">
                                             <option value="Switzerland">
                                             <option value="Syria">
                                             <option value="Tajikistan">
                                             <option value="Tanzania">
                                             <option value="Thailand">
                                             <option value="Timor-Leste">
                                             <option value="Togo">
                                             <option value="Tonga">
                                             <option value="Trinidad and Tobago">
                                             <option value="Tunisia">
                                             <option value="Turkey">
                                             <option value="Turkmenistan">
                                             <option value="Tuvalu">
                                             <option value="Uganda">
                                             <option value="Ukraine">
                                             <option value="United Arab Emirates">
                                             <option value="United Kingdom">
                                             <option value="United States">
                                             <option value="Uruguay">
                                             <option value="Uzbekistan">
                                             <option value="Vanuatu">
                                             <option value="Vatican City">
                                             <option value="Venezuela">
                                             <option value="Vietnam">
                                             <option value="Yemen">
                                             <option value="Zambia">
                                             <option value="Zimbabwe">
                                             </datalist>

                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>First Name <span class="required">*</span></label>
                                          <input type="text" name="first_name" placeholder="" required>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>Last Name <span class="required">*</span></label>
                                          <input type="text" name="last_name" placeholder="" required>
                                       </div>
                                    </div>
                                 
                                    <div class="col-md-12">
                                       <div class="checkout-form-list">
                                          <label>Address <span class="required">*</span></label>
                                          <input type="text" name="address"  placeholder="Street address" required>
                                       </div>
                                    </div>
                                    <div class="col-md-12">
                                       <div class="checkout-form-list">
                                          <input type="text" name="" placeholder="Apartment, suite, unit etc. (optional)" >
                                       </div>
                                    </div>

                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>Postcode / Zip <span class="required">*</span></label>
                                          <input type="text" name="postcode" id="postal_code" placeholder="Postcode / Zip" required>
                                       </div>
                                    </div>  
                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>Town / City <span class="required">*</span></label>
                                          <input type="text" name="city" id="city" placeholder="Town / City" required>
                                       </div>
                                    </div>


                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>State <span class="required">*</span></label>
                                          <input type="text" name="state" id="state" placeholder="" required>
                                       </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>Email Address <span class="required">*</span></label>
                                          <input type="email" name="email" placeholder="" required>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="checkout-form-list">
                                          <label>Phone <span class="required">*</span></label>
                                          <input type="text" name="phone" placeholder="Phone" required>
                                       </div>
                                    </div>
                              </div>
                           </div>
                        </div>
                        <div class="col-lg-6 col-md-12">
                           <div class="your-order mb-30 ">
                              <h3>Your order</h3>
                              <div class="your-order-table table-responsive">
                                    <table>
                                       <thead>
                                          <tr>
                                             <th class="product-name">Product</th>
                                             <th class="product-total">Total</th>
                                          </tr>
                                       </thead>
                                       <tbody>
                                          <?php
                                          $subtotal = 0;
                                          $stmt = $conn->prepare($sql);
                                          $stmt->bind_param("i", $user_id); // Make sure $user_id is defined
                                          $stmt->execute();
                                          $result = $stmt->get_result();
                                          while ($row = $result->fetch_assoc()):
                                             $product_name = $row['product_name'];
                                             $quantity = $row['quantity'];
                                             $unit_price = $row['unit_price'];
                                             $total_price = $quantity * $unit_price;
                                             $subtotal += $total_price;
                                          ?>
                                          <tr class="cart_item">
                                             <td class="product-name">
                                                <?php echo htmlspecialchars($product_name); ?>
                                                <strong class="product-quantity"> × <?php echo $quantity; ?></strong>
                                             </td>
                                             <td class="product-total">
                                                <span class="amount">₹<?php echo number_format($total_price, 2); ?></span>
                                             </td>
                                          </tr>
                                          <?php endwhile; ?>
                                       </tbody>

                                       <tfoot>
                                          <tr class="cart-subtotal">
                                                <th>Cart Subtotal</th>
                                                <td><span class="amount">₹<?php echo number_format($cartSubtotal, 2); ?></span></td>
                                          </tr>
                                          <tr class="shipping">
                                                <th>Shipping</th>
                                                <td>
                                                   <ul>
                                                   
                                                      <li>
                                                            <label>Free Shipping</label>
                                                      </li>
                                                   </ul>
                                                </td>
                                          </tr>
                                          <tr class="order-total">
                                                <th>Order Total</th>
                                                <td><strong><span class="amount">₹<?php echo number_format($cartSubtotal, 2); ?></span></strong>
                                                </td>
                                          </tr>
                                       </tfoot>
                                    </table>
                              </div>
                              <div class="payment-method">
                                 <div class="accordion" id="checkoutAccordion">
                                    <div class="accordion-item">
                                       <h2 class="accordion-header" id="checkoutOne">
                                          <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#bankOne" aria-expanded="true" aria-controls="bankOne">
                                          Direct Bank Transfer
                                          </button>
                                       </h2>
                                       <div id="bankOne" class="accordion-collapse collapse show" aria-labelledby="checkoutOne" data-bs-parent="#checkoutAccordion">
                                          <div class="accordion-body">
                                          Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order won’t be shipped until the funds have cleared in our account.
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="order-button-payment mt-20">
                                    <button type="submit" class="tp-btn tp-color-btn w-100 banner-animation">Place order</button>
                                 </div>
                              </div>
                           </div>
                        </div>
                  </div>
               </form>
            </div>
         </section>
         <!-- checkout-area end -->

       <?php 
       include 'footer.php'
       ?>
      </main>
      
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
          <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        
        
    let isPincodeValid = false;

    $(document).ready(function () {
        $('#postal_code').on('keyup', function () {
            let pincode = $(this).val();

            if (pincode.length === 6) {
                $.ajax({
                    url: `https://api.postalpincode.in/pincode/${pincode}`,
                    method: 'GET',
                    success: function (data) {
                        if (data[0].Status === "Success") {
                            let postOffice = data[0].PostOffice[0];
                            $('#city').val(postOffice.District);
                            $('#state').val(postOffice.State);
                            isPincodeValid = true;
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Invalid Pincode',
                                text: 'No data found for this pincode.'
                            });
                            $('#city').val('');
                            $('#state').val('');
                            isPincodeValid = false;
                        }
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: 'Something went wrong while fetching city and state!'
                        });
                        isPincodeValid = false;
                    }
                });
            } else {
                isPincodeValid = false;
                $('#city').val('');
                $('#state').val('');
            }
        });

        $('form').on('submit', function (e) {
            if (!isPincodeValid) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Pincode',
                    text: 'Please enter a valid 6-digit pincode and wait for city/state autofill.'
                });
            }
        });
    });
</script>

    

      <!-- JS here -->
      <script src="assets/js/jquery.js"></script>
      <script src="assets/js/waypoints.js"></script>
      <script src="assets/js/bootstrap.bundle.min.js"></script>
      <script src="assets/js/swiper-bundle.js"></script>
      <script src="assets/js/nice-select.js"></script>
      <script src="assets/js/slick.js"></script>
      <script src="assets/js/magnific-popup.js"></script>
      <script src="assets/js/counterup.js"></script>
      <script src="assets/js/wow.js"></script>
      <script src="assets/js/isotope-pkgd.js"></script>
      <script src="assets/js/imagesloaded-pkgd.js"></script>
      <script src="assets/js/countdown.js"></script>
      <script src="assets/js/ajax-form.js"></script>
      <script src="assets/js/jquery-ui.js"></script>
      <script src="assets/js/meanmenu.js"></script>
      <script src="assets/js/main.js"></script>
   </body>
</html>
