<?php
session_start();
require_once __DIR__ . '/config.php';

$settings = $conn->query('SELECT * FROM site_settings LIMIT 1')->fetch_assoc();
if (!$settings) {
    $settings = [
        'logo' => 'logo.png',
        'company_name' => 'AFS Motor Mekanik',
        'hero_title' => 'Premium Otomobil Servisi',
        'hero_text' => 'AFS Motor Mekanik olarak, İstanbul\'un en güvenilir otomobil servis hizmetini sunuyoruz. Uzman ekibimiz ve modern ekipmanlarımızla aracınız emin ellerde.',
        'hero_image' => 'hero.jpg',
        'phone' => '+90 555 123 45 67',
        'email' => 'info@afsmotor.com',
        'address' => 'İstanbul, Türkiye',
        'whatsapp' => '905551234567',
        'working_hours' => 'Pazartesi – Cumartesi 08:00–20:00',
        'city' => 'İstanbul',
        'about_image' => '',
    ];
}

$city = trim($settings['city'] ?? '') ?: 'İstanbul';
$workingHours = trim($settings['working_hours'] ?? '') ?: 'Pazartesi – Cumartesi 08:00–20:00';
$aboutFile = 'images/' . ($settings['about_image'] ?? '');

$services = [];
$serviceResult = $conn->query('SELECT * FROM services ORDER BY id ASC');
if ($serviceResult) {
    while ($row = $serviceResult->fetch_assoc()) {
        $services[] = $row;
    }
}

$galleryItems = [];
$galleryResult = $conn->query('SELECT * FROM gallery ORDER BY id DESC');
if ($galleryResult) {
    while ($row = $galleryResult->fetch_assoc()) {
        $galleryItems[] = $row;
    }
}

$isAdmin = isset($_SESSION['admin']);
$logoFile = 'images/' . $settings['logo'];
$heroFile = 'images/' . $settings['hero_image'];
$whatsapp = preg_replace('/\D+/', '', $settings['whatsapp']);

$companyWords = preg_split('/\s+/', trim($settings['company_name']));
$logoMain = $companyWords[0] ?? 'AFS';
$logoRest = implode(' ', array_slice($companyWords, 1));

$heroWords = preg_split('/\s+/', trim($settings['hero_title']));
$heroLast = array_pop($heroWords);
$heroStart = implode(' ', $heroWords);

