<?php
session_start();
error_reporting(0);
include('includes/config.php');
include_once('includes/settings.php');
if (isset($_POST['submit'])) {
  if (!empty($_SESSION['cart'])) {
    foreach ($_POST['quantity'] as $key => $val) {
      if ($val == 0) {
        unset($_SESSION['cart'][$key]);
      } else {
        $_SESSION['cart'][$key]['quantity'] = $val;

      }
    }
    echo "<script>alert('Your Cart has been Updated');</script>";
  }
}
// Code for Remove a Product from Cart
if (isset($_POST['remove_code'])) {

  if (!empty($_SESSION['cart'])) {
    foreach ($_POST['remove_code'] as $key) {

      unset($_SESSION['cart'][$key]);
    }
    echo "<script>alert('Your Cart has been Updated');</script>";
  }
}
// code for insert product in order table
if (isset($_POST['ordersubmit'])) {
  if (strlen($_SESSION['login']) == 0) {
    header('location:login.php');
  } else {
    if (!empty($_SESSION['cart'])) {
      $uid = $_SESSION['id'];

      // Validation Check: Fetch user details for address verification
      $ud_check = mysqli_query($con, "SELECT * FROM user_details WHERE user_id='$uid'");
      $ud_data = mysqli_fetch_array($ud_check);

      $is_same_as_billing = (isset($_POST['same_as_billing_val']) && $_POST['same_as_billing_val'] == "1") || ($ud_data['ship_same_as_billing'] == 1);

      $billing_incomplete = empty($ud_data['billingAddress']) || empty($ud_data['billingCity']) || empty($ud_data['billingState']);
      $shipping_incomplete = !$is_same_as_billing && (empty($ud_data['shippingAddress']) || empty($ud_data['shippingCity']) || empty($ud_data['shippingState']));

      if ($billing_incomplete || $shipping_incomplete) {
        echo "<script>alert('Error: Please complete and SAVE your Billing and Shipping addresses before proceeding. If using a unique shipping address, ensure all fields are filled and updated.'); window.location.href='my-cart.php';</script>";
        exit();
      }

      // Clear any previous incomplete orders to prevent duplicates
      mysqli_query($con, "DELETE FROM orders WHERE userId='$uid' AND paymentMethod IS NULL");

      // Check if "same as billing" was selected (passed from hidden input synchronized by JS)
      if (isset($_POST['same_as_billing_val']) && $_POST['same_as_billing_val'] == "1") {
        // Sync shipping with billing in DB - use user_details table
        mysqli_query($con, "UPDATE user_details SET 
            shippingAddress = billingAddress,
            shippingCity = billingCity,
            shippingState = billingState,
            shippingPincode = billingPincode
            WHERE user_id = '$uid'");
      }

      foreach ($_SESSION['cart'] as $productId => $details) {
        $qty = $details['quantity'];
        mysqli_query($con, "insert into orders(userId,productId,quantity) values('$uid','$productId','$qty')");
      }
      header('location:checkout.php');
      exit();
    }
  }
}

?>

<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>
<style>
  /* Base Cart Styles - Reset any conflicts */
  .cart-card,
  .summary-card,
  .address-card {
    background: #fff;
    border: 1px solid #eee;
    border-radius: 8px;
    margin-bottom: 20px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  }

  .cart-card-header,
  .summary-card-header,
  .address-card-header {
    background: #fafafa;
    border-bottom: 1px solid #eee;
    padding: 15px 20px;
  }

  .cart-card-header h5,
  .summary-card-header h6,
  .address-card-header h6 {
    margin: 0;
    font-weight: 700;
    color: #282828;
  }

  .cart-card-body {
    padding: 0;
  }

  .cart-card-footer {
    padding: 15px 20px;
    background: #fafafa;
    border-top: 1px solid #eee;
  }

  /* Summary & Address Body */
  .summary-card-body,
  .address-card-body {
    padding: 20px;
  }

  .summary-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
  }

  .summary-total {
    font-size: 16px;
    font-weight: 700;
    color: #282828;
    padding-top: 10px;
    border-top: 1px solid #eee;
    margin-top: 10px;
  }

  /* Cart Items */
  .cart-item {
    display: flex !important;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    gap: 15px;
    transition: background 0.2s;
  }

  .cart-item:hover {
    background: #fafafa;
  }

  .cart-item:last-child {
    border-bottom: none;
  }

  .cart-item-checkbox {
    flex-shrink: 0;
  }

  .cart-checkbox {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }

  .cart-item-image {
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    border: 1px solid #eee;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    overflow: hidden;
  }

  .cart-item-image img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .cart-item-details {
    flex: 1;
    min-width: 0;
  }

  .cart-item-name {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 4px;
  }

  .cart-item-name a {
    color: #282828 !important;
    text-decoration: none !important;
  }

  .cart-item-name a:hover {
    color: var(--am-primary, #E8663D) !important;
  }

  .cart-item-meta {
    font-size: 12px;
    color: #888;
    margin-bottom: 5px;
  }

  .cart-item-price {
    margin-bottom: 0;
  }

  .cart-unit-price {
    font-size: 15px;
    font-weight: 600;
    color: #282828;
  }

  .cart-item-quantity {
    flex-shrink: 0;
    text-align: center;
  }

  .cart-item-total {
    flex-shrink: 0;
    text-align: right;
    min-width: 100px;
  }

  .qty-selector {
    display: inline-flex;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
  }

  .qty-btn {
    width: 32px;
    height: 32px;
    border: none;
    background: #f5f5f5;
    cursor: pointer;
    font-size: 16px;
  }

  .qty-btn:hover {
    background: #e0e0e0;
  }

  .qty-input {
    width: 45px;
    height: 32px;
    border: none;
    text-align: center;
    font-weight: 600;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
  }

  .cart-subtotal {
    font-size: 16px;
    font-weight: 600;
    color: #282828;
  }

  /* Checkout Button */
  .btn-checkout {
    background: var(--am-primary, #E8663D) !important;
    border: none !important;
    color: #fff !important;
    width: 100%;
    padding: 12px !important;
    font-weight: 700 !important;
    border-radius: 4px !important;
    transition: all 0.3s;
  }

  .btn-checkout:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(232, 102, 61, 0.3);
  }

  /* Address Toggles */
  .address-toggle-btn {
    width: 100%;
    text-align: left;
    border: none;
    background: none;
    font-weight: 700;
    color: #282828;
    padding: 0;
    font-size: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
  }

  .toggle-icon {
    font-size: 12px;
    color: #aaa;
    transition: transform 0.3s;
  }

  .address-toggle-btn[aria-expanded="true"] .toggle-icon {
    transform: rotate(180deg);
  }

  /* Empty Cart */
  .empty-cart-container {
    text-align: center;
    padding: 60px 20px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #eee;
  }

  .empty-cart-icon {
    font-size: 60px;
    color: #ddd;
    margin-bottom: 20px;
  }

  .empty-cart-container h4 {
    color: #282828;
    margin-bottom: 10px;
  }

  /* Responsive */
  @media (max-width: 991px) {
    .cart-left-col {
      margin-bottom: 20px;
    }
  }

  @media (max-width: 767px) {
    .cart-card-header h5 {
      font-size: 18px;
    }

    .cart-item {
      flex-direction: column;
      align-items: flex-start;
      padding: 16px;
      gap: 12px;
    }

    .cart-item-checkbox {
      position: absolute;
      left: 16px;
      top: 16px;
    }

    .cart-item-image {
      width: 80px;
      height: 80px;
      margin-left: 30px;
    }

    .cart-item-details {
      width: 100%;
      padding-left: 30px;
    }

    .cart-item-name {
      font-size: 14px;
      margin-bottom: 6px;
    }

    .cart-unit-price {
      font-size: 16px;
      font-weight: 700;
    }

    .cart-item-quantity {
      width: 100%;
      padding-left: 30px;
      margin-top: 12px;
    }

    .cart-item-quantity label {
      display: inline-block;
      margin-right: 10px;
      margin-bottom: 0;
      font-weight: 600;
    }

    .qty-selector {
      display: inline-flex;
    }

    .cart-item-total {
      display: none;
      /* Hide subtotal on mobile */
    }

    /* Summary card adjustments */
    .summary-card,
    .address-card {
      margin-bottom: 15px;
    }

    .summary-card-header h6,
    .address-card-header h6 {
      font-size: 15px;
    }

    /* Button adjustments */
    .cart-card-footer {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .cart-card-footer .btn {
      width: 100%;
      margin: 0 !important;
    }
  }

  @media (max-width: 576px) {
    .cart-item {
      padding: 14px;
    }

    .cart-item-checkbox {
      left: 14px;
      top: 14px;
    }

    .cart-item-image {
      width: 70px;
      height: 70px;
    }

    .cart-item-name {
      font-size: 13px;
    }

    .cart-unit-price {
      font-size: 15px;
    }

    .qty-selector {
      width: 100%;
      justify-content: center;
    }

    .qty-input {
      width: 60px;
    }
  }
</style>


<body class="cnt-home">

  <!-- HEADER -->
  <header class="header-style-1">
    <?php include('includes/top-header.php'); ?>
    <?php include('includes/main-header.php'); ?>
    <?php include('includes/menu-bar.php'); ?>
  </header>

  <!-- Breadcrumb -->
  <div class="breadcrumb mt-2">
    <div class="container">
      <div class="breadcrumb-inner">
        <nav aria-label="breadcrumb">
          <ul class="breadcrumb list-inline list-unstyled">
            <li><a href="index.php">Home</a></li>
            <li class='active'>Shopping Cart</li>
          </ul>
        </nav>
      </div>
    </div>
  </div>

  <div class="body-content outer-top-xs">
    <div class="container">
      <?php if (!empty($_SESSION['cart'])) { ?>

        <!-- Cart Items Section -->
        <div class="row">
          <div class="col-lg-8 cart-left-col mb-4">
            <div class="cart-card">
              <div class="cart-card-header">
                <h5 class="mb-0"><i class="fa fa-shopping-cart me-2"></i> Shopping Cart
                  (<?php echo count($_SESSION['cart']); ?> items)</h5>
              </div>
              <div class="cart-card-body">
                <?php
                $pdtid = array();
                $sql = "SELECT * FROM products WHERE id IN(" . implode(',', array_keys($_SESSION['cart'])) . ") ORDER BY id ASC";
                $query = mysqli_query($con, $sql);
                $totalprice = 0;
                $totalqunty = 0;


                while ($row = mysqli_fetch_array($query)) {
                  $quantity = $_SESSION['cart'][$row['id']]['quantity'];
                  $subtotal = $quantity * $row['productPrice'];
                  $totalprice += $subtotal;
                  $_SESSION['qnty'] = $totalqunty += $quantity;
                  array_push($pdtid, $row['id']);
                  ?>
                  <div class="cart-item">
                    <div class="cart-item-checkbox">
                      <input type="checkbox" name="remove_code[]" value="<?php echo $row['id']; ?>" class="cart-checkbox">
                    </div>
                    <div class="cart-item-image">
                      <a href="product-details.php?pid=<?php echo $row['id']; ?>">
                        <img src="__admin__/productimages/<?php echo $row['id']; ?>/<?php echo $row['productImage1']; ?>"
                          alt="<?php echo $row['productName']; ?>" onerror="this.src='assets/images/blank.gif'">
                      </a>
                    </div>
                    <div class="cart-item-details">
                      <h6 class="cart-item-name">
                        <a href="product-details.php?pid=<?php echo $row['id']; ?>"><?php echo $row['productName']; ?></a>
                      </h6>
                      <p class="cart-item-meta">
                        <small class="text-muted">
                          <?php
                          $reviews = mysqli_num_rows(mysqli_query($con, "SELECT * FROM productreviews WHERE productId='{$row['id']}'"));
                          if ($reviews > 0) {
                            echo '<i class="fa fa-star text-warning"></i> ' . $reviews . ' reviews';
                          }
                          ?>
                        </small>
                      </p>
                      <p class="cart-item-price">
                        <strong class="cart-unit-price">Ghs.
                          <?php echo number_format($row['productPrice'], 2); ?></strong>

                      </p>
                    </div>
                    <div class="cart-item-quantity">
                      <label class="small text-muted d-block mb-1">Quantity</label>
                      <div class="qty-selector">
                        <button type="button" class="qty-btn" onclick="decrementQty(<?php echo $row['id']; ?>)">-</button>
                        <input type="number" name="quantity[<?php echo $row['id']; ?>]" id="qty-<?php echo $row['id']; ?>"
                          value="<?php echo $quantity; ?>" min="1" class="qty-input">
                        <button type="button" class="qty-btn" onclick="incrementQty(<?php echo $row['id']; ?>)">+</button>
                      </div>
                    </div>
                    <div class="cart-item-total">
                      <label class="small text-muted d-block mb-1">Subtotal</label>
                      <strong class="cart-subtotal" id="subtotal-<?php echo $row['id']; ?>">Ghs.
                        <?php echo number_format($subtotal, 2); ?></strong>
                    </div>
                  </div>
                <?php }
                $_SESSION['pid'] = $pdtid; ?>
              </div>
              <div class="cart-card-footer">
                <button type="button" onclick="removeSelectedItems()" class="btn btn-outline-danger btn-sm">
                  <i class="fa fa-trash-o me-1"></i> Remove Selected
                </button>
                <a href="shop.php" class="btn btn-outline-secondary btn-sm ms-2">
                  <i class="fa fa-arrow-left me-1"></i> Continue Shopping
                </a>
              </div>

            </div>
          </div>

          <!-- Order Summary & Address -->
          <div class="col-lg-4">
            <!-- Order Summary -->
            <div class="summary-card mb-4">
              <div class="summary-card-header">
                <h6 class="mb-0"><i class="fa fa-file-text-o me-2"></i> Order Summary</h6>
              </div>
              <div class="summary-card-body">
                <div class="summary-row">
                  <span id="summary-items-count">Subtotal (<?php echo $totalqunty; ?> items)</span>
                  <span id="summary-subtotal-price">Ghs. <?php echo number_format($totalprice, 2); ?></span>
                </div>
                <div class="summary-row summary-total">
                  <span>Grand Total</span>
                  <strong id="summary-grand-total">Ghs.
                    <?php
                    $grand_total = $totalprice;
                    echo $_SESSION['tp'] = number_format($grand_total, 2);
                    ?></strong>
                </div>
                <form method="post">
                  <input type="hidden" name="same_as_billing_val" id="same_as_billing_val" value="0">
                  <button type="submit" name="ordersubmit" class="btn btn-checkout">
                    <i class="fa fa-lock me-2"></i> Proceed to Checkout
                  </button>
                </form>
                <p class="text-center text-muted mt-2 small mb-0">
                  <i class="fa fa-shield me-1"></i> Safe & Secure Payment
                </p>
              </div>
            </div>

            <!-- Billing Address -->
            <?php
            $row = mysqli_fetch_array(mysqli_query($con, "SELECT ud.* FROM users u LEFT JOIN user_details ud ON u.id = ud.user_id WHERE u.id='{$_SESSION['id']}'"));
            $states_res = mysqli_query($con, "SELECT * FROM states ORDER BY state_name ASC");
            $states = [];
            while ($s = mysqli_fetch_array($states_res)) {
              $states[] = $s;
            }
            ?>
            <div class="address-card mb-3">
              <div class="address-card-header">
                <button class="address-toggle-btn" type="button" data-bs-toggle="collapse"
                  data-bs-target="#billingAddressCollapse" aria-expanded="false">
                  <i class="fa fa-map-marker me-2"></i> Billing Address
                  <i class="fa fa-chevron-down float-end toggle-icon"></i>
                </button>
              </div>
              <div class="collapse" id="billingAddressCollapse">
                <div class="address-card-body">
                  <form id="billing-form">
                    <div class="form-group mb-3">
                      <label class="form-label small">Street Address</label>
                      <textarea class="form-control form-control-sm" name="billingaddress" id="billingaddress" rows="2"
                        required><?php echo $row['billingAddress']; ?></textarea>
                    </div>
                    <div class="row">
                      <div class="col-6 mb-3">
                        <label class="form-label small">State</label>
                        <select class="form-select form-select-sm" name="billingstate" id="billingstate"
                          onchange="loadCities(this, 'billingcity')" required>
                          <option value="">Select State</option>
                          <?php foreach ($states as $s) { ?>
                            <option value="<?php echo $s['id']; ?>" <?php echo ($row['billingState'] == $s['state_name'] || $row['billingState'] == $s['id']) ? 'selected' : ''; ?>>
                              <?php echo htmlentities($s['state_name']); ?>
                            </option>
                          <?php } ?>
                        </select>
                      </div>
                      <div class="col-6 mb-3">
                        <label class="form-label small">City</label>
                        <select class="form-select form-select-sm" name="billingcity" id="billingcity" required>
                          <option value="">Select City</option>
                          <?php
                          if ($row['billingState']) {
                            $sid = $row['billingState'];
                            // If it's a name, find ID
                            if (!is_numeric($sid)) {
                              $found_s = mysqli_query($con, "SELECT id FROM states WHERE state_name='" . mysqli_real_escape_string($con, $sid) . "'");
                              if ($fs = mysqli_fetch_array($found_s))
                                $sid = $fs['id'];
                            }
                            if (is_numeric($sid)) {
                              $cities_res = mysqli_query($con, "SELECT * FROM cities WHERE state_id='$sid' ORDER BY city_name ASC");
                              while ($c = mysqli_fetch_array($cities_res)) {
                                $sel = ($row['billingCity'] == $c['city_name']) ? 'selected' : '';
                                echo "<option value='" . htmlentities($c['city_name']) . "' $sel>" . htmlentities($c['city_name']) . "</option>";
                              }
                            }
                          }
                          ?>
                        </select>
                      </div>
                    </div>
                    <div class="form-group mb-3">
                      <label class="form-label small">Postal Code</label>
                      <input class="form-control form-control-sm" name="billingpincode" id="billingpincode"
                        value="<?php echo $row['billingPincode']; ?>" required>
                    </div>
                    <button type="button" onclick="updateAddress('billing')" class="btn btn-sm btn-success w-100">
                      <i class="fa fa-check me-1"></i> Update Billing
                    </button>
                  </form>
                </div>
              </div>
            </div>

            <!-- Shipping Address -->
            <div class="address-card">
              <div class="address-card-header">
                <button class="address-toggle-btn" type="button" data-bs-toggle="collapse"
                  data-bs-target="#shippingAddressCollapse" aria-expanded="false">
                  <i class="fa fa-truck me-2"></i> Shipping Address
                  <i class="fa fa-chevron-down float-end toggle-icon"></i>
                </button>
              </div>
              <div class="collapse" id="shippingAddressCollapse">
                <div class="address-card-body">
                  <div class="form-check mb-3">
                    <input class="form-check-input" type="checkbox" name="same_as_billing" id="same_as_billing"
                      onchange="toggleShippingSection()" <?php echo ($row['ship_same_as_billing'] == 1) ? 'checked' : ''; ?>>
                    <label class="form-check-label small" for="same_as_billing">
                      Use billing address for shipping
                    </label>
                  </div>

                  <div id="shipping-address-inputs"
                    style="<?php echo ($row['ship_same_as_billing'] == 1) ? 'display:none;' : ''; ?>">
                    <form id="shipping-form">
                      <div class="form-group mb-3">
                        <label class="form-label small">Street Address</label>
                        <textarea class="form-control form-control-sm" name="shippingaddress" id="shippingaddress"
                          rows="2" required><?php echo $row['shippingAddress']; ?></textarea>
                      </div>
                      <div class="row">
                        <div class="col-6 mb-3">
                          <label class="form-label small">State</label>
                          <select class="form-select form-select-sm" name="shippingstate" id="shippingstate"
                            onchange="loadCities(this, 'shippingcity')" required>
                            <option value="">Select State</option>
                            <?php foreach ($states as $s) { ?>
                              <option value="<?php echo $s['id']; ?>" <?php echo ($row['shippingState'] == $s['state_name'] || $row['shippingState'] == $s['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlentities($s['state_name']); ?>
                              </option>
                            <?php } ?>
                          </select>
                        </div>
                        <div class="col-6 mb-3">
                          <label class="form-label small">City</label>
                          <select class="form-select form-select-sm" name="shippingcity" id="shippingcity" required>
                            <option value="">Select City</option>
                            <?php
                            if ($row['shippingState']) {
                              $sid = $row['shippingState'];
                              if (!is_numeric($sid)) {
                                $found_s = mysqli_query($con, "SELECT id FROM states WHERE state_name='" . mysqli_real_escape_string($con, $sid) . "'");
                                if ($fs = mysqli_fetch_array($found_s))
                                  $sid = $fs['id'];
                              }
                              if (is_numeric($sid)) {
                                $cities_res = mysqli_query($con, "SELECT * FROM cities WHERE state_id='$sid' ORDER BY city_name ASC");
                                while ($c = mysqli_fetch_array($cities_res)) {
                                  $sel = ($row['shippingCity'] == $c['city_name']) ? 'selected' : '';
                                  echo "<option value='" . htmlentities($c['city_name']) . "' $sel>" . htmlentities($c['city_name']) . "</option>";
                                }
                              }
                            }
                            ?>
                          </select>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <label class="form-label small">Postal Code</label>
                        <input class="form-control form-control-sm" name="shippingpincode" id="shippingpincode"
                          value="<?php echo $row['shippingPincode']; ?>" required>
                      </div>
                      <button type="button" onclick="updateAddress('shipping')" class="btn btn-sm btn-success w-100">
                        <i class="fa fa-check me-1"></i> Update Shipping
                      </button>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      <?php } else { ?>
        <div class="empty-cart-container">
          <div class="empty-cart-icon">
            <i class="fa fa-shopping-cart"></i>
          </div>
          <h4>Your Shopping Cart is Empty</h4>
          <p class="text-muted">Looks like you haven't added anything to your cart yet.</p>
          <a href="shop.php" class="btn btn-primary mt-3">
            <i class="fa fa-shopping-bag me-2"></i> Start Shopping
          </a>
        </div>
      <?php } ?>

    </div>
  </div>


  <script>
    function updateCartAjax(id, qty) {
      $.ajax({
        type: "POST",
        url: "ajax_action.php",
        dataType: "json",
        data: {
          action: 'update_cart_quantity',
          id: id,
          quantity: qty
        },
        success: function (response) {
          if (response.status === 'success') {
            if (response.removed) {
              window.location.reload();
            } else {
              $('#subtotal-' + id).text('Ghs. ' + response.item_subtotal);
              $('#summary-items-count').text('Subtotal (' + response.total_items + ' items)');
              $('#summary-subtotal-price').text('Ghs. ' + response.total_price);
              $('#summary-grand-total').text('Ghs. ' + response.grand_total);

              // Update Header Cart Count
              if ($('#cart-count').length > 0) {
                $('#cart-count').text(response.cart_count);
              }
            }
          } else {
            alert(response.message);
          }
        },
        error: function () {
          console.error('Error updating cart');
        }
      });
    }

    function incrementQty(id) {
      const input = document.getElementById('qty-' + id);
      let newQty = parseInt(input.value) + 1;
      input.value = newQty;
      updateCartAjax(id, newQty);
    }

    function decrementQty(id) {
      const input = document.getElementById('qty-' + id);
      let newQty = parseInt(input.value) - 1;
      if (newQty >= 0) { // Allow 0 to trigger removal
        input.value = newQty;
        updateCartAjax(id, newQty);
      }
    }

    function removeSelectedItems() {
      const checkboxes = document.querySelectorAll('input[name="remove_code[]"]:checked');
      if (checkboxes.length === 0) {
        alert('Please select at least one item to remove.');
        return;
      }

      if (!confirm('Are you sure you want to remove the selected items?')) {
        return;
      }

      const ids = Array.from(checkboxes).map(cb => cb.value);

      $.ajax({
        url: 'ajax_action.php',
        type: 'POST',
        data: {
          action: 'remove_cart_item',
          ids: ids
        },
        dataType: 'json',
        success: function (response) {
          if (response.status === 'success') {
            // Reload to reflect changes
            window.location.reload();
          } else {
            alert(response.message);
          }
        },
        error: function () {
          alert('An error occurred while removing items. Please try again.');
        }
      });
    }

    function updateAddress(type) {
      const formData = type === 'billing' ? $('#billing-form').serialize() : $('#shipping-form').serialize();

      $.ajax({
        type: "POST",
        url: "ajax_action.php",
        dataType: "json",
        data: formData + '&action=update_address&type=' + type,
        success: function (response) {
          if (response.status === 'success') {
            showToast(response.message, 'success');
          } else {
            showToast(response.message, 'error');
          }
        },
        error: function () {
          showToast('An error occurred. Please try again.', 'error');
        }
      });
    }

    function toggleShippingSection() {
      const isChecked = $('#same_as_billing').is(':checked');
      $('#same_as_billing_val').val(isChecked ? "1" : "2"); // 1 = use billing, 2 = unique shipping

      // Save preference to DB
      $.ajax({
        type: "POST",
        url: "ajax_action.php",
        data: { action: 'toggle_same_as_billing', value: isChecked ? 1 : 0 },
        dataType: "json"
      });

      if (isChecked) {
        $('#shipping-address-inputs').fadeOut();
        $('#shipping-address-inputs [required]').prop('required', false);
      } else {
        $('#shipping-address-inputs').fadeIn();
        $('#shipping-form [name]').prop('required', true);
      }
    }

    function loadCities(stateSelect, citySelectId) {
      const stateId = $(stateSelect).val();
      const citySelect = $('#' + citySelectId);

      citySelect.html('<option value="">Loading...</option>');

      if (!stateId) {
        citySelect.html('<option value="">Select City</option>');
        return;
      }

      $.ajax({
        type: "POST",
        url: "ajax_action.php",
        data: { action: 'get_cities_by_state', state_id: stateId },
        dataType: "json",
        success: function (response) {
          if (response.status === 'success') {
            let options = '<option value="">Select City</option>';
            response.cities.forEach(city => {
              options += `<option value="${city}">${city}</option>`;
            });
            citySelect.html(options);
          }
        }
      });
    }

    function showToast(message, type) {
      const toastEl = $('#liveToast');
      const toastInstance = new bootstrap.Toast(toastEl[0]);

      toastEl.find('.toast-body').text(message);
      toastEl.removeClass('bg-success bg-danger bg-primary');

      if (type === 'success') {
        toastEl.addClass('bg-success text-white');
      } else if (type === 'error') {
        toastEl.addClass('bg-danger text-white');
      } else {
        toastEl.addClass('bg-primary text-white');
      }

      toastInstance.show();
    }
  </script>

  <!-- Toast Container -->
  <div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1100">
    <div id="liveToast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">
          Hello, world! This is a toast message.
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
          aria-label="Close"></button>
      </div>
    </div>
  </div>

  <?php include('includes/footer.php'); ?>
  <?php include('includes/foot.php'); ?>
</body>

</html>