<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/content.php';

function e(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function url(string $path = ''): string
{
    return rtrim(BASE_URL, '/') . '/' . ltrim($path, '/');
}

function branchUrl(string $slug): string
{
    return url('sube/' . $slug);
}

function blogUrl(string $slug): string
{
    return url('blog/' . $slug);
}

function branchImage(array $branch): string
{
    $map = [
        'eyup-yuzme-kursu' => 'assets/img/branch-eyup-pool.jpg',
        'basaksehir-yuzme-kursu' => 'assets/img/branch-basaksehir-pool.jpg',
        'topkapi-yuzme-kursu' => 'assets/img/branch-topkapi-pool.jpg',
        'merter-yuzme-kursu' => 'assets/img/branch-merter-pool.jpg',
        'beylikduzu-yuzme-kursu' => 'assets/img/branch-beylikduzu-pool.jpg',
    ];
    return $map[$branch['slug'] ?? ''] ?? ($branch['image'] ?? 'assets/img/spa-pool-background.jpg');
}

function serviceVisual(array $service): string
{
    $map = [
        'ozel-yuzme-dersi' => 'assets/img/private-swimming-lesson.jpg',
        'grup-yuzme-dersi' => 'assets/img/group-swimming-lesson.jpg',
        'aile-paketleri' => 'assets/img/family-swimming-package.jpg',
        'lisansli-sporcu-egitimi' => 'assets/img/licensed-athlete-training.jpg',
    ];
    return $map[$service['slug'] ?? ''] ?? 'assets/img/pool-water-texture.jpg';
}

function serviceIconType(array $service): string
{
    $map = [
        'ozel-yuzme-dersi' => 'coach',
        'grup-yuzme-dersi' => 'drop',
        'aile-paketleri' => 'family',
        'lisansli-sporcu-egitimi' => 'medal',
    ];
    return $map[$service['slug'] ?? ''] ?? 'water';
}

function blogVisual(array $post): string
{
    $slug = $post['slug'] ?? '';
    if (str_contains($slug, 'cocuk') || str_contains($slug, 'gelisim')) {
        return 'assets/img/blog-child-development.jpg';
    }
    if (str_contains($slug, 'yas')) {
        return 'assets/img/blog-swimming-age.jpg';
    }
    if (str_contains($slug, 'ozel') || str_contains($slug, 'grup')) {
        return 'assets/img/blog-private-vs-group.jpg';
    }
    if (str_contains($slug, 'korku')) {
        return 'assets/img/blog-water-fear.jpg';
    }
    return $post['image'] ?? 'assets/img/blog-placeholder.jpg';
}

function slugify(string $text): string
{
    $map = ['ı'=>'i','İ'=>'i','ğ'=>'g','Ğ'=>'g','ü'=>'u','Ü'=>'u','ş'=>'s','Ş'=>'s','ö'=>'o','Ö'=>'o','ç'=>'c','Ç'=>'c'];
    $text = strtr($text, $map);
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? $text;
    return trim($text, '-');
}

function fetchAllOrSeed(string $table, array $seed): array
{
    $pdo = db();
    if (!$pdo) {
        return $seed;
    }
    try {
        $stmt = $pdo->query("SELECT * FROM {$table} ORDER BY id ASC");
        $rows = $stmt->fetchAll();
        return $rows ?: $seed;
    } catch (Throwable $e) {
        return $seed;
    }
}

function getBranches(): array { return fetchAllOrSeed('branches', seedBranches()); }
function getServices(): array { return fetchAllOrSeed('services', seedServices()); }
function getBlogPosts(): array { return fetchAllOrSeed('blog_posts', seedBlogPosts()); }

function findBySlug(array $items, string $slug): ?array
{
    foreach ($items as $item) {
        if (($item['slug'] ?? '') === $slug) {
            return $item;
        }
    }
    return null;
}

function csrfToken(): string
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCsrf(): bool
{
    return isset($_POST['csrf_token'], $_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$_POST['csrf_token']);
}

function isAdmin(): bool
{
    return !empty($_SESSION['admin_id']);
}

function requireAdmin(): void
{
    if (!isAdmin()) {
        header('Location: login.php');
        exit;
    }
}

function pageMeta(array $overrides = []): array
{
    return array_merge([
        'title' => 'ASSK Yüzme Kursu | İstanbul Premium Yüzme Eğitimi',
        'description' => 'ASSK Yüzme Kursu; Eyüp, Başakşehir, Topkapı, Merter ve Beylikdüzü lokasyonlarında özel yüzme dersi, grup dersi ve lisanslı sporcu eğitimi sunar.',
        'keywords' => 'yüzme kursu, özel yüzme dersi, çocuk yüzme kursu, aile yüzme paketi, lisanslı sporcu yüzme eğitimi',
        'image' => url('assets/img/hero-luxury-pool.jpg'),
        'canonical' => url(basename($_SERVER['SCRIPT_NAME'] ?? 'index.php')),
    ], $overrides);
}

function insertLead(array $data): bool
{
    $pdo = db();
    if (!$pdo) {
        $_SESSION['offline_lead'] = $data;
        return true;
    }
    $stmt = $pdo->prepare('INSERT INTO contact_leads (full_name, phone, branch, service, message, created_at) VALUES (:full_name, :phone, :branch, :service, :message, NOW())');
    return $stmt->execute([
        ':full_name' => $data['full_name'],
        ':phone' => $data['phone'],
        ':branch' => $data['branch'],
        ':service' => $data['service'],
        ':message' => $data['message'],
    ]);
}

function leadForm(?string $selectedBranch = null): string
{
    $branches = getBranches();
    $services = getServices();
    ob_start();
    ?>
    <form class="lead-form glass-card reveal" method="post" action="<?= e(url('submit-lead.php')) ?>">
        <div class="form-intro">
            <span class="eyebrow">ASSK ile planlayın</span>
            <h3>Ders Programı Hakkında Bilgi Alın</h3>
            <p>Şube, hizmet ve hedefinizi seçin; ekip sizin için en uygun başlangıç planını hazırlasın.</p>
        </div>
        <input type="hidden" name="csrf_token" value="<?= e(csrfToken()) ?>">
        <input type="text" name="website" class="hp-field" tabindex="-1" autocomplete="off" aria-hidden="true">
        <div class="form-grid">
            <label><span>Ad Soyad</span><input required name="full_name" maxlength="120" placeholder="Adınız ve soyadınız"></label>
            <label><span>Telefon</span><input required name="phone" maxlength="30" inputmode="tel" placeholder="0552 695 48 90"></label>
            <label><span>Şube Seçimi</span><select required name="branch">
                <option value="">Size en yakın şube</option>
                <?php foreach ($branches as $branch): ?>
                    <option value="<?= e($branch['name']) ?>" <?= $selectedBranch === $branch['name'] ? 'selected' : '' ?>><?= e($branch['name']) ?></option>
                <?php endforeach; ?>
            </select></label>
            <label><span>Hizmet Seçimi</span><select required name="service">
                <option value="">Program seçin</option>
                <?php foreach ($services as $service): ?>
                    <option value="<?= e($service['title']) ?>"><?= e($service['title']) ?></option>
                <?php endforeach; ?>
            </select></label>
        </div>
        <label><span>Mesaj</span><textarea name="message" rows="4" maxlength="1000" placeholder="Öğrencinin yaşı, hedefi veya tercih ettiğiniz saatleri yazabilirsiniz."></textarea></label>
        <button class="btn btn-primary" type="submit">Yüzme Eğitimine Bugün Başlayın</button>
    </form>
    <?php
    return (string)ob_get_clean();
}

function localBusinessSchema(?array $branch = null): string
{
    $schema = [
        '@context' => 'https://schema.org',
        '@type' => 'SportsActivityLocation',
        'name' => $branch ? 'ASSK Yüzme Kursu - ' . $branch['name'] : 'ASSK Yüzme Kursu',
        'telephone' => CONTACT_TEL,
        'url' => BASE_URL,
        'image' => url($branch['image'] ?? 'assets/img/hero-luxury-pool.jpg'),
        'address' => $branch['address'] ?? 'Istanbul',
        'areaServed' => 'Istanbul',
        'sport' => 'Swimming',
    ];
    return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '</script>';
}
