<?php
require_once "../../includes/islogin.php";
require '../../includes/db_connect.php';

$user_id = $_SESSION['user_id'];

// 장바구니 데이터 가져오기
$sql = "SELECT c.cart_id, c.food_id, c.quantity, c.added_at,
               f.name, f.price, f.discount_rate, f.image_url
        FROM Cart c
        JOIN Foods f ON c.food_id = f.food_id
        WHERE c.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$cart_items = [];
$total_price = 0;

while ($row = $result->fetch_assoc()) {
  $cart_items[] = $row;
  $total_price += $row['price'] * $row['quantity'];
}

// 현재 장바구니에서 식당 ID 가져오기
$restaurant_sql = "SELECT f.restaurant_id
                   FROM Cart c
                   JOIN Foods f ON c.food_id = f.food_id
                   WHERE c.user_id = ?
                   LIMIT 1";
$rest_stmt = $conn->prepare($restaurant_sql);
$rest_stmt->bind_param("i", $user_id);
$rest_stmt->execute();
$rest_result = $rest_stmt->get_result();
$restaurant_id = $rest_result->fetch_assoc()['restaurant_id'] ?? 1;

// 해당 식당에서 평점 높은 음식 추천 (장바구니에 없는 것만)
$recommend_sql = "SELECT f.food_id, f.name, f.description, f.price, f.image_url, 
                         AVG(r.rating) AS avg_rating, COUNT(*) as review_count
                  FROM Reviews r
                  JOIN Foods f ON r.food_id = f.food_id
                  WHERE r.restaurant_id = ?
                    AND r.food_id NOT IN (
                      SELECT food_id FROM Cart WHERE user_id = ?
                    )
                  GROUP BY r.food_id
                  ORDER BY avg_rating DESC, review_count DESC
                  LIMIT 3";
