<?php
require_once 'config/config.php';

// Filtreleme ve sıralama
$category_filter = $_GET['category'] ?? '';
$sort = $_GET['sort'] ?? 'views'; // views, rating, reviews

// Kategoriler (sidebar için)
$stmt = $pdo->query("SELECT * FROM company_categories WHERE status = 'active' ORDER BY name");
$categories = $stmt->fetchAll();

// Firma sorgusu
$where = ["c.status = 'active'"];
$params = [];

if ($category_filter) {
    $where[] = "ccr.category_id = ?";
    $params[] = $category_filter;
}

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

// Sıralama
$orderBy = "c.views DESC";
switch ($sort) {
    case 'rating':
        $orderBy = "avg_rating DESC, c.views DESC";
        break;
    case 'reviews':
        $orderBy = "review_count DESC, c.views DESC";
        break;
    default:
        $orderBy = "c.views DESC";
}

$sql = "
    SELECT c.*, 
           (SELECT AVG(rating) FROM reviews WHERE company_id = c.id AND status = 'approved') as avg_rating,
           (SELECT COUNT(*) FROM reviews WHERE company_id = c.id AND status = 'approved') as review_count
    FROM companies c
    " . ($category_filter ? "INNER JOIN company_category_relations ccr ON c.id = ccr.company_id" : "") . "
    WHERE $whereClause
    ORDER BY $orderBy
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$companies = $stmt->fetchAll();

// Her firma için kategorileri al
foreach ($companies as &$company) {
    $stmt = $pdo->prepare("
        SELECT cc.* FROM company_categories cc
        INNER JOIN company_category_relations ccr ON cc.id = ccr.category_id
        WHERE ccr.company_id = ?
    ");
    $stmt->execute([$company['id']]);
    $company['categories'] = $stmt->fetchAll();
}
unset($company);

$page_title = 'Firmalar';
include 'includes/header.php';
?>

<div class="container mt-4">
    <div class="row">
        <!-- Sidebar - Kategoriler -->
        <div class="col-md-3 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Kategoriler</h5>
                </div>
                <div class="list-group list-group-flush">
                    <a href="companies.php"
                        class="list-group-item list-group-item-action <?= !$category_filter ? 'active' : '' ?>">
                        Tüm Kategoriler
                    </a>
                    <?php foreach ($categories as $cat): ?>
                        <a href="companies.php?category=<?= $cat['id'] ?>&sort=<?= $sort ?>"
                            class="list-group-item list-group-item-action <?= $category_filter == $cat['id'] ? 'active' : '' ?>">
                            <?= e($cat['name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Ana İçerik -->
        <div class="col-md-9">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>Firmalar</h1>
                <div>
                    <label class="form-label me-2">Sırala:</label>
                    <select class="form-select d-inline-block" style="width: auto;"
                        onchange="window.location.href='companies.php?category=<?= $category_filter ?>&sort=' + this.value">
                        <option value="views" <?= $sort === 'views' ? 'selected' : '' ?>>En Çok Ziyaret</option>
                        <option value="rating" <?= $sort === 'rating' ? 'selected' : '' ?>>En Yüksek Puan</option>
                        <option value="reviews" <?= $sort === 'reviews' ? 'selected' : '' ?>>En Çok Yorum</option>
                    </select>
                </div>
            </div>

            <?php if (empty($companies)): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>Firma bulunamadı.
                </div>
            <?php else: ?>
                <div class="row">
                    <?php foreach ($companies as $company): ?>
                        <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                            <div class="card h-100 shadow-sm hover-shadow transition">
                                <div class="card-body text-center position-relative">
                                    <!-- Link Wrap -->
                                    <a href="<?= SITE_URL ?>/firma/<?= e($company['slug'] ?? '') ?>"
                                        class="text-decoration-none text-dark">
                                        <!-- Logo -->
                                        <div class="mb-3">
                                            <?php if (!empty($company['logo'])): ?>
                                                <img src="<?= e(getImageUrl($company['logo'])) ?>"
                                                    alt="<?= e($company['company_name']) ?>" class="img-fluid bg-white"
                                                    style="width: 150px; height: 150px; object-fit: contain; border-radius: 50%; border: 3px solid #f8f9fa; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                                            <?php else: ?>
                                                <div class="d-inline-flex align-items-center justify-content-center bg-light text-secondary"
                                                    style="width: 150px; height: 150px; border-radius: 50%; border: 3px solid #dee2e6;">
                                                    <i class="fas fa-building fa-4x"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Firma Adı -->
                                        <h5 class="card-title mb-2 fw-bold text-primary"><?= e($company['company_name']) ?></h5>
                                    </a>

                                    <!-- Kategoriler -->
                                    <?php if (!empty($company['categories'])): ?>
                                        <div class="mb-3">
                                            <?php foreach ($company['categories'] as $cat): ?>
                                                <a href="<?= SITE_URL ?>/companies.php?category=<?= $cat['id'] ?>"
                                                    class="badge bg-info text-white me-1 mb-1 text-decoration-none">
                                                    <i class="fas fa-tag me-1"></i><?= e($cat['name']) ?>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Puanlama -->
                                    <?php if ($company['avg_rating']): ?>
                                        <div class="mb-3">
                                            <?= displayStars($company['avg_rating']) ?>
                                            <div class="mt-1 small">
                                                <strong class="text-dark"><?= number_format($company['avg_rating'], 1) ?>/5</strong>
                                                <span class="text-muted ms-1">(<?= $company['review_count'] ?> yorum)</span>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="mb-3 text-muted small">
                                            <i class="far fa-comment-dots me-1"></i>Henüz yorum yok
                                        </div>
                                    <?php endif; ?>

                                    <!-- Üyelik Tipi -->
                                    <div class="mb-2">
                                        <?php $isGold = in_array($company['membership_type'], ['gold', 'paid'], true); ?>
                                        <?php if ($isGold): ?>
                                            <span class="badge rounded-pill bg-warning text-dark border border-warning">
                                                <i class="fas fa-crown me-1"></i>Gold
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-footer bg-white border-top-0 pb-4 text-center">
                                    <a href="<?= SITE_URL ?>/firma/<?= e($company['slug']) ?>"
                                        class="btn btn-outline-primary w-75 rounded-pill">
                                        <i class="fas fa-arrow-right me-2"></i>İncele
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>