<?php
/**
 * public/vendors.php — รายการร้านค้าทั้งหมด (All Vendors Directory)
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/auth.php';

// Custom Fallback Function สำหรับ sanitize()
if (!function_exists('safe_sanitize')) {
    function safe_sanitize($string) {
        if (function_exists('sanitize')) {
            return sanitize($string);
        }
        return htmlspecialchars((string)$string, ENT_QUOTES, 'UTF-8');
    }
}

$vendors = [];
$dbError = '';

try {
    $db = getDBConnection();

    // Fetch all approved vendors with product count
    // Use lower_case for table and columns.
    // Explicitly select and GROUP BY specific columns to prevent ONLY_FULL_GROUP_BY errors.
    $stmt = $db->query("
        select 
            v.id, 
            v.store_slug, 
            v.store_banner, 
            v.store_logo, 
            v.store_name, 
            v.description, 
            count(distinct p.id) as product_count
        from vendors v
        left join products p on p.vendor_id = v.id and p.status = 'active'
        where v.status = 'approved'
        group by 
            v.id, 
            v.store_slug, 
            v.store_banner, 
            v.store_logo, 
            v.store_name, 
            v.description
        order by v.store_name asc, v.id asc
    ");
    
    if ($stmt) {
        $vendors = $stmt->fetchAll();
    }

    if (empty($vendors)) {
        $vendors = [];
    }
} catch (PDOException $e) {
    $dbError = 'พบปัญหาในการเชื่อมต่อหรือดึงข้อมูลจากฐานข้อมูล: ' . $e->getMessage();
} catch (Exception $e) {
    $dbError = 'เกิดข้อผิดพลาดของระบบ: ' . $e->getMessage();
}

$pageTitle = "ร้านค้าทั้งหมด";
require_once __DIR__ . '/../includes/header.php';
?>

<div class="mb-4 d-flex flex-column flex-md-row align-items-center justify-content-between gap-3">
  <div>
    <h2 class="fw-bold mb-1">🏪 ร้านค้าทั้งหมดบน <?php echo defined('SITE_NAME') ? safe_sanitize(SITE_NAME) : 'Shop'; ?></h2>
    <p class="text-muted mb-0">เลือกช้อปสินค้าคุณภาพจากผู้ขายหลากหลายร้านค้าที่เราคัดสรรมาให้คุณ</p>
  </div>
  <div class="d-flex gap-2">
    <a href="index.php" class="btn btn-outline-secondary rounded-pill px-3">← กลับไปหน้าหลัก</a>
    <?php if (function_exists('isLoggedIn') && isLoggedIn()): ?>
      <a href="register_store.php" class="btn btn-success rounded-pill px-4 fw-bold shadow-sm">➕ เปิดร้านค้าของคุณ</a>
    <?php else: ?>
      <a href="login.php?redirect=register_store.php" class="btn btn-success rounded-pill px-4 fw-bold shadow-sm">➕ เปิดร้านค้าของคุณ</a>
    <?php endif; ?>
  </div>
</div>

<?php if (!empty($dbError)): ?>
    <div class="alert alert-danger shadow-sm border-0 rounded-3 mb-4">
        <h5 class="fw-bold mb-2">⚠️ ระบบขัดข้องชั่วคราว</h5>
        <p class="mb-0">ขออภัย ไม่สามารถโหลดข้อมูลร้านค้าได้ในขณะนี้ กรุณาลองใหม่อีกครั้งในภายหลัง</p>
        <p class="mb-0 mt-2 text-muted small"><i>Details: <?php echo safe_sanitize($dbError); ?></i></p>
    </div>
<?php endif; ?>

<div class="row g-4">
  <?php if (empty($vendors)): ?>
    <div class="col-12 text-center py-5">
      <div class="fs-1">🏪</div>
      <h4 class="text-muted mt-2">ยังไม่มีร้านค้าเปิดให้บริการ</h4>
      <a href="index.php" class="btn btn-outline-primary rounded-pill mt-2">กลับไปหน้าหลัก</a>
    </div>
  <?php else: ?>
    <?php foreach ($vendors as $v): ?>
      <?php $vendorUrl = "shop.php?slug=" . urlencode(!empty($v['store_slug']) ? $v['store_slug'] : ($v['id'] ?? '')); ?>
      <div class="col-md-6 col-lg-4">
        <div class="card card-custom h-100 overflow-hidden shadow-sm hover-shadow transition">
          <!-- Banner Background -->
          <?php 
            $bannerPath = !empty($v['store_banner']) ? $v['store_banner'] : '';
            // ตรวจสอบ path รูปภาพป้องกันปัญหา
            $bannerUrl = '';
            if ($bannerPath) {
                // ใช้ strncmp แทน str_starts_with() เพื่อรองรับ PHP < 8.0
                $isAbsoluteUrl = (strncmp($bannerPath, 'http://', 7) === 0 || strncmp($bannerPath, 'https://', 8) === 0);
                $bannerUrl = defined('UPLOAD_URL') && !$isAbsoluteUrl
                             ? rtrim(UPLOAD_URL, '/') . '/' . ltrim($bannerPath, '/')
                             : $bannerPath;
            }
          ?>
          <div class="bg-secondary position-relative" style="height: 100px; background: <?php echo $bannerUrl ? "url('".safe_sanitize($bannerUrl)."') center/cover" : "linear-gradient(135deg, #4f46e5, #7c3aed)"; ?>;">
          </div>
          
          <div class="card-body pt-0 position-relative">
            <!-- Logo Avatar -->
            <div class="d-flex align-items-end justify-content-between mb-3" style="margin-top: -35px;">
              <?php 
                $logoPath = !empty($v['store_logo']) ? $v['store_logo'] : '';
                $logoUrl = '';
                if ($logoPath) {
                    // ใช้ strncmp แทน str_starts_with() เพื่อรองรับ PHP < 8.0
                    $logoIsAbsolute = (strncmp($logoPath, 'http://', 7) === 0 || strncmp($logoPath, 'https://', 8) === 0);
                    $logoUrl = defined('UPLOAD_URL') && !$logoIsAbsolute
                                 ? rtrim(UPLOAD_URL, '/') . '/' . ltrim($logoPath, '/')
                                 : $logoPath;
                }
              ?>
              <?php if (!empty($logoUrl)): ?>
                <img src="<?php echo safe_sanitize($logoUrl); ?>" 
                     class="rounded-circle border border-3 border-white shadow-sm bg-white" 
                     style="width: 70px; height: 70px; object-fit: cover;" 
                     alt="<?php echo safe_sanitize($v['store_name'] ?? ''); ?>"
                     onerror="this.onerror=null; this.src='assets/images/default-store.png';">
              <?php else: ?>
                <div class="rounded-circle border border-3 border-white shadow-sm bg-primary text-white d-flex align-items-center justify-content-center fw-bold fs-4" 
                     style="width: 70px; height: 70px;">
                  <?php echo mb_substr($v['store_name'] ?? 'S', 0, 1); ?>
                </div>
              <?php endif; ?>
              
              <span class="badge bg-primary text-white rounded-pill px-3 py-2 fw-semibold shadow-sm">
                📦 <?php echo (int)($v['product_count'] ?? 0); ?> สินค้า
              </span>
            </div>

            <h5 class="fw-bold mb-1">
              <a href="<?php echo safe_sanitize($vendorUrl); ?>" class="text-decoration-none text-dark">
                <?php echo safe_sanitize($v['store_name'] ?? 'ร้านค้า'); ?>
              </a>
            </h5>

            <p class="text-muted small mb-3 text-truncate-2" style="min-height: 40px;">
              <?php echo safe_sanitize(!empty($v['description']) ? $v['description'] : 'ร้านค้าคุณภาพ การันตีสินค้าตรงปก จัดส่งรวดเร็ว'); ?>
            </p>

            <a href="<?php echo safe_sanitize($vendorUrl); ?>" class="btn btn-primary-custom w-100 rounded-pill fw-bold py-2 shadow-sm d-flex align-items-center justify-content-center gap-2">
              <span>เข้าสู่ร้านค้า</span> 🛒
            </a>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

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