<?php
require '../config.php';
session_start();
require 'navbar.php'; // Ensure this path is correct

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

$user_id = $_SESSION['user_id'];

// Use prepared statements for security
$stmt = $conn->prepare("
     SELECT 
        k.*, 
        p.nama, 
        p.harga, 
        p.gambar,
        up.ukuran,
        up.stok AS stok_ukuran
    FROM keranjang k 
    JOIN produk p ON k.produk_id = p.id 
    JOIN ukuran_produk up ON k.ukuran_id = up.id
    WHERE k.pengguna_id = ?
");
if ($stmt === false) {
  die("Prepare failed: " . $conn->error);
}
$stmt->bind_param("i", $user_id);
$stmt->execute();
$query_result = $stmt->get_result();

$total = 0;
?>

<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Keranjang Belanja - Day Apparel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    /* Global Minimalist Black & White Theme */
    body {
      background-color: #f8f8f8;
      /* Light gray background */
      color: #333;
      /* Dark gray for general text */
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      /* Modern sans-serif font */
    }

    .container.main-content {
      background-color: #fff;
      /* White background for the main content area */
      border-radius: 12px;
      /* More rounded corners for softness */
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
      /* Stronger, softer shadow */
      padding: 40px;
      /* Increased padding */
      margin-top: 30px;
      /* Space from navbar */
      margin-bottom: 30px;
    }

    /* Page Header */
    h5 {
      font-size: 2.2rem;
      /* Larger, more prominent heading */
      font-weight: 700;
      /* Bolder */
      color: #222;
      /* Darker heading color */
      padding-bottom: 20px;
      /* More space below heading */
      margin-bottom: 40px;
      /* More space before table/alert */
      position: relative;
      text-align: center;
      /* Center the heading */
    }

    h2::after {
      content: '';
      display: block;
      width: 60px;
      /* Short, subtle divider */
      height: 3px;
      background-color: #333;
      /* Solid black divider */
      margin: 15px auto 0;
      /* Center the divider */
      border-radius: 2px;
    }

    /* Desktop Table Styling */
    .desktop-table {
      display: block;
    }
    .mobile-cards {
      display: none;
    }

    /* Table Styling */
    .table {
      margin-bottom: 2rem;
      /* More space below table */
      border-collapse: separate;
      /* Needed for border-radius on cells if applied */
      border-spacing: 0;
    }

    .table thead th {
      background-color: #f0f0f0;
      /* Light gray for table header background */
      color: #555;
      /* Darker text for headers */
      font-weight: 600;
      /* Bolder headers */
      padding: 1rem 1.25rem;
      /* More padding in headers */
      border-bottom: 2px solid #ddd;
      /* Clearer bottom border for header */
      text-transform: uppercase;
      /* Uppercase for a modern look */
      font-size: 0.9rem;
      letter-spacing: 0.5px;
    }

    .table tbody tr {
      transition: background-color 0.2s ease;
      /* Smooth hover transition */
    }

    .table tbody tr:hover {
      background-color: #f5f5f5;
      /* Very light gray on row hover */
    }

    .table td {
      padding: 1rem 1.25rem;
      /* More padding in cells */
      vertical-align: middle;
      /* Center content vertically */
      border-top: 1px solid #eee;
      /* Lighter border for cells */
      font-size: 1rem;
    }

    .table td:first-child {
      /* Product column */
      display: flex;
      align-items: center;
      gap: 15px;
      /* Space between image and text */
    }

    .table td img {
      width: 60px;
      /* Larger product image thumbnail */
      height: 60px;
      /* Maintain aspect ratio */
      object-fit: cover;
      /* Cover the area */
      border-radius: 8px;
      /* More rounded image corners */
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      /* Subtle shadow for image */
      flex-shrink: 0;
    }

    /* Price and Total Text */
    .table td:nth-child(2),
    /* Harga */
    .table td:nth-child(4),
    /* Subtotal */
    .table tfoot strong {
      /* Total */
      font-weight: 600;
      color: #333;
      /* Darker price text */
    }

    .table tfoot tr:last-child {
      background-color: #f0f0f0;
      /* Light gray background for total row */
      font-size: 1.1rem;
      border-top: 2px solid #ddd;
    }

    .table tfoot td {
      padding-top: 1.5rem;
      padding-bottom: 1.5rem;
    }

    .table tfoot .text-end {
      padding-right: 1.25rem;
      /* Align total label with content */
    }

    .cart-item-card {
      background: #fff;
      border: 1px solid #e9ecef;
      border-radius: 12px;
      padding: 1.25rem;
      margin-bottom: 1rem;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
    }

    .cart-item-card:hover {
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      transform: translateY(-1px);
    }

    .cart-item-card.warning {
      border-left: 4px solid #ffc107;
      background-color: rgba(255, 243, 205, 0.3);
    }

    .cart-item-header {
      display: flex;
      align-items: flex-start;
      gap: 1rem;
      margin-bottom: 1rem;
    }

    .cart-item-image {
      width: 70px;
      height: 70px;
      object-fit: cover;
      border-radius: 8px;
      flex-shrink: 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .cart-item-info {
      flex: 1;
    }

    .cart-item-name {
      font-weight: 600;
      color: #333;
      font-size: 1rem;
      margin-bottom: 0.5rem;
      line-height: 1.3;
    }

    .cart-item-details {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 0.75rem;
      margin-bottom: 1rem;
    }

    .detail-item {
      background: #f8f9fa;
      padding: 0.75rem;
      border-radius: 8px;
      text-align: center;
    }

    .detail-label {
      font-size: 0.75rem;
      color: #666;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 0.25rem;
    }

    .detail-value {
      font-weight: 600;
      color: #333;
      font-size: 0.9rem;
    }

    .cart-item-total {
      background: #333;
      color: white;
      padding: 0.75rem;
      border-radius: 8px;
      text-align: center;
      margin-bottom: 1rem;
    }

    .total-label {
      font-size: 0.75rem;
      opacity: 0.8;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .total-value {
      font-size: 1.1rem;
      font-weight: 600;
      margin-top: 0.25rem;
    }

    .cart-item-actions {
      text-align: center;
    }

    /* Stock Issues */
    .stock-warning {
      background: #fff3cd;
      border: 1px solid #ffeaa7;
      border-radius: 6px;
      padding: 0.5rem 0.75rem;
      margin-top: 0.5rem;
      font-size: 0.8rem;
      color: #856404;
    }

    .stock-warning i {
      color: #dc3545;
      margin-right: 0.25rem;
    }

    /* Buttons */
    .btn {
      padding: 12px 25px;
      /* Larger buttons */
      border-radius: 8px;
      /* More rounded button corners */
      font-weight: 600;
      /* Bolder text on buttons */
      transition: all 0.3s ease;
      display: inline-flex;
      /* For icon alignment */
      align-items: center;
      justify-content: center;
      font-size: 0.9rem;
    }

    .btn-primary {
      background-color: #333;
      /* Black for primary button */
      color: #fff;
      border: 1px solid #333;
    }

    .btn-primary:hover {
      background-color: #555;
      /* Darker gray on hover */
      border-color: #555;
      transform: translateY(-2px);
      /* Subtle lift effect */
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    .btn-danger {
      background-color: #e74c3c;
      /* A slightly softer red */
      border-color: #e74c3c;
    }

    .btn-danger:hover {
      background-color: #c0392b;
      border-color: #c0392b;
      transform: translateY(-1px);
    }

    .btn-outline-secondary {
      border-color: #6c757d;
      color: #6c757d;
    }
    .btn-outline-secondary:hover {
      background-color: #6c757d;
      border-color: #6c757d;
      color: white;
    }

    .btn-sm {
      padding: 8px 15px;
      /* Adjust smaller buttons */
      font-size: 0.875rem;
      border-radius: 6px;
    }

    .btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
    /* Total Section */
    .cart-total {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 1.5rem;
      margin: 1.5rem 0;
      text-align: center;
    }
    .cart-total-label {
      font-size: 1rem;
      color: #666;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      margin-bottom: 0.5rem;
    }
    .cart-total-value {
      font-size: 1.8rem;
      font-weight: 700;
      color: #333;
    }

    /* Empty Cart Alert */
    .alert-info {
      background-color: #e9ecef;
      /* Lighter, more subtle background */
      color: #495057;
      /* Darker text */
      border-color: #dee2e6;
      /* Subtle border */
      padding: 1.5rem 2rem;
      /* More padding */
      border-radius: 12px;
      /* Consistent rounded corners */
      font-size: 1.1rem;
      text-align: center;
      /* Center content */
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      /* Subtle shadow */
    }

    .alert-info i {
      color: #6c757d;
      margin-bottom: 1rem;
    }

    .alert-info a {
      color: #333;
      /* Black link in alert */
      font-weight: 600;
      text-decoration: none;
      transition: color 0.2s ease;
    }

    .alert-info a:hover {
      color: #000;
      text-decoration: underline;
    }

    .alert-warning {
      background-color: #fff3cd;
      border-color: #ffeaa7;
      color: #856404;
      border-radius: 8px;
      padding: 1rem 1.5rem;
    }

    /* Action Buttons Container */
    .cart-actions {
      display: flex;
      gap: 1rem;
      margin-top: 1.5rem;
    }

    .cart-actions .btn {
      flex: 1;
      min-height: 48px;
    }

    /* Responsive Design */
    @media (max-width: 768px) {
      .container.main-content {
        padding: 15px;
        margin-top: 15px;
        margin-bottom: 15px;
        border-radius: 8px;
      }

      h5 {
        font-size: 1.5rem;
        margin-bottom: 20px;
        padding-bottom: 10px;
      }

      h5::after {
        width: 40px;
        margin-top: 10px;
      }

      /* Hide desktop table, show mobile cards */
      .desktop-table {
        display: none;
      }

      .mobile-cards {
        display: block;
      }

      .cart-item-card {
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 8px;
      }

      .cart-item-image {
        width: 60px;
        height: 60px;
        display: flex;
      }

      .cart-item-name {
        font-size: 0.95rem;
      }

      .cart-item-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 0.5rem;
        display: flex;
      }

      .detail-item {
        padding: 0.6rem;
      }

      .detail-label {
        font-size: 0.7rem;
      }

      .detail-value {
        font-size: 0.85rem;
      }

      .cart-total {
        padding: 1.25rem;
        margin: 1rem 0;
        justify-content: center;
      }

      .cart-total-value {
        font-size: 1.5rem;
      }

      .cart-actions {
        flex-direction: column;
        gap: 0.75rem;
      }

      .cart-actions .btn {
        width: 100%;
        padding: 12px 20px;
      }

      .btn {
        font-size: 0.9rem;
      }

      .btn-sm {
        padding: 8px 12px;
        font-size: 0.8rem;
      }

      .alert-info {
        padding: 1.5rem 1rem;
        font-size: 0.95rem;
      }
    }

    @media (max-width: 480px) {
      .container.main-content {
        padding: 12px;
      }

      h5 {
        font-size: 1.3rem;
      }

      .cart-item-header {
        gap: 0.75rem;
      }

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

      .cart-item-name {
        font-size: 0.9rem;
      }

      .cart-item-details {
        grid-template-columns: 1fr;
        gap: 0.5rem;
      }

      .cart-total-value {
        font-size: 1.3rem;
      }

      .detail-value {
        font-size: 0.8rem;
      }
    }

    /* Touch Improvements */
    @media (hover: none) and (pointer: coarse) {
      .cart-item-card:hover,
      .table tbody tr:hover {
        background-color: inherit;
        transform: none;
      }

      .cart-item-card:active {
        transform: scale(0.98);
        transition: transform 0.1s ease;
      }

      .btn:active {
        transform: scale(0.95);
      }
    }
  </style>
</head>

<body>
  <div class="container main-content">
    <h5>Keranjang Belanja Anda</h5>
    <?php if ($query_result->num_rows > 0): ?>
      <form action="checkout.php" method="POST">
        
        <!-- Desktop Table View -->
        <div class="desktop-table">
          <div class="table-responsive">
            <table class="table">
              <thead>
                <tr>
                  <th scope="col">Produk</th>
                  <th scope="col">Harga</th>
                  <th scope="col">Jumlah</th>
                  <th scope="col">Ukuran</th>
                  <th scope="col">Subtotal</th>
                  <th scope="col">Aksi</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $total_stok_issues = 0;
                $query_result->data_seek(0); // Reset result pointer
                while ($row = $query_result->fetch_assoc()) :
                  $subtotal = $row['harga'] * $row['jumlah'];
                  $total += $subtotal;

                  // Cek apakah ada masalah stok
                  $stok_issue = false;
                  if ($row['stok_ukuran'] <= 0) {
                    $stok_issue = true;
                    $total_stok_issues++;
                  } elseif ($row['jumlah'] > $row['stok_ukuran']) {
                    $stok_issue = true;
                    $total_stok_issues++;
                  }
                ?>
                  <tr class="<?= $stok_issue ? 'table-warning' : '' ?>">
                    <td>
                      <img src="../upload/<?= htmlspecialchars($row['gambar']) ?>" alt="<?= htmlspecialchars($row['nama']) ?>">
                      <div>
                        <?= htmlspecialchars($row['nama']) ?>
                        <?php if ($stok_issue): ?>
                          <br><small class="text-danger"><i class="fas fa-exclamation-triangle"></i>
                            <?= $row['stok_ukuran'] <= 0 ? 'Stok Habis' : 'Jumlah melebihi stok tersedia (' . $row['stok_ukuran'] . ')' ?>
                          </small>
                        <?php endif; ?>
                      </div>
                    </td>
                    <td>Rp<?= number_format($row['harga'], 0, ',', '.') ?></td>
                    <td>
                      <?= htmlspecialchars($row['jumlah']) ?>
                      <?php if ($stok_issue && $row['stok_ukuran'] > 0): ?>
                        <br><small class="text-muted">Stok: <?= $row['stok_ukuran'] ?></small>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?= htmlspecialchars($row['ukuran']) ?>
                      <?php if ($row['stok_ukuran'] <= 0): ?>
                        <br><small class="text-danger">Tidak Tersedia</small>
                      <?php endif; ?>
                    </td>
                    <td>Rp<?= number_format($subtotal, 0, ',', '.') ?></td>
                    <td>
                      <a href="hapus_keranjang.php?id=<?= htmlspecialchars($row['id']) ?>" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus produk ini dari keranjang?')">
                        <i class="fas fa-trash-alt"></i> Hapus
                      </a>
                    </td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="4" class="text-end"><strong>Total Belanja</strong></td>
                  <td colspan="2"><strong>Rp<?= number_format($total, 0, ',', '.') ?></strong></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        <!-- Mobile Card View -->
        <div class="mobile-cards">
          <?php
          $total = 0; // Reset total for mobile view
          $total_stok_issues = 0;
          $query_result->data_seek(0); // Reset result pointer
          while ($row = $query_result->fetch_assoc()) :
            $subtotal = $row['harga'] * $row['jumlah'];
            $total += $subtotal;

            // Cek apakah ada masalah stok
            $stok_issue = false;
            if ($row['stok_ukuran'] <= 0) {
              $stok_issue = true;
              $total_stok_issues++;
            } elseif ($row['jumlah'] > $row['stok_ukuran']) {
              $stok_issue = true;
              $total_stok_issues++;
            }
          ?>
            <div class="cart-item-card <?= $stok_issue ? 'warning' : '' ?>">
              <div class="cart-item-header">
                <img src="../upload/<?= htmlspecialchars($row['gambar']) ?>" alt="<?= htmlspecialchars($row['nama']) ?>" class="cart-item-image">
                <div class="cart-item-info">
                  <div class="cart-item-name"><?= htmlspecialchars($row['nama']) ?></div>
                  <?php if ($stok_issue): ?>
                    <div class="stock-warning">
                      <i class="fas fa-exclamation-triangle"></i>
                      <?= $row['stok_ukuran'] <= 0 ? 'Stok Habis' : 'Jumlah melebihi stok tersedia (' . $row['stok_ukuran'] . ')' ?>
                    </div>
                  <?php endif; ?>
                </div>
              </div>

              <div class="cart-item-details">
                <div class="detail-item">
                  <div class="detail-label">Harga</div>
                  <div class="detail-value">Rp<?= number_format($row['harga'], 0, ',', '.') ?></div>
                </div>
                <div class="detail-item">
                  <div class="detail-label">Jumlah</div>
                  <div class="detail-value">
                    <?= htmlspecialchars($row['jumlah']) ?>
                    <?php if ($stok_issue && $row['stok_ukuran'] > 0): ?>
                      <br><small class="text-muted">Stok: <?= $row['stok_ukuran'] ?></small>
                    <?php endif; ?>
                  </div>
                </div>
                <div class="detail-item">
                  <div class="detail-label">Ukuran</div>
                  <div class="detail-value">
                    <?= htmlspecialchars($row['ukuran']) ?>
                    <?php if ($row['stok_ukuran'] <= 0): ?>
                      <br><small class="text-danger">Tidak Tersedia</small>
                    <?php endif; ?>
                  </div>
                </div>
              </div>

              <div class="cart-item-total">
                <div class="total-label">Subtotal</div>
                <div class="total-value">Rp<?= number_format($subtotal, 0, ',', '.') ?></div>
              </div>

              <div class="cart-item-actions">
                <a href="hapus_keranjang.php?id=<?= htmlspecialchars($row['id']) ?>" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus produk ini dari keranjang?')">
                  <i class="fas fa-trash-alt me-1"></i> Hapus dari Keranjang
                </a>
              </div>
            </div>
          <?php endwhile; ?>

          <!-- Mobile Total -->
          <div class="cart-total">
            <div class="cart-total-label">Total Belanja</div>
            <div class="cart-total-value">Rp<?= number_format($total, 0, ',', '.') ?></div>
          </div>
        </div>

        <?php if ($total_stok_issues > 0): ?>
          <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>Perhatian!</strong> Ada <?= $total_stok_issues ?> produk dengan masalah stok.
            Silakan hapus produk yang tidak tersedia atau sesuaikan jumlah sebelum melanjutkan checkout.
          </div>
        <?php endif; ?>

        <div class="cart-actions">
          <a href="../index.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Lanjutkan Belanja
          </a>
          <button type="submit" class="btn btn-primary" <?= $total_stok_issues > 0 ? 'disabled title="Tidak bisa checkout - ada masalah stok"' : '' ?>>
            <i class="fas fa-money-check-alt me-2"></i>Lanjutkan ke Checkout
          </button>
        </div>
      </form>
    <?php else: ?>
      <div class="alert alert-info">
        <i class="fas fa-shopping-cart fa-3x"></i><br><br>
        Keranjang belanja Anda masih kosong.<br><br>
        <a href="../index.php" class="alert-link">Mulai Berbelanja Sekarang</a>
      </div>
    <?php endif; ?>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  
  <script>
    // Touch feedback for mobile
    if ('ontouchstart' in window) {
      document.querySelectorAll('.cart-item-card, .btn').forEach(element => {
        element.addEventListener('touchstart', function() {
          this.style.opacity = '0.8';
        });
        
        element.addEventListener('touchend', function() {
          this.style.opacity = '1';
        });
      });
    }

    // Smooth scroll for better UX
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
          target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
          });
        }
      });
    });
  </script>
  
  <?php include '../footer.php'; ?>
</body>

</html>