function afs_service_icon($title) {
    $t = mb_strtolower($title, 'UTF-8');
    if (str_contains($t, 'motor')) return 'fa-gears';
    if (str_contains($t, 'lastik') || str_contains($t, 'jant')) return 'fa-dharmachakra';
    if (str_contains($t, 'elektrik')) return 'fa-bolt';
    if (str_contains($t, 'yağ') || str_contains($t, 'yag') || str_contains($t, 'filtre')) return 'fa-oil-can';
    if (str_contains($t, 'şanzıman') || str_contains($t, 'sanziman')) return 'fa-cogs';
    if (str_contains($t, 'koruma')) return 'fa-shield-halved';
    return 'fa-wrench';
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($settings['company_name']); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($settings['hero_text']); ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="style.css">
</head>
<body>

<?php if ($isAdmin): ?>
<div class="admin-bar">
    <span>Yönetici modu</span>
    <div>
        <a href="admin/dashboard.php">Dashboard</a>
        <a href="admin/services.php">Hizmetler</a>
        <a href="admin/gallery.php">Galeri</a>
        <a href="admin/messages.php">Mesajlar</a>
        <a href="admin/settings.php">Ayarlar</a>
    </div>
</div>
<?php endif; ?>

<div class="top-strip">
    <div class="container">
        <span class="hide-sm"><i class="fas fa-location-dot"></i> <?php echo htmlspecialchars($settings['address']); ?></span>
        <span class="hide-sm"><i class="far fa-clock"></i> <?php echo htmlspecialchars($workingHours); ?></span>
        <a href="tel:<?php echo htmlspecialchars(preg_replace('/\s+/', '', $settings['phone'])); ?>">
            <i class="fas fa-phone"></i> <?php echo htmlspecialchars($settings['phone']); ?>
        </a>
    </div>
</div>

<nav class="navbar">
    <div class="container">
        <a href="#" class="logo">
            <?php if (!empty($settings['logo']) && is_file($logoFile)): ?>
                <img src="<?php echo htmlspecialchars($logoFile); ?>" alt="<?php echo htmlspecialchars($settings['company_name']); ?>">
            <?php else: ?>
                <span class="logo-mark"><?php echo htmlspecialchars(mb_substr($logoMain, 0, 3)); ?></span>
            <?php endif; ?>
            <span class="logo-text">
                <b><?php echo htmlspecialchars($logoMain); ?></b> <?php echo htmlspecialchars($logoRest); ?>
                <small>MEKANİK SERVİS</small>
            </span>
        </a>
        <ul class="nav-links" id="navLinks">
            <li><a href="#services">Hizmetler</a></li>
            <li><a href="#gallery">Galeri</a></li>
            <li><a href="#about">Hakkımızda</a></li>
            <li><a href="#contact">İletişim</a></li>
            <li><a href="admin/index.php" class="admin-link"><i class="fas fa-user-lock"></i> Yönetici</a></li>
        </ul>
        <button class="hamburger" id="hamburger" aria-label="Menü">
            <span></span><span></span><span></span>
        </button>
    </div>
</nav>

<section class="hero">
    <div class="hero-bg"<?php if (!empty($settings['hero_image']) && is_file($heroFile)): ?> style="background-image:url('<?php echo htmlspecialchars($heroFile); ?>')"<?php endif; ?>></div>
    <div class="hero-overlay"></div>
    <div class="container">
        <div class="hero-content">
            <div class="kicker"><?php echo htmlspecialchars($city); ?> • Premium servis</div>
            <h1>
                <?php echo htmlspecialchars($heroStart); ?>
                <span><?php echo htmlspecialchars($heroLast); ?></span>
            </h1>
            <p><?php echo htmlspecialchars($settings['hero_text']); ?></p>
            <div class="hero-buttons">
                <a href="#contact" class="btn btn-primary">Randevu Al</a>
                <a href="#services" class="btn btn-outline">Hizmetlerimiz</a>
            </div>
            <div class="hero-stats">
                <div>
                    <span class="stat-num">10+</span>
                    <p>Yıl deneyim</p>
                </div>
                <div>
                    <span class="stat-num">500+</span>
                    <p>Mutlu müşteri</p>
                </div>
                <div>
                    <span class="stat-num">24/7</span>
                    <p>Destek hattı</p>
                </div>
            </div>
        </div>
        <div class="hero-panel">
            <?php if (!empty($settings['hero_image']) && is_file($heroFile)): ?>
                <img src="<?php echo htmlspecialchars($heroFile); ?>" alt="<?php echo htmlspecialchars($settings['company_name']); ?>">
            <?php endif; ?>
            <div class="panel-frame"></div>
            <div class="panel-tag">ATÖLYE • <?php echo htmlspecialchars(mb_strtoupper($city, 'UTF-8')); ?></div>
        </div>
    </div>
</section>

<section class="section services" id="services">
    <div class="container">
        <div class="section-head">
            <div class="kicker">Uzmanlık alanları</div>
            <h2>Hizmet<span>lerimiz</span></h2>
            <p>Aracınız için ihtiyaç duyduğunuz tüm mekanik işlemleri, aynı çatı altında ve garantili işçilikle sunuyoruz.</p>
        </div>
        <div class="services-grid">
            <?php
            $fallbackServices = [
                ['title' => 'Motor Bakımı', 'description' => 'Profesyonel motor bakım ve onarım hizmetleri.'],
                ['title' => 'Lastik & Jant', 'description' => 'Lastik değişimi, denge ve jant bakımı.'],
                ['title' => 'Elektrik Sistemleri', 'description' => 'Arıza tespiti ve elektrik sistem onarımı.'],
                ['title' => 'Yağ & Filtre', 'description' => 'Motor yağı değişimi ve filtre bakımı.'],
                ['title' => 'Şanzıman', 'description' => 'Otomatik ve manuel şanzıman onarımı.'],
                ['title' => 'Tam Koruma', 'description' => 'Kapsamlı araç bakım ve koruma paketleri.'],
            ];
            $list = $services ?: $fallbackServices;
            $i = 1;
            foreach ($list as $service):
                $num = str_pad((string) $i, 2, '0', STR_PAD_LEFT);
                $serviceImg = isset($service['image']) ? 'images/services/' . $service['image'] : '';
            ?>
            <article class="service-card">
                <?php if (!empty($service['image']) && is_file($serviceImg)): ?>
                    <img class="service-img" src="<?php echo htmlspecialchars($serviceImg); ?>" alt="<?php echo htmlspecialchars($service['title']); ?>">
                <?php endif; ?>
                <div class="service-top">
                    <span class="service-icon"><i class="fas <?php echo afs_service_icon($service['title']); ?>"></i></span>
                    <span class="service-num"><?php echo $num; ?></span>
                </div>
                <h3><?php echo htmlspecialchars($service['title']); ?></h3>
                <p><?php echo htmlspecialchars($service['description']); ?></p>
            </article>
            <?php $i++; endforeach; ?>
        </div>
    </div>
</section>

<section class="section gallery" id="gallery">
    <div class="container">
        <div class="section-head">
            <div class="kicker">Atölyeden kareler</div>
            <h2>Çalışma<span>larımız</span></h2>
            <p>Revizyon, bakım ve onarım süreçlerinden seçilmiş işler.</p>
        </div>
        <div class="gallery-grid">
            <?php if ($galleryItems): ?>
                <?php foreach ($galleryItems as $index => $item): ?>
                    <div class="gallery-item<?php echo $index === 0 ? ' large' : ''; ?>">
                        <img src="images/uploads/<?php echo htmlspecialchars($item['image']); ?>" alt="Çalışma">
                        <div class="gallery-overlay">
                            <small>ATÖLYE</small>
                            <strong>Servis kaydı</strong>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="gallery-item large"><i class="fas fa-car-side"></i><div class="gallery-overlay"><small>MOTOR</small><strong>Revizyon</strong></div></div>
                <div class="gallery-item"><i class="fas fa-gears"></i><div class="gallery-overlay"><small>BAKIM</small><strong>Periyodik</strong></div></div>
                <div class="gallery-item"><i class="fas fa-bolt"></i><div class="gallery-overlay"><small>ELEKTRİK</small><strong>Arıza tespit</strong></div></div>
            <?php endif; ?>
        </div>
    </div>
</section>

<section class="section about" id="about">
    <div class="container">
        <div class="about-grid">
            <div class="about-visual">
                <div class="about-frame">
                    <?php if (!empty($settings['about_image']) && is_file($aboutFile)): ?>
                        <img src="<?php echo htmlspecialchars($aboutFile); ?>" alt="<?php echo htmlspecialchars($settings['company_name']); ?>">
                    <?php elseif (!empty($settings['hero_image']) && is_file($heroFile)): ?>
                        <img src="<?php echo htmlspecialchars($heroFile); ?>" alt="<?php echo htmlspecialchars($settings['company_name']); ?>">
                    <?php endif; ?>
                </div>
                <div class="experience-box">
                    <strong>10+</strong>
                    <span>Yıllık saha deneyimi</span>
                </div>
            </div>
            <div class="about-copy">
                <div class="kicker">Kurumsal</div>
                <h2><?php echo htmlspecialchars($logoMain); ?> <span><?php echo htmlspecialchars($logoRest ?: 'Motor'); ?></span></h2>
                <p><?php echo htmlspecialchars($settings['hero_text']); ?></p>
                <p>Kaliteli işçilik, şeffaf fiyat ve teslim tarihinde sadakat — atölye disiplinimizi bunlarla kuruyoruz.</p>
                <div class="about-features">
                    <div><i class="fas fa-check"></i> Uzman ekip</div>
                    <div><i class="fas fa-check"></i> Garantili hizmet</div>
                    <div><i class="fas fa-check"></i> Diagnostik ekipman</div>
                    <div><i class="fas fa-check"></i> Net işçilik bedeli</div>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="cta">
    <div class="container">
        <div>
            <div class="kicker" style="color:#fff;">Randevu</div>
            <h2>Aracınızı uzman ellere bırakın</h2>
        </div>
        <a href="#contact" class="btn btn-outline">Hemen iletişime geç</a>
    </div>
</section>

<section class="section contact" id="contact">
    <div class="container">
        <div class="contact-grid">
            <div class="contact-copy">
                <div class="kicker">İletişim</div>
                <h2>Atölyeye <span>ulaşın</span></h2>
                <p>Randevu, keşif veya servis durumu için bizi arayın ya da formu doldurun.</p>
                <div class="contact-list">
                    <div>
                        <i class="fas fa-location-dot"></i>
                        <div><small>Adres</small><strong><?php echo htmlspecialchars($settings['address']); ?></strong></div>
                    </div>
                    <a href="tel:<?php echo htmlspecialchars(preg_replace('/\s+/', '', $settings['phone'])); ?>">
                        <i class="fas fa-phone"></i>
                        <div><small>Telefon</small><strong><?php echo htmlspecialchars($settings['phone']); ?></strong></div>
                    </a>
                    <a href="mailto:<?php echo htmlspecialchars($settings['email']); ?>">
                        <i class="fas fa-envelope"></i>
                        <div><small>E-posta</small><strong><?php echo htmlspecialchars($settings['email']); ?></strong></div>
                    </a>
                    <div>
                        <i class="far fa-clock"></i>
                        <div><small>Çalışma saatleri</small><strong><?php echo htmlspecialchars($workingHours); ?></strong></div>
                    </div>
                </div>
            </div>
            <form class="contact-form" action="send_message.php" method="post">
                <?php if (isset($_GET['sent'])): ?>
                    <div class="form-note success">Randevu talebiniz alındı. En kısa sürede dönüş yapacağız.</div>
                <?php elseif (isset($_GET['error'])): ?>
                    <div class="form-note error">Lütfen ad, geçerli e-posta ve mesaj alanlarını doldurun.</div>
                <?php endif; ?>
                <div class="form-row">
                    <input type="text" name="name" placeholder="Adınız soyadınız" required>
                    <input type="email" name="email" placeholder="E-posta" required>
                </div>
                <div class="form-row">
                    <input type="text" name="phone" placeholder="Telefon">
                    <input type="text" name="subject" value="Randevu Talebi" placeholder="Konu">
                </div>
                <textarea name="message" placeholder="Araç bilgisi, istediğiniz gün/saat ve notunuz" required></textarea>
                <button type="submit" class="btn btn-primary">Randevu talebi gönder</button>
            </form>
        </div>
    </div>
</section>

<footer class="footer">
    <div class="container">
        <div class="footer-grid">
            <div>
                <h3><b><?php echo htmlspecialchars($logoMain); ?></b> <?php echo htmlspecialchars($logoRest); ?></h3>
                <p>Ağır vasıta ve otomobil mekaniğinde ölçülebilir işçilik, net teslim.</p>
                <div class="social">
                    <a href="#" aria-label="Instagram"><i class="fab fa-instagram"></i></a>
                    <a href="#" aria-label="Facebook"><i class="fab fa-facebook-f"></i></a>
                    <a href="#" aria-label="YouTube"><i class="fab fa-youtube"></i></a>
                </div>
            </div>
            <div>
                <h4>Hizmetler</h4>
                <ul>
                    <?php foreach (array_slice($list, 0, 4) as $service): ?>
                        <li><a href="#services"><?php echo htmlspecialchars($service['title']); ?></a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div>
                <h4>Kurumsal</h4>
                <ul>
                    <li><a href="#about">Hakkımızda</a></li>
                    <li><a href="#gallery">Çalışmalar</a></li>
                    <li><a href="#contact">İletişim</a></li>
                </ul>
            </div>
            <div>
                <h4>İletişim</h4>
                <ul>
                    <li><a href="tel:<?php echo htmlspecialchars(preg_replace('/\s+/', '', $settings['phone'])); ?>"><?php echo htmlspecialchars($settings['phone']); ?></a></li>
                    <li><a href="mailto:<?php echo htmlspecialchars($settings['email']); ?>"><?php echo htmlspecialchars($settings['email']); ?></a></li>
                    <li><a href="#contact">Randevu al</a></li>
                </ul>
            </div>
        </div>
        <div class="footer-bottom">
            &copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($settings['company_name']); ?>. Tüm hakları saklıdır.
        </div>
    </div>
</footer>

<a class="whatsapp-float" href="https://wa.me/<?php echo htmlspecialchars($whatsapp); ?>" target="_blank" rel="noopener" aria-label="WhatsApp">
    <i class="fab fa-whatsapp"></i>
</a>

<script>
    const hamburger = document.getElementById('hamburger');
    const navLinks = document.getElementById('navLinks');
    hamburger.addEventListener('click', () => navLinks.classList.toggle('active'));
    document.querySelectorAll('.nav-links a').forEach((link) => {
        link.addEventListener('click', () => navLinks.classList.remove('active'));
    });
</script>
</body>
</html>
