<?php
// PHP 7.4 compatible Shopping Bag Page
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'products.php';

// Initialize session bag if not set
if (!isset($_SESSION['bag']) || !is_array($_SESSION['bag'])) {
    $_SESSION['bag'] = array();
}

$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

// Handle Actions
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = isset($_POST['product_id']) ? $_POST['product_id'] : '';
    $size = isset($_POST['size']) ? $_POST['size'] : 'M';
    $trade_in = isset($_POST['trade_in']) ? $_POST['trade_in'] : 'No Trade-in';
    $warranty = isset($_POST['warranty']) ? $_POST['warranty'] : 'No Tee Care+';
    
    $product = get_product_by_id($product_id);
    if ($product) {
        // Calculate costs
        $discount = 0.0;
        if ($trade_in === 'Recycle Condition') {
            $discount = 3.0;
        } elseif ($trade_in === 'Good Condition') {
            $discount = 7.0;
        } elseif ($trade_in === 'Excellent Condition') {
            $discount = 12.0;
        }

        $warranty_cost = 0.0;
        if ($warranty === '1-Year Tee Care+') {
            $warranty_cost = 9.0;
        } elseif ($warranty === '2-Year Tee Care+') {
            $warranty_cost = 19.0;
        }

        $single_price = max(0.0, $product['price'] + $warranty_cost - $discount);
        
        // Create unique key for this configuration
        $config_string = $product_id . '_' . $size . '_' . $trade_in . '_' . $warranty;
        $unique_key = md5($config_string);
        
        if (isset($_SESSION['bag'][$unique_key])) {
            $_SESSION['bag'][$unique_key]['quantity'] += 1;
        } else {
            $_SESSION['bag'][$unique_key] = array(
                'product_id' => $product_id,
                'size' => $size,
                'trade_in' => $trade_in,
                'warranty' => $warranty,
                'single_price' => $single_price,
                'quantity' => 1,
                'discount' => $discount,
                'warranty_cost' => $warranty_cost
            );
        }
    }
    header('Location: bag.php');
    exit;
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $unique_key = isset($_POST['unique_key']) ? $_POST['unique_key'] : '';
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
    
    if (isset($_SESSION['bag'][$unique_key])) {
        if ($quantity <= 0) {
            unset($_SESSION['bag'][$unique_key]);
        } else {
            $_SESSION['bag'][$unique_key]['quantity'] = $quantity;
        }
    }
    header('Location: bag.php');
    exit;
}

if ($action === 'remove') {
    $unique_key = isset($_GET['key']) ? $_GET['key'] : '';
    if (isset($_SESSION['bag'][$unique_key])) {
        unset($_SESSION['bag'][$unique_key]);
    }
    header('Location: bag.php');
    exit;
}

require_once 'header.php';
?>

<!-- Bag Title Section -->
<section class="bag-title-section">
  <div class="container">
    <h1>Review your Bag.</h1>
    <p style="font-size: 15px; color: var(--text-secondary); margin-top: 4px;">Free shipping on all order configurations.</p>
  </div>
</section>

