<?php
/**
 * public/shop.php — หน้าร้านค้าเฉพาะ (Store Frontpage)
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/auth.php';

$db = getDBConnection();

$slug = isset($_GET['slug']) ? sanitize($_GET['slug']) : '';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($slug) {
    $stmt = $db->prepare("SELECT * FROM vendors WHERE store_slug = ? AND status = 'approved'");
    $stmt->execute([$slug]);
    $vendor = $stmt->fetch();
} elseif ($id > 0) {
    $stmt = $db->prepare("SELECT * FROM vendors WHERE id = ? AND status = 'approved'");
    $stmt->execute([$id]);
    $vendor = $stmt->fetch();
} else {
    $vendor = false;
}

if (!$vendor) {
    header('Location: ' . SITE_URL . '/vendors.php');
    exit;
}

$vendorId = (int)$vendor['id'];

// Filtering parameters
$vcat_id = isset($_GET['vcategory']) ? (int)$_GET['vcategory'] : 0;
$cat_id  = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$search  = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$sort    = isset($_GET['sort']) ? sanitize($_GET['sort']) : 'latest';
$page    = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit   = 8;
$offset  = ($page - 1) * $limit;

// Build query for products belonging to this vendor
$where = ["p.vendor_id = ?", "p.status = 'active'"];
$params = [$vendorId];

if ($vcat_id > 0) {
    $where[] = "p.vendor_category_id = ?";
    $params[] = $vcat_id;
}
if ($cat_id > 0) {
    $where[] = "p.category_id = ?";
    $params[] = $cat_id;
}
if (!empty($search)) {
    $where[] = "(p.name LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$whereClause = implode(" AND ", $where);

// Sorting logic
$orderBy = "p.created_at DESC";
if ($sort === 'price_asc') $orderBy = "p.price ASC";
if ($sort === 'price_desc') $orderBy = "p.price DESC";

// Count products
$countStmt = $db->prepare("SELECT COUNT(*) FROM products p WHERE $whereClause");
$countStmt->execute($params);
$totalProducts = $countStmt->fetchColumn();
$totalPages = ceil($totalProducts / $limit);

// Fetch products
$query = "SELECT p.*, c.name as category_name, vc.name as vcat_name 
          FROM products p 
          JOIN categories c ON p.category_id = c.id 
          LEFT JOIN vendor_categories vc ON p.vendor_category_id = vc.id 
          WHERE $whereClause 
          ORDER BY $orderBy 
          LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$products = $stmt->fetchAll();

// Fetch sub-categories of this vendor
$vcatStmt = $db->prepare("SELECT * FROM vendor_categories WHERE vendor_id = ? AND is_active = 1 ORDER BY sort_order ASC");
$vcatStmt->execute([$vendorId]);
$vendorCategories = $vcatStmt->fetchAll();

$pageTitle = sanitize($vendor['store_name']) . " - หน้าร้านค้า";
require_once __DIR__ . '/../includes/header.php';
?>

<nav aria-label="breadcrumb" class="my-3">
  <ol class="breadcrumb bg-light p-3 rounded-3 shadow-sm">
    <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none">หน้าหลัก</a></li>
    <li class="breadcrumb-item"><a href="vendors.php" class="text-decoration-none">ร้านค้าทั้งหมด</a></li>
    <li class="breadcrumb-item active" aria-current="page"><?php echo htmlspecialchars($vendor['store_name']); ?></li>
  </ol>
</nav>

<!-- Store Header Header / Banner Card -->
<div class="card card-custom overflow-hidden mb-4 p-0 shadow-sm border-0 shop-profile-card">
  <div class="position-relative" style="height: 180px; background: <?php echo $vendor['store_banner'] ? "url('".htmlspecialchars($vendor['store_banner'])."') center/cover" : "linear-gradient(135deg, #312e81, #4338ca)"; ?>;">
  </div>

  <div class="card-body p-4 bg-white position-relative">
    <div class="row align-items-end g-3" style="margin-top: -50px;">
      <div class="col-auto">
        <?php if (!empty($vendor['store_logo'])): ?>
          <img src="<?php echo htmlspecialchars($vendor['store_logo']); ?>" 
               class="rounded-circle border border-4 border-white shadow-sm" 
               style="width: 100px; height: 100px; object-fit: cover;" 
               alt="<?php echo htmlspecialchars($vendor['store_name']); ?>">
        <?php else: ?>
          <div class="rounded-circle border border-4 border-white shadow-sm bg-primary text-white d-flex align-items-center justify-content-center fw-bold fs-2" 
               style="width: 100px; height: 100px;">
            <?php echo mb_substr($vendor['store_name'], 0, 1); ?>
          </div>
        <?php endif; ?>
      </div>

      <div class="col">
        <h2 class="fw-bold mb-1 text-gray-900 shop-title"><?php echo htmlspecialchars($vendor['store_name']); ?></h2>
        <p class="text-gray-600 mb-2 small shop-desc"><?php echo htmlspecialchars($vendor['description'] ?: 'ยินดีต้อนรับสู่หน้าร้านของเรา'); ?></p>
        
        <div class="d-flex flex-wrap gap-3 text-gray-600 small">
          <?php if ($vendor['contact_phone'] ?? $vendor['phone'] ?? false): ?>
            <span class="shop-info-item">📞 <?php echo htmlspecialchars($vendor['contact_phone'] ?? $vendor['phone']); ?></span>
          <?php endif; ?>
          <?php if ($vendor['contact_email'] ?? false): ?>
            <span class="shop-info-item">✉️ <?php echo htmlspecialchars($vendor['contact_email']); ?></span>
          <?php endif; ?>
          <span class="shop-info-item">📦 <?php echo $totalProducts; ?> สินค้า</span>
        </div>
      </div>

      <!-- ปุ่มทางลัดสำหรับเจ้าของร้านค้า -->
      <?php if (isLoggedIn() && (int)$_SESSION['user']['id'] === (int)$vendor['user_id']): ?>
        <div class="col-12 col-md-auto mt-3 mt-md-0">
          <div class="d-flex gap-2">
            <a href="add-product.php" class="btn btn-success rounded-pill px-3 fw-bold shadow-sm">
              ➕ เพิ่มสินค้าใหม่
            </a>
            <a href="<?php echo dirname(SITE_URL); ?>/vendor_panel/index.php" class="btn btn-outline-primary rounded-pill px-3 fw-bold shadow-sm">
              ⚙️ จัดการร้านค้า
            </a>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Category Filters & Search -->
<div class="row mb-4 align-items-center">
  <div class="col-md-7 mb-2 mb-md-0">
    <div class="d-flex flex-wrap gap-2">
      <a href="shop.php?slug=<?php echo urlencode($vendor['store_slug']); ?>" 
         class="btn btn-sm rounded-pill <?php echo $vcat_id === 0 ? 'btn-primary' : 'btn-outline-secondary'; ?>">
        ทั้งหมด 🛍️
      </a>
      <?php foreach ($vendorCategories as $vcat): ?>
        <a href="shop.php?slug=<?php echo urlencode($vendor['store_slug']); ?>&vcategory=<?php echo $vcat['id']; ?>" 
           class="btn btn-sm rounded-pill <?php echo $vcat_id === $vcat['id'] ? 'btn-primary' : 'btn-outline-secondary'; ?>">
          🏷️ <?php echo htmlspecialchars($vcat['name']); ?>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
  
  <div class="col-md-5">
    <form method="GET" action="shop.php" class="d-flex gap-2">
      <input type="hidden" name="slug" value="<?php echo htmlspecialchars($vendor['store_slug']); ?>">
      <?php if ($vcat_id > 0): ?>
        <input type="hidden" name="vcategory" value="<?php echo $vcat_id; ?>">
      <?php endif; ?>
      <input type="text" name="search" class="form-control rounded-pill px-3" placeholder="🔍 ค้นหาในร้านนี้..." value="<?php echo sanitize($search); ?>">
      <select name="sort" class="form-select rounded-pill" style="width: 150px;" onchange="this.form.submit()">
        <option value="latest" <?php echo $sort === 'latest' ? 'selected' : ''; ?>>✨ ล่าสุด</option>
        <option value="price_asc" <?php echo $sort === 'price_asc' ? 'selected' : ''; ?>>💵 ราคาต่ำ-สูง</option>
        <option value="price_desc" <?php echo $sort === 'price_desc' ? 'selected' : ''; ?>>💎 ราคาสูง-ต่ำ</option>
      </select>
    </form>
  </div>
</div>

<!-- Product Grid (4 or 5 Columns on Desktop) -->
<div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-4 row-cols-xl-5 g-3 g-md-4">
  <?php if (empty($products)): ?>
    <div class="col-12 text-center py-5">
      <div class="fs-1">📦</div>
      <h4 class="text-muted mt-2">ไม่พบสินค้าในร้านนี้</h4>
      <a href="shop.php?slug=<?php echo urlencode($vendor['store_slug']); ?>" class="btn btn-outline-primary rounded-pill mt-2">ดูสินค้าทั้งหมดของร้าน</a>
    </div>
  <?php else: ?>
    <?php foreach ($products as $p): ?>
      <div class="col d-flex align-items-stretch">
        <div class="card card-custom h-100 position-relative w-100">
          <?php if ($p['is_new']): ?>
            <span class="position-absolute top-0 start-0 m-2 badge badge-tag-new">✨ ใหม่</span>
          <?php endif; ?>

          <a href="product_detail.php?id=<?php echo $p['id']; ?>" class="product-img-wrapper">
            <img src="<?php echo sanitize(formatImageUrl($p['main_image'])); ?>" onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';" class="product-card-img" alt="<?php echo sanitize($p['name']); ?>" loading="lazy">
          </a>

          <div class="card-body d-flex flex-column justify-content-between p-3">
            <div>
              <span class="store-badge mb-1">
                🏷️ <?php echo sanitize($p['vcat_name'] ?: $p['category_name']); ?>
              </span>
              <h6 class="card-title fw-normal mb-1">
                <a href="product_detail.php?id=<?php echo $p['id']; ?>" class="product-title-link">
                  <?php echo sanitize($p['name']); ?>
                </a>
              </h6>
              <div class="d-flex align-items-baseline flex-wrap gap-1 mb-3">
                <span class="price-current">฿<?php echo number_format($p['price'], 2); ?></span>
                <?php if ($p['normal_price'] > $p['price']): ?>
                  <span class="price-strike">฿<?php echo number_format($p['normal_price'], 2); ?></span>
                  <?php 
                    $discountPct = round((($p['normal_price'] - $p['price']) / $p['normal_price']) * 100);
                  ?>
                  <span class="discount-badge">-<?php echo $discountPct; ?>%</span>
                <?php endif; ?>
              </div>
            </div>

            <button onclick="addToCart(<?php echo $p['id']; ?>)" class="btn btn-primary-custom w-100 rounded-pill py-2">
              หยิบใส่ตะกร้า 🛒
            </button>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
  <nav class="mt-5 d-flex justify-content-center">
    <ul class="pagination">
      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
          <a class="page-link" href="shop.php?slug=<?php echo urlencode($vendor['store_slug']); ?>&page=<?php echo $i; ?>&vcategory=<?php echo $vcat_id; ?>&search=<?php echo urlencode($search); ?>&sort=<?php echo $sort; ?>">
            <?php echo $i; ?>
          </a>
        </li>
      <?php endfor; ?>
    </ul>
  </nav>
<?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
