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

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

$company = null;

if (!empty($slug)) {
    // Slug ile ara (URL'den gelen)
    $stmt = $pdo->prepare("
        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
        WHERE c.slug = ? AND c.status = 'active'
    ");
    $stmt->execute([$slug]);
    $company = $stmt->fetch();
} elseif ($id > 0) {
    // ID ile ara (Fallback)
    $stmt = $pdo->prepare("
        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
        WHERE c.id = ? AND c.status = 'active'
    ");
    $stmt->execute([$id]);
    $company = $stmt->fetch();
}

if (!$company) {
    header("HTTP/1.0 404 Not Found");
    include '404.php';
    exit;
}

// Diğer sorgular için ID'yi ayarla
$id = $company['id'];

// Görüntülenme sayısını artır
$stmt = $pdo->prepare("UPDATE companies SET views = views + 1 WHERE id = ?");
$stmt->execute([$id]);

// Firma kategorileri
$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 = ? AND cc.status = 'active'
    ORDER BY cc.name
");
$stmt->execute([$id]);
$companyCategories = $stmt->fetchAll();

// Firma resimleri
$stmt = $pdo->prepare("
    SELECT * FROM company_images
    WHERE company_id = ?
    ORDER BY sort_order ASC, id ASC
");
$stmt->execute([$id]);
$companyImages = $stmt->fetchAll();

// Firma hizmetleri
$stmt = $pdo->prepare("
    SELECT s.*
    FROM services s
    WHERE s.company_id = ? AND s.status = 'active'
    ORDER BY s.views DESC, s.created_at DESC
");
$stmt->execute([$id]);
$services = $stmt->fetchAll();

// Yorumlar
$stmt = $pdo->prepare("
    SELECT * FROM reviews
    WHERE company_id = ? AND status = 'approved'
    ORDER BY created_at DESC
");
$stmt->execute([$id]);
$reviews = $stmt->fetchAll();

$page_title = $company['company_name'];
include 'includes/header.php';

$isGold = isGoldMember($company);
?>

<div class="container mt-4">
    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between flex-wrap gap-3">
                        <div class="d-flex align-items-center gap-3">
                            <?php if (!empty($company['logo'])): ?>
                                <img src="<?= e(getImageUrl($company['logo'])) ?>" alt="<?= e($company['company_name']) ?>"
                                    class="img-thumbnail" style="width: 90px; height: 90px; object-fit: contain;">
                            <?php else: ?>
                                <div class="d-inline-flex align-items-center justify-content-center bg-light"
                                    style="width: 90px; height: 90px; border-radius: 8px; border: 1px solid #dee2e6;">
                                    <i class="fas fa-building fa-2x text-muted"></i>
                                </div>
                            <?php endif; ?>

                            <div>
                                <h1 class="h3 mb-1"><?= e($company['company_name']) ?></h1>
                                <div class="text-muted small">
                                    <i class="fas fa-eye me-1"></i><?= (int) $company['views'] ?> görüntülenme
                                </div>

                                <?php if (!empty($company['avg_rating'])): ?>
                                    <div class="mt-2">
                                        <?= displayStars($company['avg_rating']) ?>
                                        <span
                                            class="ms-2"><strong><?= number_format((float) $company['avg_rating'], 1) ?>/5</strong></span>
                                        <span class="text-muted ms-1">(<?= (int) $company['review_count'] ?> yorum)</span>
                                    </div>
                                <?php else: ?>
                                    <div class="mt-2 text-muted small">Henüz yorum yapılmamış</div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if ($isGold): ?>
                            <div class="text-end">
                                <?php if (!empty($company['phone'])): ?>
                                    <a href="tel:<?= e($company['phone']) ?>" class="btn btn-success mb-2">
                                        <i class="fas fa-phone me-2"></i>Hemen Ara
                                    </a>
                                <?php endif; ?>
                                <?php if (!empty($company['whatsapp'])): ?>
                                    <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $company['whatsapp']) ?>"
                                        target="_blank" class="btn btn-success mb-2"
                                        style="background-color:#25D366;border-color:#25D366;">
                                        <i class="fab fa-whatsapp me-2"></i>WhatsApp
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($companyCategories)): ?>
                        <div class="mt-3">
                            <?php foreach ($companyCategories as $cat): ?>
                                <a href="<?= SITE_URL ?>/<?= e($cat['slug']) ?>"
                                    class="badge bg-primary me-1 mb-1"><?= e($cat['name']) ?></a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($company['about'])): ?>
                        <hr>
                        <div class="company-about">
                            <?= nl2br(e($company['about'])) ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($isGold): ?>
                        <?php
                        $hasSocialCols = columnExists('companies', 'instagram');
                        $instagram = $company['instagram'] ?? '';
                        $facebook = $company['facebook'] ?? '';
                        $youtube = $company['youtube'] ?? '';
                        $other_social = $company['other_social'] ?? '';
                        ?>
                        <?php if ($hasSocialCols && ($instagram || $facebook || $youtube || $other_social)): ?>
                            <hr>
                            <div>
                                <h5 class="mb-3">Sosyal Medya</h5>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php if ($instagram): ?>
                                        <a class="btn btn-outline-danger btn-sm" target="_blank" href="<?= e($instagram) ?>"><i
                                                class="fab fa-instagram me-1"></i>Instagram</a>
                                    <?php endif; ?>
                                    <?php if ($facebook): ?>
                                        <a class="btn btn-outline-primary btn-sm" target="_blank" href="<?= e($facebook) ?>"><i
                                                class="fab fa-facebook me-1"></i>Facebook</a>
                                    <?php endif; ?>
                                    <?php if ($youtube): ?>
                                        <a class="btn btn-outline-danger btn-sm" target="_blank" href="<?= e($youtube) ?>"><i
                                                class="fab fa-youtube me-1"></i>YouTube</a>
                                    <?php endif; ?>
                                    <?php if ($other_social): ?>
                                        <a class="btn btn-outline-secondary btn-sm" target="_blank"
                                            href="<?= e($other_social) ?>"><i class="fas fa-link me-1"></i>Bağlantı</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!empty($companyImages)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">Fotoğraflar</h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <?php foreach ($companyImages as $img): ?>
                                <div class="col-6 col-md-4">
                                    <img src="<?= e(getImageUrl($img['image_url'])) ?>" class="img-fluid rounded" alt=""
                                        style="width:100%;height:180px;object-fit:cover;">
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!empty($services)): ?>
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Hizmetler</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($services as $service): ?>
                                <div class="col-md-6 mb-4">
                                    <div class="card h-100">
                                        <?php if (!empty($service['image'])): ?>
                                            <img src="<?= e(getImageUrl($service['image'])) ?>" class="card-img-top"
                                                alt="<?= e($service['title']) ?>" style="height: 180px; object-fit: cover;">
                                        <?php endif; ?>
                                        <div class="card-body">
                                            <h6 class="card-title mb-2"><?= e($service['title']) ?></h6>
                                            <p class="card-text small text-muted mb-3">
                                                <?= e(excerpt(strip_tags($service['description']), 100)) ?></p>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <?php if (!empty($service['price'])): ?>
                                                    <span
                                                        class="text-primary fw-bold"><?= number_format((float) $service['price'], 2) ?>
                                                        ₺</span>
                                                <?php else: ?>
                                                    <span></span>
                                                <?php endif; ?>
                                                <a href="<?= SITE_URL ?>/hizmet/<?= (int) $service['id'] ?>"
                                                    class="btn btn-sm btn-primary">Detay</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Yorumlar</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($reviews)): ?>
                        <p class="text-muted mb-0">Henüz yorum yapılmamış.</p>
                    <?php else: ?>
                        <?php foreach ($reviews as $review): ?>
                            <div class="border-bottom pb-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong><?= e($review['name'] . ' ' . $review['surname']) ?></strong>
                                        <div class="text-muted small"><?= formatDate($review['created_at'], 'd.m.Y') ?></div>
                                    </div>
                                    <div><?= displayStars($review['rating']) ?></div>
                                </div>
                                <div class="mt-2"><?= nl2br(e($review['comment'])) ?></div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card mb-5">
                <div class="card-header">
                    <h5 class="mb-0">Yorum Yap</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="<?= SITE_URL ?>/submit-review.php">
                        <input type="hidden" name="company_id" value="<?= (int) $company['id'] ?>">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Ad</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Soyad</label>
                                <input type="text" class="form-control" name="surname" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">E-posta</label>
                            <input type="email" class="form-control" name="email" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Puan</label>
                            <select class="form-select" name="rating" required>
                                <option value="">Seçin</option>
                                <option value="5">5</option>
                                <option value="4">4</option>
                                <option value="3">3</option>
                                <option value="2">2</option>
                                <option value="1">1</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Yorum</label>
                            <textarea class="form-control" name="comment" rows="4" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-2"></i>Gönder
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">İletişim</h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($company['address'])): ?>
                        <p class="mb-2"><i class="fas fa-map-marker-alt me-2 text-muted"></i><?= e($company['address']) ?>
                        </p>
                    <?php endif; ?>
                    <?php if (!empty($company['phone'])): ?>
                        <p class="mb-2"><i class="fas fa-phone me-2 text-muted"></i><?= e($company['phone']) ?></p>
                    <?php endif; ?>
                    <?php if (!$isGold): ?>
                        <div class="alert alert-info small mb-0">
                            <i class="fas fa-crown me-2"></i>WhatsApp ve hızlı arama gibi özellikler Gold paket ile
                            aktiftir.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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