$rec_stmt = $conn->prepare($recommend_sql);
$rec_stmt->bind_param("ii", $restaurant_id, $user_id);
$rec_stmt->execute();
$recommend_result = $rec_stmt->get_result();
?>

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

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>장바구니</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
  <style>
    html,
    body {
      height: 100%;
      margin: 0;
    }

    .container {
      height: 100%;
      display: flex;
      flex-direction: column;
      max-width: 400px;
      margin: 0 auto;
    }

    .app-container {
      max-width: 500px;
      height: 100%;
      margin: 0 auto;
      display: flex;
      flex-direction: column;
    }

    .main-content {
      flex: 1;
      overflow-y: auto;
    }


    .header {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 15px;
      height: 70px;
      box-sizing: border-box;
      border-bottom: 1px solid #ddd;
    }

    .header h1 {
      flex-grow: 1;
      font-size: 1.2em;
      margin: 0;
      text-align: center;
    }

    .store-info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
    }

    .menu-item {
      display: flex;
      padding: 10px;
      border-bottom: 1px solid #eee;
    }

    .menu-image {
      position: relative;
      width: 80px;
      height: 80px;
      margin-right: 10px;
    }

    .menu-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }

    .menu-info {
      flex: 1;
    }

    .menu-info h4 {
      margin: 0 0 5px;
    }

    .menu-info .price {
      margin-bottom: 5px;
      color: #888;
    }

    .section-title {
      padding: 10px;
      font-weight: bold;
      background: #f5f5f5;
      border-top: 1px solid #ccc;
    }

    input[type="text"] {
      padding: 10px;
      width: 100%;
      box-sizing: border-box;
      border-radius: 5px;
      border: 1px solid #ccc;
    }

    button {
      cursor: pointer;
    }

    .order-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 10px;
      border-top: 1px solid #ccc;
      background: #fff;
      flex-shrink: 0;
    }

    .order-bar .total-price {
      font-weight: bold;
      font-size: 16px;
    }

    .order-bar button {
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 5px;
      padding: 10px 20px;
    }

    .bottom-nav {
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 10px 0;
      border-top: 1px solid #eee;
      background-color: white;
      flex-shrink: 0;
    }

    .bottom-nav a {
      color: #555;
      font-size: 1.5em;
      text-decoration: none;
      padding: 10px 15px;
      transition: color 0.2s;
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }

    .bottom-nav a:hover,
    .bottom-nav a.active {
      color: #007bff;
    }

    .qty-delete-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;
    }

    .qty-left {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .qty-btn {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      background-color: #eee;
      color: #333;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      font-size: 16px;
      text-decoration: none;
      transition: background-color 0.2s, color 0.2s;
    }

    .qty-btn:hover {
      background-color: #007bff;
      color: white;
    }

    .qty-num {
      font-weight: bold;
      font-size: 14px;
      min-width: 40px;
      text-align: center;
    }

    .remove-btn {
      color: #888;
      font-size: 1.2em;
      padding-left: 10px;
      text-decoration: none;
    }

    .remove-btn:hover {
      color: #e74c3c;
    }
  </style>
</head>

<body>
  <div class="app-container">
    <div class="header">
      <h1>장바구니</h1>
    </div>
    <div class="main-content">
      <form action="submit_order.php" method="POST">
        <?php foreach ($cart_items as $item): ?>
        <div class="menu-item" style="align-items: flex-start;">
          <div class="menu-image" style="width: 60px; height: 60px;">
            <img src="<?= $item['image_url'] ?>" alt="<?= $item['name'] ?>">
          </div>
          <div class="menu-info">
            <h4>
              <?= $item['name'] ?>
            </h4>
            <div class="price">가격:
              <?= number_format($item['price']) ?>원
            </div>
            <input type="hidden" name="food_id[]" value="<?= $item['food_id'] ?>">
            <input type="hidden" name="food_quantity[]" value="<?= $item['quantity'] ?>">
            <input type="hidden" name="food_price[]" value="<?= $item['price'] ?>">
            <div class="qty-delete-row" data-food-id="<?= $item['food_id'] ?>">
              <div class="qty-left">
                <a href="#" class="qty-btn minus"><i class="fas fa-minus-circle"></i></a>
                <span class="qty-num">
                  <?= $item['quantity'] ?>개
                </span>
                <a href="#" class="qty-btn plus"><i class="fas fa-plus-circle"></i></a>
              </div>
              <a href="#" class="remove-btn" data-food-id="<?= $item['food_id'] ?>">
                <i class="fas fa-trash"></i>
              </a>
            </div>


          </div>
        </div>
        <?php endforeach; ?>

        <div style="padding: 10px;">
          <input type="text" name="special_request" placeholder="주문 시 요청 사항 입력란" />
        </div>

        <?php if ($recommend_result->num_rows > 0): ?>
        <div class="section-title">추천 메뉴</div>
        <?php while ($rec = $recommend_result->fetch_assoc()): ?>
        <div class="menu-item">
          <div class="menu-image">
            <img src="<?= $rec['image_url'] ?>" alt="<?= $rec['name'] ?>" />
          </div>
          <div class="menu-info">
            <h4>
              <?= $rec['name'] ?> <span style="font-size: 0.9em; color: #f39c12;">★
                <?= number_format($rec['avg_rating'], 1) ?>
              </span>
            </h4>
            <div>
              <?= nl2br($rec['description']) ?>
            </div>
            <div style="color: #888; font-size: 14px; margin-top: 5px;">
              <?= number_format($rec['price']) ?>원
            </div>
          </div>
        </div>
        <?php endwhile; ?>
        <?php endif; ?>



        <div class="order-bar">
          <div class="total-price">
            <?= number_format($total_price) ?>원
          </div>
          <button type="submit">주문하기</button>
        </div>
      </form>
    </div>

    <!-- 하단 네비게이션 -->
    <nav class="bottom-nav">
      <a href="../../main.php"><i class="fas fa-home"></i></a>
      <a href="../user/dibs.php"><i class="fas fa-heart"></i></a>
      <a href="orderlist.php" class="active"><i class="fas fa-receipt"></i></a>
      <a href="../../auth/redirect-mypage.php"><i class="fas fa-user"></i></a>
    </nav>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(function () {
      $('.qty-delete-row .qty-btn').click(function (e) {
        e.preventDefault();
        const $btn = $(this);
        const $wrapper = $btn.closest('.qty-delete-row');
        const foodId = $wrapper.data('food-id');
        const isPlus = $btn.hasClass('plus');
        const $qtySpan = $wrapper.find('.qty-num');

        $.ajax({
          url: '../../auth/update_cart_ajax.php',
          method: 'POST',
          data: {
            action: isPlus ? 'increase' : 'decrease',
            food_id: foodId
          },
          dataType: 'json',
          success: function (res) {
            if (res.success) {
              if (res.quantity > 0) {
                $qtySpan.text(res.quantity + '개');
                $wrapper.siblings('input[name="food_quantity[]"]').val(res.quantity);
                if (res.total_price !== undefined) {
                  $('.total-price').text(Number(res.total_price).toLocaleString() + '원');
                }
              } else {
                location.reload(); // 수량 0이면 삭제
              }
            } else {
              alert('업데이트 실패: ' + res.message);
            }
          },
          error: function () {
            alert('서버 통신 오류');
          }
        });
      });

      $('.remove-btn').click(function (e) {
        e.preventDefault();
        const foodId = $(this).data('food-id');
        if (!confirm('이 항목을 장바구니에서 삭제할까요?')) return;

        $.ajax({
          url: '../../auth/delete_cart_item.php',
          method: 'POST',
          data: { food_id: foodId },
          dataType: 'json',
          success: function (res) {
            if (res.success) {
              location.reload(); // 삭제 후 새로고침
            } else {
              alert('삭제 실패: ' + res.message);
            }
          },
          error: function () {
            alert('서버 통신 오류');
          }
        });
      });
      $('form').on('submit', function (e) {
        const itemCount = <?= count($cart_items) ?>;
        if (itemCount === 0) {
          alert('장바구니가 비어 있습니다.');
          e.preventDefault(); // 폼 제출 막기
        }
      });
    });
  </script>


</body>

</html>