<div class="container">
  <?php if (empty($_SESSION['bag'])): ?>
    <!-- Empty Bag Layout -->
    <div class="empty-bag-message">
      <p>Your Bag is empty.</p>
      <a href="index.php" class="btn btn-primary">Continue Shopping</a>
    </div>
  <?php else: ?>
    <!-- Populated Bag Layout -->
    <div class="bag-items-list">
      <?php 
      $subtotal = 0.0;
      $has_unavailable_items = false;
      foreach ($_SESSION['bag'] as $key => $item): 
        $product = get_product_by_id($item['product_id']);
        $is_available = ($product !== null);
        
        if (!$is_available) {
            $has_unavailable_items = true;
            $product = array(
                'id' => $item['product_id'],
                'name' => 'Product ' . ucfirst($item['product_id']),
                'price' => $item['single_price'],
                'image_url' => 'assets/images/default.jpg',
                'specs' => array(),
                'thai_specs' => array()
            );
        }
        
        $item_total = $item['single_price'] * $item['quantity'];
        $subtotal += $item_total;
      ?>
        <div class="bag-item" style="<?php echo !$is_available ? 'opacity: 0.8;' : ''; ?>">
          <!-- Product image -->
          <div class="bag-item-image">
            <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" onerror="this.src='https://images.unsplash.com/photo-1521572267360-ee0c2909d518?auto=format&fit=crop&q=80&w=100';">
          </div>
          
          <!-- Product details and controls -->
          <div class="bag-item-info">
            <div class="bag-item-details">
              <h2>
                <?php echo htmlspecialchars($product['name']); ?>
                <?php if (!$is_available): ?>
                  <span style="font-size: 11px; background: rgba(255, 59, 48, 0.1); color: #ff3b30; padding: 2px 6px; border-radius: 4px; font-weight: 500; margin-left: 6px;">No longer available</span>
                <?php endif; ?>
              </h2>
              <div class="bag-item-meta">
                <span>Size: <strong><?php echo htmlspecialchars($item['size']); ?></strong></span>
                <?php if ($item['discount'] > 0): ?>
                  <span>Trade-in: <?php echo htmlspecialchars($item['trade_in']); ?> (-$<?php echo number_format($item['discount'], 2); ?>)</span>
                <?php endif; ?>
                <?php if ($item['warranty_cost'] > 0): ?>
                  <span>Coverage: <?php echo htmlspecialchars($item['warranty']); ?> (+$<?php echo number_format($item['warranty_cost'], 2); ?>)</span>
                <?php endif; ?>
              </div>
            </div>
            
            <div class="bag-item-actions">
              <!-- Form to update quantity -->
              <form action="bag.php" method="POST" style="display: inline-block;">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="unique_key" value="<?php echo htmlspecialchars($key); ?>">
                <select name="quantity" class="bag-qty-select" aria-label="Quantity selector">
                  <?php for ($q = 1; $q <= 10; $q++): ?>
                    <option value="<?php echo $q; ?>" <?php echo ($item['quantity'] === $q) ? 'selected' : ''; ?>>
                      <?php echo $q; ?>
                    </option>
                  <?php endfor; ?>
                </select>
              </form>
              <span>|</span>
              <a href="bag.php?action=remove&key=<?php echo htmlspecialchars($key); ?>" class="remove-btn">Remove</a>
            </div>
          </div>
          
          <!-- Subtotal display per item -->
          <div class="bag-item-price-col">
            <div class="bag-item-total">
              $<?php echo number_format($item_total, 2); ?>
            </div>
            <div style="font-size: 12px; color: var(--text-secondary);">
              $<?php echo number_format($item['single_price'], 2); ?> each
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
    
    <!-- Bag Summary Section -->
    <div class="bag-summary-section">
      <div><!-- Left empty spacer for layout balance --></div>
      <div>
        <div class="bag-summary-card">
          <div class="summary-row">
            <span>Subtotal</span>
            <span>$<?php echo number_format($subtotal, 2); ?></span>
          </div>
          <div class="summary-row">
            <span>Shipping</span>
            <span>Free</span>
          </div>
          <div class="summary-row total">
            <span>Total</span>
            <span>$<?php echo number_format($subtotal, 2); ?></span>
          </div>
          <div class="bag-summary-actions">
            <?php if ($has_unavailable_items): ?>
              <button class="btn btn-primary" style="width: 100%; opacity: 0.5; cursor: not-allowed;" disabled>Check Out</button>
              <p style="font-size: 11px; color: #ff3b30; margin-top: 8px; text-align: center;">Please remove unavailable items before checking out.</p>
            <?php else: ?>
              <a href="checkout.php" class="btn btn-primary">Check Out</a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  <?php endif; ?>
</div>

<?php
require_once 'footer.php';
?>
