<?php
declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

$config = require BASE_PATH . '/config/config.php';
$GLOBALS['zalorox_config'] = $config;

require BASE_PATH . '/app/Core/Helpers.php';

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';

    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }

    $file = BASE_PATH . '/app/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';

    if (is_file($file)) {
        require $file;
    }
});

$pdo = \App\Core\Database::connection($config);

function upsert(PDO $pdo, string $table, array $data, array $uniqueKeys): void
{
    $columns = array_keys($data);
    $placeholders = array_map(static fn (string $column): string => ':' . $column, $columns);
    $updates = array_values(array_diff($columns, $uniqueKeys));
    $updateSql = implode(', ', array_map(static fn (string $column): string => "{$column} = VALUES({$column})", $updates));

    $sql = sprintf(
        'INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s',
        $table,
        implode(', ', $columns),
        implode(', ', $placeholders),
        $updateSql === '' ? $uniqueKeys[0] . ' = ' . $uniqueKeys[0] : $updateSql
    );

    $statement = $pdo->prepare($sql);
    $statement->execute($data);
}

function seedComment(PDO $pdo, array $data): void
{
    $statement = $pdo->prepare(
        'SELECT id FROM comments
         WHERE content_type = :content_type
           AND content_id = :content_id
           AND user_id = :user_id
           AND content = :content
         LIMIT 1'
    );
    $statement->execute([
        'content_type' => $data['content_type'],
        'content_id' => $data['content_id'],
        'user_id' => $data['user_id'],
        'content' => $data['content'],
    ]);

    if ($statement->fetchColumn()) {
        return;
    }

    $insert = $pdo->prepare(
        'INSERT INTO comments
            (content_type, content_id, commentable_type, commentable_id, user_id, parent_id, content, body, status, risk_score, created_at, updated_at)
         VALUES
            (:content_type, :content_id, :commentable_type, :commentable_id, :user_id, :parent_id, :content, :body, :status, :risk_score, :created_at, :updated_at)'
    );
    $insert->execute([
        'content_type' => $data['content_type'],
        'content_id' => $data['content_id'],
        'commentable_type' => $data['content_type'],
        'commentable_id' => $data['content_id'],
        'user_id' => $data['user_id'],
        'parent_id' => $data['parent_id'] ?? null,
        'content' => $data['content'],
        'body' => $data['content'],
        'status' => $data['status'] ?? 'published',
        'risk_score' => $data['risk_score'] ?? 0,
        'created_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
        'updated_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
    ]);
}

function seedSubscription(PDO $pdo, array $data): void
{
    $statement = $pdo->prepare(
        'SELECT id FROM subscriptions
         WHERE (subscriber_id = :subscriber_lookup OR user_id = :user_lookup)
           AND creator_id = :creator_id
           AND package_id = :package_id
         LIMIT 1'
    );
    $statement->execute([
        'subscriber_lookup' => $data['subscriber_id'],
        'user_lookup' => $data['subscriber_id'],
        'creator_id' => $data['creator_id'],
        'package_id' => $data['package_id'],
    ]);

    $existingId = (int) ($statement->fetchColumn() ?: 0);
    if ($existingId > 0) {
        $update = $pdo->prepare(
            'UPDATE subscriptions
             SET subscriber_id = :subscriber_id,
                 user_id = :user_id,
                 creator_id = :creator_id,
                 package_id = :package_id,
                 order_id = :order_id,
                 starts_at = :starts_at,
                 ends_at = :ends_at,
                 status = :status,
                 updated_at = NOW()
             WHERE id = :id'
        );
        $update->execute($data + ['id' => $existingId]);

        return;
    }

    $insert = $pdo->prepare(
        'INSERT INTO subscriptions
            (subscriber_id, user_id, creator_id, package_id, order_id, starts_at, ends_at, status, created_at, updated_at)
         VALUES
            (:subscriber_id, :user_id, :creator_id, :package_id, :order_id, :starts_at, :ends_at, :status, NOW(), NOW())'
    );
    $insert->execute($data);
}

function seedCommunityPost(PDO $pdo, array $data, array $pollOptions = []): int
{
    $statement = $pdo->prepare(
        'SELECT id FROM community_posts
         WHERE user_id = :user_id
           AND post_type = :post_type
           AND COALESCE(content, "") = COALESCE(:content, "")
           AND COALESCE(poll_question, "") = COALESCE(:poll_question, "")
         LIMIT 1'
    );
    $statement->execute([
        'user_id' => $data['user_id'],
        'post_type' => $data['post_type'],
        'content' => $data['content'] ?? null,
        'poll_question' => $data['poll_question'] ?? null,
    ]);

    $existingId = (int) ($statement->fetchColumn() ?: 0);
    if ($existingId > 0) {
        return $existingId;
    }

    $insert = $pdo->prepare(
        'INSERT INTO community_posts
            (user_id, post_type, content, image_path, poll_question, status, risk_score, created_at, updated_at)
         VALUES
            (:user_id, :post_type, :content, :image_path, :poll_question, :status, :risk_score, :created_at, :updated_at)'
    );
    $insert->execute([
        'user_id' => $data['user_id'],
        'post_type' => $data['post_type'],
        'content' => $data['content'] ?? null,
        'image_path' => $data['image_path'] ?? null,
        'poll_question' => $data['poll_question'] ?? null,
        'status' => $data['status'] ?? 'published',
        'risk_score' => $data['risk_score'] ?? 0,
        'created_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
        'updated_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
    ]);
    $postId = (int) $pdo->lastInsertId();

    if (($data['post_type'] ?? '') === 'poll') {
        $optionInsert = $pdo->prepare(
            'INSERT INTO community_poll_options (post_id, option_text, vote_count, sort_order, created_at)
             VALUES (:post_id, :option_text, :vote_count, :sort_order, NOW())'
        );
        foreach (array_values($pollOptions) as $index => $option) {
            $optionInsert->execute([
                'post_id' => $postId,
                'option_text' => (string) ($option['text'] ?? $option),
                'vote_count' => (int) ($option['votes'] ?? 0),
                'sort_order' => $index + 1,
            ]);
        }
    }

    return $postId;
}

function seedCommunityComment(PDO $pdo, array $data): void
{
    $statement = $pdo->prepare(
        'SELECT id FROM community_comments
         WHERE post_id = :post_id AND user_id = :user_id AND content = :content
         LIMIT 1'
    );
    $statement->execute([
        'post_id' => $data['post_id'],
        'user_id' => $data['user_id'],
        'content' => $data['content'],
    ]);
    if ($statement->fetchColumn()) {
        return;
    }

    $pdo->prepare(
        'INSERT INTO community_comments
            (post_id, user_id, parent_id, content, status, risk_score, created_at, updated_at)
         VALUES
            (:post_id, :user_id, NULL, :content, :status, :risk_score, :created_at, :updated_at)'
    )->execute([
        'post_id' => $data['post_id'],
        'user_id' => $data['user_id'],
        'content' => $data['content'],
        'status' => $data['status'] ?? 'published',
        'risk_score' => $data['risk_score'] ?? 0,
        'created_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
        'updated_at' => $data['created_at'] ?? date('Y-m-d H:i:s'),
    ]);
}

function seedStory(PDO $pdo, array $data): void
{
    $statement = $pdo->prepare(
        'SELECT id FROM stories
         WHERE user_id = :user_id AND story_type = :story_type AND COALESCE(content, "") = COALESCE(:content, "")
         LIMIT 1'
    );
    $statement->execute([
        'user_id' => $data['user_id'],
        'story_type' => $data['story_type'],
        'content' => $data['content'] ?? null,
    ]);
    $existingId = (int) ($statement->fetchColumn() ?: 0);
    if ($existingId > 0) {
        $pdo->prepare(
            'UPDATE stories
             SET status = "active", expires_at = DATE_ADD(NOW(), INTERVAL 24 HOUR), deleted_at = NULL
             WHERE id = :id'
        )->execute(['id' => $existingId]);
        return;
    }

    $pdo->prepare(
        'INSERT INTO stories
            (user_id, story_type, content, media_path, link_url, status, expires_at, created_at, deleted_at)
         VALUES
            (:user_id, :story_type, :content, :media_path, :link_url, "active", DATE_ADD(NOW(), INTERVAL 24 HOUR), NOW(), NULL)'
    )->execute([
        'user_id' => $data['user_id'],
        'story_type' => $data['story_type'],
        'content' => $data['content'] ?? null,
        'media_path' => $data['media_path'] ?? null,
        'link_url' => $data['link_url'] ?? null,
    ]);
}

$users = [
    ['username' => 'admin', 'email' => 'admin@localhost.test', 'password_hash' => password_hash('admin12345', PASSWORD_DEFAULT), 'nickname' => 'Zalorox Admin', 'role' => 'admin', 'status' => 'active', 'language' => 'tr'],
    ['username' => 'creator', 'email' => 'creator@localhost.test', 'password_hash' => password_hash('creator12345', PASSWORD_DEFAULT), 'nickname' => 'Zalorox Creator', 'role' => 'creator', 'status' => 'active', 'language' => 'tr'],
    ['username' => 'user', 'email' => 'user@localhost.test', 'password_hash' => password_hash('user12345', PASSWORD_DEFAULT), 'nickname' => 'Zalorox User', 'role' => 'user', 'status' => 'active', 'language' => 'tr'],
    ['username' => 'test_admin', 'email' => 'test_admin@localhost.test', 'password_hash' => password_hash('testadmin123', PASSWORD_DEFAULT), 'nickname' => 'Zalorox Test Admin', 'role' => 'admin', 'status' => 'active', 'language' => 'tr'],
    ['username' => 'test_creator', 'email' => 'test_creator@localhost.test', 'password_hash' => password_hash('testcreator123', PASSWORD_DEFAULT), 'nickname' => 'Zalorox Test Creator', 'role' => 'creator', 'status' => 'active', 'language' => 'tr'],
    ['username' => 'test_user', 'email' => 'test_user@localhost.test', 'password_hash' => password_hash('testuser123', PASSWORD_DEFAULT), 'nickname' => 'Zalorox Test User', 'role' => 'user', 'status' => 'active', 'language' => 'tr'],
];

foreach ($users as $user) {
    upsert($pdo, 'users', $user, ['email']);
}

$userIds = [];
$seedUsernames = array_map(static fn (array $user): string => $user['username'], $users);
$statement = $pdo->query('SELECT id, username FROM users WHERE username IN ("' . implode('","', array_map(static fn (string $username): string => str_replace('"', '\"', $username), $seedUsernames)) . '")');
foreach ($statement->fetchAll() as $row) {
    $userIds[$row['username']] = (int) $row['id'];
}

$profiles = [
    ['user_id' => $userIds['admin'], 'display_name' => 'Zalorox Admin', 'nickname' => 'admin', 'bio' => 'ZPanel yoneticisi.'],
    ['user_id' => $userIds['creator'], 'display_name' => 'Zalorox Creator', 'nickname' => 'creator', 'bio' => 'Mod ve muzik ureticisi.'],
    ['user_id' => $userIds['user'], 'display_name' => 'Zalorox User', 'nickname' => 'user', 'bio' => 'Standart uye.'],
    ['user_id' => $userIds['test_admin'], 'display_name' => 'Zalorox Test Admin', 'nickname' => 'test_admin', 'bio' => 'Test modu admin hesabi.'],
    ['user_id' => $userIds['test_creator'], 'display_name' => 'Zalorox Test Creator', 'nickname' => 'test_creator', 'bio' => 'Test modu creator hesabi.'],
    ['user_id' => $userIds['test_user'], 'display_name' => 'Zalorox Test User', 'nickname' => 'test_user', 'bio' => 'Test modu standart uye hesabi.'],
];

foreach ($profiles as $profile) {
    upsert($pdo, 'profiles', $profile, ['user_id']);
}

$userProfiles = [
    ['user_id' => $userIds['admin'], 'nickname' => 'admin', 'display_name' => 'Zalorox Admin', 'about' => 'ZPanel yoneticisi.', 'avatar' => '/assets/img/logo-zpanel.png', 'cover_image' => '/uploads/covers/mod-3.svg', 'instagram' => 'https://instagram.com/zalorox', 'youtube' => 'https://youtube.com/@zalorox', 'website' => 'https://zalorox.com', 'privacy' => 'public', 'message_privacy' => 'everyone', 'billing_email' => 'admin@localhost.test'],
    ['user_id' => $userIds['creator'], 'nickname' => 'creator', 'display_name' => 'Zalorox Creator', 'about' => 'FS25 premium mod paketleri, muzik demolari ve destekci icerikleri yayinlayan test creator profili.', 'avatar' => '/assets/img/logo-studio.png', 'cover_image' => '/uploads/covers/mod-1.svg', 'instagram' => 'https://instagram.com/zaloroxcreator', 'youtube' => 'https://youtube.com/@zaloroxcreator', 'website' => 'https://zalorox.com', 'privacy' => 'public', 'message_privacy' => 'friends', 'billing_email' => 'creator@localhost.test'],
    ['user_id' => $userIds['user'], 'nickname' => 'user', 'display_name' => 'Zalorox User', 'about' => 'Standart uye.', 'avatar' => '/assets/img/logo.gif', 'cover_image' => '/uploads/covers/mod-2.svg', 'instagram' => null, 'youtube' => null, 'website' => null, 'privacy' => 'public', 'message_privacy' => 'everyone', 'billing_email' => 'user@localhost.test'],
    ['user_id' => $userIds['test_admin'], 'nickname' => 'test_admin', 'display_name' => 'Zalorox Test Admin', 'about' => 'Test modu admin hesabi.', 'avatar' => '/assets/img/logo-zpanel.png', 'cover_image' => '/uploads/covers/mod-3.svg', 'instagram' => null, 'youtube' => null, 'website' => 'https://zalorox.com', 'privacy' => 'public', 'message_privacy' => 'everyone', 'billing_email' => 'test_admin@localhost.test'],
    ['user_id' => $userIds['test_creator'], 'nickname' => 'test_creator', 'display_name' => 'Zalorox Test Creator', 'about' => 'Test modu creator hesabi. Profil sayfasi, paket kartlari ve takip aksiyonlari icin ornek veriler icerir.', 'avatar' => '/assets/img/logo-studio.png', 'cover_image' => '/uploads/covers/mod-1.svg', 'instagram' => 'https://instagram.com/zaloroxtest', 'youtube' => 'https://youtube.com/@zaloroxtest', 'website' => 'https://zalorox.com', 'privacy' => 'public', 'message_privacy' => 'everyone', 'billing_email' => 'test_creator@localhost.test'],
    ['user_id' => $userIds['test_user'], 'nickname' => 'test_user', 'display_name' => 'Zalorox Test User', 'about' => 'Test modu standart uye hesabi.', 'avatar' => '/assets/img/logo.gif', 'cover_image' => '/uploads/covers/mod-2.svg', 'instagram' => null, 'youtube' => null, 'website' => null, 'privacy' => 'public', 'message_privacy' => 'everyone', 'billing_email' => 'test_user@localhost.test'],
];

foreach ($userProfiles as $profile) {
    upsert($pdo, 'user_profiles', $profile, ['user_id']);
}

$communityTextPostId = seedCommunityPost($pdo, [
    'user_id' => $userIds['creator'],
    'post_type' => 'text',
    'content' => 'FS25 Pro Farm Pack icin yeni ekran goruntuleri ve destekci notlari bugun Studio akisine eklendi.',
    'image_path' => null,
    'poll_question' => null,
    'status' => 'published',
    'risk_score' => 2,
    'created_at' => date('Y-m-d H:i:s', strtotime('-3 hours')),
]);

$communityImagePostId = seedCommunityPost($pdo, [
    'user_id' => $userIds['creator'],
    'post_type' => 'image',
    'content' => 'Yeni harita testinden kisa bir kare. Yol detaylarini haftalik secime tasiyorum.',
    'image_path' => '/uploads/covers/mod-2.svg',
    'poll_question' => null,
    'status' => 'published',
    'risk_score' => 1,
    'created_at' => date('Y-m-d H:i:s', strtotime('-1 day')),
]);

$communityPollPostId = seedCommunityPost($pdo, [
    'user_id' => $userIds['creator'],
    'post_type' => 'poll',
    'content' => null,
    'image_path' => null,
    'poll_question' => 'Sonraki premium testte hangisini one alalim?',
    'status' => 'published',
    'risk_score' => 1,
    'created_at' => date('Y-m-d H:i:s', strtotime('-2 days')),
], [
    ['text' => 'Yeni traktor paketi', 'votes' => 7],
    ['text' => 'Harita genisletmesi', 'votes' => 5],
    ['text' => 'Ses paketi', 'votes' => 3],
]);

$pdo->prepare(
    'INSERT INTO community_reactions (post_id, user_id, reaction, created_at)
     VALUES (:post_id, :user_id, "like", NOW())
     ON DUPLICATE KEY UPDATE reaction = VALUES(reaction), created_at = NOW()'
)->execute(['post_id' => $communityTextPostId, 'user_id' => $userIds['user']]);

seedCommunityComment($pdo, [
    'post_id' => $communityTextPostId,
    'user_id' => $userIds['user'],
    'content' => 'Yeni paket notlari cok iyi gorunuyor, test linkini bekliyorum.',
    'status' => 'published',
    'risk_score' => 1,
    'created_at' => date('Y-m-d H:i:s', strtotime('-2 hours')),
]);

seedStory($pdo, [
    'user_id' => $userIds['creator'],
    'story_type' => 'image',
    'content' => 'Bugunku FS25 testinden 24 saatlik durum.',
    'media_path' => '/uploads/covers/mod-1.svg',
    'link_url' => 'https://zalorox.com',
]);

seedStory($pdo, [
    'user_id' => $userIds['admin'],
    'story_type' => 'text',
    'content' => 'ZPanel topluluk denetimi Bolum 20 MVP ile yayinda.',
    'media_path' => null,
    'link_url' => null,
]);

$rootCategories = [
    ['parent_id' => null, 'type' => 'mod', 'name' => 'FS25 Mods', 'slug' => 'fs25-mods', 'description' => 'Farming Simulator 25 icin yeni ve populer modlar.', 'icon' => 'FS', 'banner' => '/uploads/covers/mod-1.svg', 'sort_order' => 10, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'FS22 Mods', 'slug' => 'fs22-mods', 'description' => 'FS22 arsivinden secili modlar.', 'icon' => '22', 'banner' => '/uploads/covers/mod-2.svg', 'sort_order' => 20, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'FS13 Mods', 'slug' => 'fs13-mods', 'description' => 'Klasik FS13 mod koleksiyonu.', 'icon' => '13', 'banner' => '/uploads/covers/mod-3.svg', 'sort_order' => 30, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'FS11 Mods', 'slug' => 'fs11-mods', 'description' => 'Eski seri modlarini saklayan alan.', 'icon' => '11', 'banner' => '/uploads/covers/mod-1.svg', 'sort_order' => 40, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'Packs', 'slug' => 'packs', 'description' => 'Mod paketleri ve creator bundle kayitlari.', 'icon' => 'PK', 'banner' => '/uploads/covers/mod-2.svg', 'sort_order' => 50, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'Work-In-Progress', 'slug' => 'work-in-progress', 'description' => 'Gelistirme asamasindaki modlar.', 'icon' => 'WP', 'banner' => '/uploads/covers/mod-3.svg', 'sort_order' => 60, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'Premium', 'slug' => 'premium', 'description' => 'Abonelik ve paket gerektiren premium modlar.', 'icon' => 'PR', 'banner' => '/uploads/covers/mod-1.svg', 'sort_order' => 70, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'mod', 'name' => 'Weekly Choice', 'slug' => 'weekly-choice', 'description' => 'Haftanin one cikan mod secimleri.', 'icon' => 'WC', 'banner' => '/uploads/covers/mod-2.svg', 'sort_order' => 80, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Electronic', 'slug' => 'electronic', 'description' => 'Elektronik muzikler.', 'icon' => 'EL', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 10, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Cinematic', 'slug' => 'cinematic', 'description' => 'Sinematik muzikler.', 'icon' => 'CN', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 20, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Rap', 'slug' => 'rap', 'description' => 'Rap ve hip-hop kayitlari.', 'icon' => 'RP', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 30, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Arabesk Rap', 'slug' => 'arabesk-rap', 'description' => 'Arabesk rap parcalari.', 'icon' => 'AR', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 40, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Phonk', 'slug' => 'phonk', 'description' => 'Phonk ve drift enerjisi.', 'icon' => 'PH', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 50, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Turku', 'slug' => 'turku', 'description' => 'Modern turku yorumlari.', 'icon' => 'TK', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 60, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Karadeniz', 'slug' => 'karadeniz', 'description' => 'Karadeniz ritimleri.', 'icon' => 'KD', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 70, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Remix', 'slug' => 'remix', 'description' => 'Remix ve edit kayitlari.', 'icon' => 'RX', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 80, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Trap', 'slug' => 'trap', 'description' => 'Trap altyapi ve vokaller.', 'icon' => 'TR', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 90, 'is_active' => 1],
    ['parent_id' => null, 'type' => 'music', 'name' => 'Oyun Muzigi', 'slug' => 'oyun-muzigi', 'description' => 'Oyun ve sinematik muzikler.', 'icon' => 'OM', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 100, 'is_active' => 1],
];

foreach ($rootCategories as $category) {
    upsert($pdo, 'categories', $category, ['slug']);
}

$categoryIds = [];
$statement = $pdo->query('SELECT id, slug FROM categories');
foreach ($statement->fetchAll() as $row) {
    $categoryIds[$row['slug']] = (int) $row['id'];
}

$childCategories = [
    ['parent_id' => $categoryIds['fs25-mods'], 'type' => 'mod', 'name' => 'Tractors', 'slug' => 'tractors', 'description' => 'Traktor modlari ve ekipman uyumluluklari.', 'icon' => 'TR', 'banner' => '/uploads/covers/mod-1.svg', 'sort_order' => 10, 'is_active' => 1],
    ['parent_id' => $categoryIds['fs25-mods'], 'type' => 'mod', 'name' => 'Vehicles', 'slug' => 'vehicles', 'description' => 'Kamyon, arac ve servis ekipmanlari.', 'icon' => 'VH', 'banner' => '/uploads/covers/mod-2.svg', 'sort_order' => 20, 'is_active' => 1],
    ['parent_id' => $categoryIds['fs25-mods'], 'type' => 'mod', 'name' => 'Maps', 'slug' => 'maps', 'description' => 'Haritalar, koyler ve genisleme alanlari.', 'icon' => 'MP', 'banner' => '/uploads/covers/mod-3.svg', 'sort_order' => 30, 'is_active' => 1],
    ['parent_id' => $categoryIds['fs25-mods'], 'type' => 'mod', 'name' => 'Tools', 'slug' => 'tools', 'description' => 'Uretim ve saha araci eklentileri.', 'icon' => 'TL', 'banner' => '/uploads/covers/mod-1.svg', 'sort_order' => 40, 'is_active' => 1],
    ['parent_id' => $categoryIds['fs25-mods'], 'type' => 'mod', 'name' => 'Miscellaneous', 'slug' => 'miscellaneous', 'description' => 'Kucuk eklentiler, duzeltmeler ve cesitli modlar.', 'icon' => 'MS', 'banner' => '/uploads/covers/mod-2.svg', 'sort_order' => 50, 'is_active' => 1],
];

foreach ($childCategories as $category) {
    upsert($pdo, 'categories', $category, ['slug']);
}

$categoryIds = [];
$statement = $pdo->query('SELECT id, slug FROM categories');
foreach ($statement->fetchAll() as $row) {
    $categoryIds[$row['slug']] = (int) $row['id'];
}

$supportPackages = [
    [
        'name' => 'Bronze Destek',
        'slug' => 'bronze-destek',
        'description' => 'Creator calismalarini desteklemek ve temel premium erisimleri test etmek icin baslangic paketi.',
        'price_monthly' => '49.90',
        'price_6_month' => '269.90',
        'price_12_month' => '499.90',
        'benefits' => ['Premium mod erisimi', 'Premium muzik erisimi'],
    ],
    [
        'name' => 'Silver Destek',
        'slug' => 'silver-destek',
        'description' => 'Premium modlar, premium muzikler ve erken demo icerikleri icin orta seviye destek paketi.',
        'price_monthly' => '99.90',
        'price_6_month' => '539.90',
        'price_12_month' => '999.90',
        'benefits' => ['Premium modlar', 'Premium muzikler', 'Erken demo icerikler'],
    ],
    [
        'name' => 'Gold Destek',
        'slug' => 'gold-destek',
        'description' => 'Tum premium mod ve muzik testleri icin ana seed paketi. Abonelik erisim kontrolu bu paketle dogrulanir.',
        'price_monthly' => '149.90',
        'price_6_month' => '809.90',
        'price_12_month' => '1499.90',
        'benefits' => ['Tum premium erisimler', 'Creator destek rozeti', 'Oncelikli demo icerikler'],
    ],
];

foreach ($supportPackages as $package) {
    upsert($pdo, 'packages', [
        'user_id' => $userIds['creator'],
        'creator_id' => $userIds['creator'],
        'name' => $package['name'],
        'slug' => $package['slug'],
        'description' => $package['description'],
        'price_monthly' => $package['price_monthly'],
        'price_6_month' => $package['price_6_month'],
        'price_12_month' => $package['price_12_month'],
        'price' => $package['price_monthly'],
        'currency' => 'TRY',
        'billing_period' => 'monthly',
        'benefits' => json_encode($package['benefits'], JSON_UNESCAPED_UNICODE),
        'status' => 'active',
        'is_active' => 1,
    ], ['slug']);
}

upsert($pdo, 'packages', [
    'user_id' => $userIds['test_creator'],
    'creator_id' => $userIds['test_creator'],
    'name' => 'Test Creator Backstage',
    'slug' => 'test-creator-backstage',
    'description' => 'Test creator profilinde abonelik/destek sekmesini dogrulamak icin aktif seed paketi.',
    'price_monthly' => '39.90',
    'price_6_month' => '199.90',
    'price_12_month' => '359.90',
    'price' => '39.90',
    'currency' => 'TRY',
    'billing_period' => 'monthly',
    'benefits' => json_encode(['Profil paket karti testi', 'Premium destek rozeti', 'Erken demo notlari'], JSON_UNESCAPED_UNICODE),
    'status' => 'active',
    'is_active' => 1,
], ['slug']);

$packageIds = [];
$statement = $pdo->query('SELECT id, slug FROM packages');
foreach ($statement->fetchAll() as $row) {
    $packageIds[$row['slug']] = (int) $row['id'];
}

$premiumPackageId = $packageIds['gold-destek'] ?? $packageIds['silver-destek'] ?? $packageIds['bronze-destek'] ?? null;

$sitePlans = [
    [
        'name' => 'Zalorox Music Premium',
        'slug' => 'music-premium',
        'description' => 'Reklamsiz dinleme, premium player ve premium listeler icin site genel aboneligi.',
        'price_monthly' => '49.90',
        'price_6_month' => '269.90',
        'price_12_month' => '499.90',
        'features_json' => json_encode(['Reklamsiz dinleme', 'Premium player', 'Premium listeler', 'Mobil/desktop app erisimi TODO'], JSON_UNESCAPED_UNICODE),
        'status' => 'active',
    ],
    [
        'name' => 'Zalorox Music Premium Plus',
        'slug' => 'music-premium-plus',
        'description' => 'Erken erisim listeleri ve ileride mobil/desktop uygulama premium erisimi icin ust plan.',
        'price_monthly' => '79.90',
        'price_6_month' => '429.90',
        'price_12_month' => '799.90',
        'features_json' => json_encode(['Tum Premium ozellikleri', 'Erken erisim listeleri', 'Yuksek kalite player', 'App premium erisimi TODO'], JSON_UNESCAPED_UNICODE),
        'status' => 'active',
    ],
];

foreach ($sitePlans as $plan) {
    upsert($pdo, 'site_plans', $plan, ['slug']);
}

$sitePlanIds = [];
$statement = $pdo->query('SELECT id, slug FROM site_plans');
foreach ($statement->fetchAll() as $row) {
    $sitePlanIds[$row['slug']] = (int) $row['id'];
}

if (!empty($sitePlanIds['music-premium']) && !empty($userIds['test_user'])) {
    upsert($pdo, 'site_subscriptions', [
        'user_id' => $userIds['test_user'],
        'site_plan_id' => $sitePlanIds['music-premium'],
        'order_id' => null,
        'starts_at' => date('Y-m-d H:i:s', strtotime('-2 days')),
        'ends_at' => date('Y-m-d H:i:s', strtotime('+30 days')),
        'status' => 'active',
    ], ['user_id', 'site_plan_id']);
}

if ($premiumPackageId !== null) {
    seedSubscription($pdo, [
        'subscriber_id' => $userIds['user'],
        'user_id' => $userIds['user'],
        'creator_id' => $userIds['creator'],
        'package_id' => $premiumPackageId,
        'order_id' => null,
        'starts_at' => date('Y-m-d H:i:s', strtotime('-5 days')),
        'ends_at' => date('Y-m-d H:i:s', strtotime('+25 days')),
        'status' => 'active',
    ]);
}

$mods = [
    ['category' => 'premium', 'title' => 'FS25 Pro Farm Pack', 'slug' => 'fs25-pro-farm-pack', 'summary' => 'Premium ciftlik ekipman paketi.', 'description' => 'FS25 icin premium ciftlik ekipmanlari, erken erisim notlari ve creator destek paketiyle gelen demo kayit.', 'cover' => '/uploads/covers/mod-1.svg', 'external' => 'https://drive.google.com/', 'access' => 'subscriber', 'privacy' => 'premium', 'package_id' => $premiumPackageId, 'downloads' => 4820, 'views' => 18420, 'likes' => 622, 'dislikes' => 18, 'featured' => 1, 'rating' => '4.9', 'days' => 1],
    ['category' => 'tractors', 'title' => 'Anatolian Tractor 80', 'slug' => 'anatolian-tractor-80', 'summary' => 'Gundelik isler icin dengeli traktor modu.', 'description' => 'Orta guc sinifinda, yakit dengesi ve modern kaplama detaylariyla hazirlanan public traktor modu.', 'cover' => '/uploads/covers/mod-2.svg', 'external' => 'https://sharemods.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 3920, 'views' => 12110, 'likes' => 430, 'dislikes' => 12, 'featured' => 1, 'rating' => '4.8', 'days' => 2],
    ['category' => 'maps', 'title' => 'Village Roads Map', 'slug' => 'village-roads-map', 'summary' => 'Dar yollar ve koy tarlalari iceren harita.', 'description' => 'FS25 icin koy yollarina, kucuk tarlalara ve hafif daglik rotalara odaklanan public harita modu.', 'cover' => '/uploads/covers/mod-3.svg', 'external' => 'https://mediafire.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 3180, 'views' => 15200, 'likes' => 512, 'dislikes' => 21, 'featured' => 1, 'rating' => '4.7', 'days' => 3],
    ['category' => 'tools', 'title' => 'Field Tools Pack', 'slug' => 'field-tools-pack', 'summary' => 'Temel saha ekipmanlari paketi.', 'description' => 'Pulluk, silindir ve hafif saha yardimcilari iceren ucretsiz ekipman paketi.', 'cover' => '/uploads/covers/mod-1.svg', 'external' => 'https://drive.google.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 2115, 'views' => 9020, 'likes' => 210, 'dislikes' => 9, 'featured' => 0, 'rating' => '4.5', 'days' => 4],
    ['category' => 'vehicles', 'title' => 'City Vehicle Pack', 'slug' => 'city-vehicle-pack', 'summary' => 'Sehir servis araclari.', 'description' => 'Roleplay ve servis kullanimi icin public arac paketi.', 'cover' => '/uploads/covers/mod-2.svg', 'external' => 'https://sharemods.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 1750, 'views' => 8325, 'likes' => 174, 'dislikes' => 7, 'featured' => 0, 'rating' => '4.4', 'days' => 5],
    ['category' => 'miscellaneous', 'title' => 'Crop Texture Fix', 'slug' => 'crop-texture-fix', 'summary' => 'Ekin dokulari icin hafif duzeltme.', 'description' => 'FS25 ekin doku gecislerini iyilestiren kucuk ve ucretsiz mod.', 'cover' => '/uploads/covers/mod-3.svg', 'external' => 'https://mediafire.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 1280, 'views' => 6400, 'likes' => 122, 'dislikes' => 5, 'featured' => 0, 'rating' => '4.3', 'days' => 6],
    ['category' => 'tractors', 'title' => 'Compact Loader Addon', 'slug' => 'compact-loader-addon', 'summary' => 'Kucuk ciftlikler icin yukleyici.', 'description' => 'Dar alanlarda calismak icin optimize edilmis public compact loader modu.', 'cover' => '/uploads/covers/mod-1.svg', 'external' => 'https://drive.google.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 2210, 'views' => 7105, 'likes' => 188, 'dislikes' => 6, 'featured' => 0, 'rating' => '4.6', 'days' => 7],
    ['category' => 'vehicles', 'title' => 'Utility Trailer Set', 'slug' => 'utility-trailer-set', 'summary' => 'Farkli kapasite secenekli romork seti.', 'description' => 'Ciftlik icinde hafif tasima isleri icin public romork seti.', 'cover' => '/uploads/covers/mod-2.svg', 'external' => 'https://sharemods.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 2690, 'views' => 9760, 'likes' => 263, 'dislikes' => 11, 'featured' => 0, 'rating' => '4.5', 'days' => 8],
    ['category' => 'miscellaneous', 'title' => 'Misc Lights Kit', 'slug' => 'misc-lights-kit', 'summary' => 'Arac ve alan aydinlatmalari.', 'description' => 'Garaj, arac ve ciftlik alanlari icin kucuk aydinlatma kiti.', 'cover' => '/uploads/covers/mod-3.svg', 'external' => 'https://mediafire.com/', 'access' => 'free', 'privacy' => 'public', 'package_id' => null, 'downloads' => 890, 'views' => 4100, 'likes' => 80, 'dislikes' => 4, 'featured' => 0, 'rating' => '4.2', 'days' => 9],
    ['category' => 'premium', 'title' => 'Elite Harvester Pack', 'slug' => 'elite-harvester-pack', 'summary' => 'Premium bicerdoser paketi.', 'description' => 'Buyuk tarlalar icin premium bicerdoser paketi ve abonelik destekli erken erisim modu.', 'cover' => '/uploads/covers/mod-1.svg', 'external' => 'https://drive.google.com/', 'access' => 'subscriber', 'privacy' => 'premium', 'package_id' => $premiumPackageId, 'downloads' => 1450, 'views' => 11980, 'likes' => 344, 'dislikes' => 8, 'featured' => 1, 'rating' => '4.8', 'days' => 10],
    ['category' => 'premium', 'title' => 'Premium Map Bundle', 'slug' => 'premium-map-bundle', 'summary' => 'Premium harita ve gorev paketi.', 'description' => 'Abonelik paketiyle acilan genis harita, gorev akisi ve paket icerigi.', 'cover' => '/uploads/covers/mod-2.svg', 'external' => 'https://drive.google.com/', 'access' => 'paid', 'privacy' => 'premium', 'package_id' => $premiumPackageId, 'downloads' => 980, 'views' => 10420, 'likes' => 301, 'dislikes' => 10, 'featured' => 0, 'rating' => '4.7', 'days' => 11],
];

foreach ($mods as $mod) {
    $publishedAt = date('Y-m-d H:i:s', strtotime('-' . (int) $mod['days'] . ' days'));

    upsert($pdo, 'mods', [
        'user_id' => $userIds['creator'],
        'creator_id' => $userIds['creator'],
        'category_id' => $categoryIds[$mod['category']] ?? $categoryIds['fs25-mods'],
        'title' => $mod['title'],
        'slug' => $mod['slug'],
        'summary' => $mod['summary'],
        'description' => $mod['description'],
        'external_link' => $mod['external'],
        'external_link_status' => 'safe',
        'external_link_risk_score' => 5,
        'cover_path' => $mod['cover'],
        'cover_image' => $mod['cover'],
        'file_url' => $mod['external'],
        'version' => '1.0.0',
        'game_version' => 'FS25',
        'access_type' => $mod['access'],
        'privacy' => $mod['privacy'],
        'package_id' => $mod['package_id'],
        'status' => 'published',
        'download_count' => $mod['downloads'],
        'view_count' => $mod['views'],
        'like_count' => $mod['likes'],
        'dislike_count' => $mod['dislikes'],
        'featured' => $mod['featured'],
        'rating' => $mod['rating'],
        'published_at' => $publishedAt,
    ], ['slug']);
}

$modIds = [];
$statement = $pdo->query('SELECT id, slug FROM mods');
foreach ($statement->fetchAll() as $row) {
    $modIds[$row['slug']] = (int) $row['id'];
}

$galleryCycle = [
    '/uploads/covers/mod-1.svg',
    '/uploads/covers/mod-2.svg',
    '/uploads/covers/mod-3.svg',
];

foreach ($mods as $index => $mod) {
    $modId = $modIds[$mod['slug']] ?? null;
    if (!$modId) {
        continue;
    }

    upsert($pdo, 'mod_images', [
        'mod_id' => $modId,
        'image_path' => $galleryCycle[$index % count($galleryCycle)],
        'sort_order' => 10,
    ], ['mod_id', 'image_path']);

    upsert($pdo, 'mod_images', [
        'mod_id' => $modId,
        'image_path' => $galleryCycle[($index + 1) % count($galleryCycle)],
        'sort_order' => 20,
    ], ['mod_id', 'image_path']);
}

$modVideos = [
    ['slug' => 'fs25-pro-farm-pack', 'video_url' => 'https://www.youtube.com/watch?v=ScMzIvxBSi4', 'provider' => 'youtube', 'sort_order' => 30],
    ['slug' => 'village-roads-map', 'video_url' => 'https://vimeo.com/76979871', 'provider' => 'vimeo', 'sort_order' => 30],
];

foreach ($modVideos as $video) {
    if (empty($modIds[$video['slug']])) {
        continue;
    }

    upsert($pdo, 'mod_videos', [
        'mod_id' => $modIds[$video['slug']],
        'video_url' => $video['video_url'],
        'provider' => $video['provider'],
        'sort_order' => $video['sort_order'],
    ], ['mod_id', 'video_url']);
}

if (!empty($modIds['fs25-pro-farm-pack'])) {
    upsert($pdo, 'mod_models', [
        'mod_id' => $modIds['fs25-pro-farm-pack'],
        'model_path' => 'https://modelviewer.dev/shared-assets/models/Astronaut.glb',
        'model_type' => 'glb',
        'thumbnail_path' => '/uploads/covers/mod-1.svg',
        'title' => 'Demo 3D Model',
        'sort_order' => 40,
    ], ['mod_id', 'model_path']);
}

$seedComments = [
    ['slug' => 'anatolian-tractor-80', 'user_id' => $userIds['user'], 'content' => 'Denge ayarlari iyi olmus, orta seviye tarlalarda sorunsuz calisti.', 'status' => 'published', 'risk_score' => 4, 'days' => 1],
    ['slug' => 'village-roads-map', 'user_id' => $userIds['creator'], 'content' => 'Harita icin yeni koy yolu guncellemesi sonraki demo seedinde eklenecek.', 'status' => 'published', 'risk_score' => 3, 'days' => 2],
    ['slug' => 'field-tools-pack', 'user_id' => $userIds['user'], 'content' => 'Kurulum notu yeterli, ekipmanlar kayitli kariyerde gorundu.', 'status' => 'published', 'risk_score' => 2, 'days' => 3],
    ['slug' => 'fs25-pro-farm-pack', 'user_id' => $userIds['admin'], 'content' => 'Premium erisim testi icin demo yorum kaydi.', 'status' => 'published', 'risk_score' => 1, 'days' => 4],
    ['slug' => 'city-vehicle-pack', 'user_id' => $userIds['user'], 'content' => 'Model detaylari guzel, servis gorevleri icin kullanisli.', 'status' => 'published', 'risk_score' => 5, 'days' => 5],
];

foreach ($seedComments as $comment) {
    if (empty($modIds[$comment['slug']])) {
        continue;
    }

    seedComment($pdo, [
        'content_type' => 'mod',
        'content_id' => $modIds[$comment['slug']],
        'user_id' => $comment['user_id'],
        'content' => $comment['content'],
        'status' => $comment['status'],
        'risk_score' => $comment['risk_score'],
        'created_at' => date('Y-m-d H:i:s', strtotime('-' . (int) $comment['days'] . ' days')),
    ]);
}

upsert($pdo, 'music', [
    'creator_id' => $userIds['creator'],
    'category_id' => $categoryIds['electronic'],
    'title' => 'Night Drive Fields',
    'slug' => 'night-drive-fields',
    'artist_name' => 'Zalorox Beats',
    'description' => 'Seed ile gelen ornek muzik kaydi.',
    'cover_path' => '/uploads/music-covers/track-1.svg',
    'file_path' => '/uploads/music-files/night-drive-fields.mp3',
    'duration_seconds' => 184,
    'access_type' => 'free',
    'status' => 'published',
    'published_at' => date('Y-m-d H:i:s'),
], ['slug']);

$musicGenres = [
    ['name' => 'Rap', 'slug' => 'rap', 'description' => 'Rap ve hip-hop kayitlari.', 'icon' => 'RP', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 10],
    ['name' => 'Arabesk Rap', 'slug' => 'arabesk-rap', 'description' => 'Arabesk rap ve duygusal altyapilar.', 'icon' => 'AR', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 20],
    ['name' => 'Phonk', 'slug' => 'phonk', 'description' => 'Phonk, drift ve gece surusu enerjisi.', 'icon' => 'PH', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 30],
    ['name' => 'Turku', 'slug' => 'turku', 'description' => 'Modern turku yorumlari ve akustik kayitlar.', 'icon' => 'TK', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 40],
    ['name' => 'Karadeniz', 'slug' => 'karadeniz', 'description' => 'Karadeniz ritimleri ve hizli tempolu parcalar.', 'icon' => 'KD', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 50],
    ['name' => 'Remix', 'slug' => 'remix', 'description' => 'Remix, edit ve yeniden yorumlanan demo kayitlar.', 'icon' => 'RX', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 60],
    ['name' => 'Trap', 'slug' => 'trap', 'description' => 'Trap altyapilar ve modern vokal denemeleri.', 'icon' => 'TR', 'banner' => '/uploads/music-covers/track-1.svg', 'sort_order' => 70],
    ['name' => 'Oyun Muzigi', 'slug' => 'oyun-muzigi', 'description' => 'Oyun, menu ve sinematik sahne muzikleri.', 'icon' => 'OM', 'banner' => '/uploads/music-covers/track-2.svg', 'sort_order' => 80],
];

foreach ($musicGenres as $genre) {
    upsert($pdo, 'music_genres', $genre, ['slug']);
}

$musicGenreIds = [];
$statement = $pdo->query('SELECT id, slug FROM music_genres');
foreach ($statement->fetchAll() as $row) {
    $musicGenreIds[$row['slug']] = (int) $row['id'];
}

$artists = [
    ['user_id' => $userIds['creator'], 'artist_name' => 'Zalorox Beats', 'slug' => 'zalorox-beats', 'bio' => 'Zalorox demo beatleri, rap ve oyun muzikleri icin test sanatci profili.', 'avatar' => '/uploads/music-covers/track-1.svg', 'cover_image' => '/uploads/music-covers/track-1.svg', 'verified' => 1, 'status' => 'approved', 'rejection_reason' => null, 'spotify_url' => 'https://open.spotify.com/', 'youtube_url' => 'https://www.youtube.com/@zalorox', 'apple_music_url' => 'https://music.apple.com/', 'instagram_url' => 'https://instagram.com/zalorox', 'rights_confirmed_at' => date('Y-m-d H:i:s')],
    ['user_id' => $userIds['creator'], 'artist_name' => 'Night Engine', 'slug' => 'night-engine', 'bio' => 'Phonk, drift ve gece surusu enerjisi icin demo sanatci.', 'avatar' => '/uploads/music-covers/track-2.svg', 'cover_image' => '/uploads/music-covers/track-2.svg', 'verified' => 0, 'status' => 'pending', 'rejection_reason' => null, 'spotify_url' => 'https://open.spotify.com/', 'youtube_url' => 'https://www.youtube.com/', 'apple_music_url' => 'https://music.apple.com/', 'instagram_url' => null, 'rights_confirmed_at' => date('Y-m-d H:i:s')],
    ['user_id' => $userIds['creator'], 'artist_name' => 'Game Audio Lab', 'slug' => 'game-audio-lab', 'bio' => 'Oyun menuleri ve sinematik sahneler icin demo muzik profili.', 'avatar' => '/uploads/music-covers/track-1.svg', 'cover_image' => '/uploads/music-covers/track-1.svg', 'verified' => 0, 'status' => 'rejected', 'rejection_reason' => 'Demo reddetme nedeni: hak sahipligi notu eksik.', 'spotify_url' => null, 'youtube_url' => 'https://www.youtube.com/', 'apple_music_url' => null, 'instagram_url' => null, 'rights_confirmed_at' => null],
];

foreach ($artists as $artist) {
    upsert($pdo, 'artists', $artist, ['slug']);
}

$artistIds = [];
$statement = $pdo->query('SELECT id, artist_name, slug FROM artists');
foreach ($statement->fetchAll() as $row) {
    $artistIds[(string) $row['artist_name']] = (int) $row['id'];
}

$musicTracks = [
    ['genre' => 'rap', 'title' => 'Gece Bloklari', 'slug' => 'gece-bloklari', 'artist' => 'Zalorox Beats', 'description' => 'Rap tarzinda demo public/free kayit.', 'cover' => '/uploads/music-covers/track-1.svg', 'privacy' => 'public', 'package_id' => null, 'plays' => 18420, 'likes' => 912, 'featured' => 1, 'days' => 1],
    ['genre' => 'arabesk-rap', 'title' => 'Yorgun Yollar', 'slug' => 'yorgun-yollar', 'artist' => 'Creator', 'description' => 'Arabesk rap hissinde demo public/free kayit.', 'cover' => '/uploads/music-covers/track-2.svg', 'privacy' => 'free', 'package_id' => null, 'plays' => 14300, 'likes' => 640, 'featured' => 1, 'days' => 2],
    ['genre' => 'phonk', 'title' => 'Drift Smoke', 'slug' => 'drift-smoke', 'artist' => 'Night Engine', 'description' => 'Phonk ve drift enerjisi icin demo parca.', 'cover' => '/uploads/music-covers/track-1.svg', 'privacy' => 'public', 'package_id' => null, 'plays' => 21870, 'likes' => 1220, 'featured' => 1, 'days' => 3],
    ['genre' => 'turku', 'title' => 'Bozkir Ezgisi', 'slug' => 'bozkir-ezgisi', 'artist' => 'Anadolu Sound', 'description' => 'Modern turku dokusunda demo public/free kayit.', 'cover' => '/uploads/music-covers/track-2.svg', 'privacy' => 'public', 'package_id' => null, 'plays' => 7800, 'likes' => 310, 'featured' => 0, 'days' => 4],
    ['genre' => 'karadeniz', 'title' => 'Yayla Yolu', 'slug' => 'yayla-yolu', 'artist' => 'Karadeniz Crew', 'description' => 'Karadeniz ritimlerini kullanan demo kayit.', 'cover' => '/uploads/music-covers/track-1.svg', 'privacy' => 'free', 'package_id' => null, 'plays' => 9600, 'likes' => 455, 'featured' => 0, 'days' => 5],
    ['genre' => 'remix', 'title' => 'Night Drive Remix', 'slug' => 'night-drive-remix', 'artist' => 'Zalorox Beats', 'description' => 'Night Drive Fields icin demo remix versiyonu.', 'cover' => '/uploads/music-covers/track-2.svg', 'privacy' => 'public', 'package_id' => null, 'plays' => 11640, 'likes' => 520, 'featured' => 0, 'days' => 6],
    ['genre' => 'trap', 'title' => 'Low Gear Trap', 'slug' => 'low-gear-trap', 'artist' => 'Creator', 'description' => 'Trap altyapi demo kaydi.', 'cover' => '/uploads/music-covers/track-1.svg', 'privacy' => 'public', 'package_id' => null, 'plays' => 6900, 'likes' => 280, 'featured' => 0, 'days' => 7],
    ['genre' => 'oyun-muzigi', 'title' => 'Boss Fight Menu', 'slug' => 'boss-fight-menu', 'artist' => 'Game Audio Lab', 'description' => 'Oyun menusu ve boss sahnesi icin demo public/free muzik.', 'cover' => '/uploads/music-covers/track-2.svg', 'privacy' => 'free', 'package_id' => null, 'plays' => 13100, 'likes' => 705, 'featured' => 0, 'days' => 8],
    ['genre' => 'rap', 'title' => 'Studio Gold Session', 'slug' => 'studio-gold-session', 'artist' => 'Zalorox Beats', 'description' => 'Site Premium demo track. Creator paketi degil, site premium aboneligi test etmek icin seed edilir.', 'cover' => '/uploads/music-covers/track-1.svg', 'privacy' => 'premium', 'package_id' => null, 'plays' => 5200, 'likes' => 510, 'featured' => 1, 'days' => 9],
    ['genre' => 'phonk', 'title' => 'Premium Phonk Vault', 'slug' => 'premium-phonk-vault', 'artist' => 'Night Engine', 'description' => 'Premium phonk demo track. Muzik tarafinda site premium mantigi kullanilir.', 'cover' => '/uploads/music-covers/track-2.svg', 'privacy' => 'premium', 'package_id' => null, 'plays' => 4300, 'likes' => 390, 'featured' => 0, 'days' => 10],
];

foreach ($musicTracks as $track) {
    $publishedAt = date('Y-m-d H:i:s', strtotime('-' . (int) $track['days'] . ' days'));

    upsert($pdo, 'music_tracks', [
        'user_id' => $userIds['creator'],
        'artist_id' => $artistIds[$track['artist']] ?? null,
        'category_id' => $categoryIds[$track['genre']] ?? null,
        'title' => $track['title'],
        'slug' => $track['slug'],
        'artist_name' => $track['artist'],
        'description' => $track['description'],
        'cover_image' => $track['cover'],
        'audio_file' => '',
        'external_link' => 'https://music.youtube.com/',
        'youtube_url' => 'https://www.youtube.com/watch?v=ScMzIvxBSi4',
        'spotify_url' => 'https://open.spotify.com/',
        'apple_music_url' => 'https://music.apple.com/',
        'privacy' => $track['privacy'],
        'package_id' => $track['package_id'],
        'status' => 'published',
        'play_count' => $track['plays'],
        'view_count' => max(100, (int) floor($track['plays'] / 3)),
        'like_count' => $track['likes'],
        'featured' => $track['featured'],
        'created_at' => $publishedAt,
        'updated_at' => $publishedAt,
    ], ['slug']);
}

$musicTrackIds = [];
$statement = $pdo->query('SELECT id, slug FROM music_tracks');
foreach ($statement->fetchAll() as $row) {
    $musicTrackIds[$row['slug']] = (int) $row['id'];
}

foreach ($musicTracks as $track) {
    if (empty($musicTrackIds[$track['slug']]) || empty($musicGenreIds[$track['genre']])) {
        continue;
    }

    upsert($pdo, 'music_track_genres', [
        'track_id' => $musicTrackIds[$track['slug']],
        'genre_id' => $musicGenreIds[$track['genre']],
    ], ['track_id', 'genre_id']);
}

foreach ($musicTracks as $track) {
    if (empty($musicTrackIds[$track['slug']])) {
        continue;
    }

    upsert($pdo, 'music_copyright_checks', [
        'track_id' => $musicTrackIds[$track['slug']],
        'user_id' => $userIds['creator'],
        'file_hash' => hash('sha256', 'seed:' . $track['slug']),
        'title' => $track['title'],
        'artist_name' => $track['artist'],
        'status' => 'clean',
        'risk_score' => 0,
        'reasons' => json_encode([], JSON_UNESCAPED_UNICODE),
        'provider' => 'seed_local_hash',
    ], ['track_id', 'provider']);
}

$musicComments = [
    ['slug' => 'gece-bloklari', 'user_id' => $userIds['user'], 'content' => 'Beat temiz, vokal icin guzel alan birakiyor.', 'status' => 'published', 'risk_score' => 2, 'days' => 1],
    ['slug' => 'drift-smoke', 'user_id' => $userIds['creator'], 'content' => 'Phonk demo kaydi icin kapak ve platform linkleri test amacli.', 'status' => 'published', 'risk_score' => 1, 'days' => 2],
    ['slug' => 'studio-gold-session', 'user_id' => $userIds['admin'], 'content' => 'Premium erisim testi icin demo music yorumu.', 'status' => 'published', 'risk_score' => 1, 'days' => 3],
];

foreach ($musicComments as $comment) {
    if (empty($musicTrackIds[$comment['slug']])) {
        continue;
    }

    seedComment($pdo, [
        'content_type' => 'music',
        'content_id' => $musicTrackIds[$comment['slug']],
        'user_id' => $comment['user_id'],
        'content' => $comment['content'],
        'status' => $comment['status'],
        'risk_score' => $comment['risk_score'],
        'created_at' => date('Y-m-d H:i:s', strtotime('-' . (int) $comment['days'] . ' days')),
    ]);
}

// Bolum 8: Arkadaslik, mesajlasma ve nested yorum demo verileri.
$friendshipStatement = $pdo->prepare(
    'SELECT id FROM friendships
     WHERE (requester_id = :user_a AND receiver_id = :user_b)
        OR (requester_id = :user_b2 AND receiver_id = :user_a2)
     LIMIT 1'
);
$friendshipStatement->execute([
    'user_a' => $userIds['user'],
    'user_b' => $userIds['creator'],
    'user_b2' => $userIds['creator'],
    'user_a2' => $userIds['user'],
]);
$friendshipId = $friendshipStatement->fetchColumn();

if ($friendshipId) {
    $updateFriendship = $pdo->prepare('UPDATE friendships SET status = "accepted", updated_at = NOW() WHERE id = :id');
    $updateFriendship->execute(['id' => (int) $friendshipId]);
} else {
    $insertFriendship = $pdo->prepare(
        'INSERT INTO friendships (requester_id, receiver_id, status, created_at, updated_at)
         VALUES (:requester_id, :receiver_id, "accepted", NOW(), NOW())'
    );
    $insertFriendship->execute([
        'requester_id' => $userIds['user'],
        'receiver_id' => $userIds['creator'],
    ]);
}

upsert($pdo, 'user_follows', [
    'follower_id' => $userIds['user'],
    'followed_id' => $userIds['creator'],
], ['follower_id', 'followed_id']);

upsert($pdo, 'user_follows', [
    'follower_id' => $userIds['test_user'],
    'followed_id' => $userIds['creator'],
], ['follower_id', 'followed_id']);

$conversationStatement = $pdo->prepare(
    'SELECT c.id
     FROM conversations c
     INNER JOIN conversation_participants p1 ON p1.conversation_id = c.id AND p1.user_id = :user_id
     INNER JOIN conversation_participants p2 ON p2.conversation_id = c.id AND p2.user_id = :creator_id
     WHERE c.type = "private"
     LIMIT 1'
);
$conversationStatement->execute([
    'user_id' => $userIds['user'],
    'creator_id' => $userIds['creator'],
]);
$conversationId = (int) ($conversationStatement->fetchColumn() ?: 0);

if ($conversationId <= 0) {
    $pdo->prepare('INSERT INTO conversations (type, created_at, updated_at) VALUES ("private", NOW(), NOW())')->execute();
    $conversationId = (int) $pdo->lastInsertId();
}

upsert($pdo, 'conversation_participants', [
    'conversation_id' => $conversationId,
    'user_id' => $userIds['user'],
    'last_read_at' => date('Y-m-d H:i:s', strtotime('-10 minutes')),
    'archived_at' => null,
], ['conversation_id', 'user_id']);

upsert($pdo, 'conversation_participants', [
    'conversation_id' => $conversationId,
    'user_id' => $userIds['creator'],
    'last_read_at' => date('Y-m-d H:i:s', strtotime('-2 minutes')),
    'archived_at' => null,
], ['conversation_id', 'user_id']);

$seedMessages = [
    ['sender_id' => $userIds['user'], 'message_type' => 'text', 'body' => 'Selam, yeni mod paketi icin test surumu hazir mi?', 'minutes' => 18],
    ['sender_id' => $userIds['creator'], 'message_type' => 'emoji', 'body' => 'Hazir, bugun Studio uzerinden linki paylasiyorum :)', 'minutes' => 14],
    ['sender_id' => $userIds['user'], 'message_type' => 'gif', 'body' => 'Harika!', 'gif_url' => '/assets/img/logo.gif', 'minutes' => 8],
];

foreach ($seedMessages as $message) {
    $exists = $pdo->prepare(
        'SELECT id FROM messages
         WHERE conversation_id = :conversation_id
           AND sender_id = :sender_id
           AND body = :body
         LIMIT 1'
    );
    $exists->execute([
        'conversation_id' => $conversationId,
        'sender_id' => $message['sender_id'],
        'body' => $message['body'],
    ]);

    if ($exists->fetchColumn()) {
        continue;
    }

    $insertMessage = $pdo->prepare(
        'INSERT INTO messages
            (conversation_id, sender_id, message_type, body, attachment_path, gif_url, link_url, is_deleted, status, risk_score, created_at, updated_at)
         VALUES
            (:conversation_id, :sender_id, :message_type, :body, :attachment_path, :gif_url, :link_url, 0, "sent", :risk_score, :created_at, :updated_at)'
    );
    $insertMessage->execute([
        'conversation_id' => $conversationId,
        'sender_id' => $message['sender_id'],
        'message_type' => $message['message_type'],
        'body' => $message['body'],
        'attachment_path' => $message['attachment_path'] ?? null,
        'gif_url' => $message['gif_url'] ?? null,
        'link_url' => $message['link_url'] ?? null,
        'risk_score' => 2,
        'created_at' => date('Y-m-d H:i:s', strtotime('-' . (int) $message['minutes'] . ' minutes')),
        'updated_at' => date('Y-m-d H:i:s', strtotime('-' . (int) $message['minutes'] . ' minutes')),
    ]);
}

if (!empty($modIds['anatolian-tractor-80'])) {
    $parent = $pdo->prepare(
        'SELECT id FROM comments
         WHERE content_type = "mod"
           AND content_id = :content_id
           AND user_id = :user_id
           AND content = :content
         LIMIT 1'
    );
    $parent->execute([
        'content_id' => $modIds['anatolian-tractor-80'],
        'user_id' => $userIds['user'],
        'content' => 'Denge ayarlari iyi olmus, orta seviye tarlalarda sorunsuz calisti.',
    ]);
    $parentId = (int) ($parent->fetchColumn() ?: 0);

    if ($parentId > 0) {
        seedComment($pdo, [
            'content_type' => 'mod',
            'content_id' => $modIds['anatolian-tractor-80'],
            'user_id' => $userIds['creator'],
            'parent_id' => $parentId,
            'content' => 'Geri bildirim icin tesekkurler, sonraki surumde yakit ayari da iyilesecek.',
            'status' => 'published',
            'risk_score' => 1,
            'created_at' => date('Y-m-d H:i:s', strtotime('-12 hours')),
        ]);

        upsert($pdo, 'comment_likes', [
            'comment_id' => $parentId,
            'user_id' => $userIds['creator'],
        ], ['comment_id', 'user_id']);
    }
}

$settings = [
    ['setting_key' => 'payment_provider', 'setting_value' => $config['PAYMENT_PROVIDER'], 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'payment_test_mode', 'setting_value' => $config['PAYMENT_TEST_MODE'] ? '1' : '0', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'platform_fee_percent', 'setting_value' => '10', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'site_commission_rate', 'setting_value' => '0.10', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'commission_rate', 'setting_value' => '0.10', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'tax_rate', 'setting_value' => '0.20', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'provider_fee_rate', 'setting_value' => '0', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'provider_fee_fixed', 'setting_value' => '0', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'minimum_withdrawal_amount', 'setting_value' => '100', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'payout_delay_minutes', 'setting_value' => '20', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'balance_hold_days', 'setting_value' => '0', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'currency', 'setting_value' => 'TRY', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'default_currency', 'setting_value' => 'TRY', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'tax_calc_type', 'setting_value' => 'gross', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'payout_mode', 'setting_value' => 'manual', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'default_language', 'setting_value' => $config['DEFAULT_LANGUAGE'] ?? 'tr', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'supported_languages', 'setting_value' => json_encode($config['supported_languages'] ?? ['tr', 'en', 'de', 'fr'], JSON_UNESCAPED_UNICODE), 'type' => 'json', 'is_public' => 1],
    ['setting_key' => 'site_name', 'setting_value' => 'Zalorox', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'site_description', 'setting_value' => 'Modlar, muzikler ve creator abonelikleri icin Zalorox platformu.', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'site_logo', 'setting_value' => '/assets/img/logo.gif', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'music_logo', 'setting_value' => '/assets/img/logo-music.png', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'studio_logo', 'setting_value' => '/assets/img/logo-studio.png', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'zpanel_logo', 'setting_value' => '/assets/img/logo-zpanel.png', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'favicon', 'setting_value' => '/assets/img/Fav-İcon.png', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'logo_path', 'setting_value' => '/assets/img/logo.gif', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'zpanel_logo_path', 'setting_value' => '/assets/img/logo-zpanel.png', 'type' => 'string', 'is_public' => 0],
    ['setting_key' => 'default_theme', 'setting_value' => 'system', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'header_menu_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 1],
    ['setting_key' => 'maintenance_mode', 'setting_value' => '0', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'registrations_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'cookie_text', 'setting_value' => 'Zalorox deneyimini iyilestirmek icin gerekli cerezleri kullanir.', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'footer_description', 'setting_value' => 'Modlar, muzikler ve creator abonelikleri icin Zalorox platformu.', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'footer_copyright', 'setting_value' => 'Zalorox Network', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'social_x', 'setting_value' => '', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'social_youtube', 'setting_value' => '', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'social_instagram', 'setting_value' => '', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'social_discord', 'setting_value' => '', 'type' => 'string', 'is_public' => 1],
    ['setting_key' => 'shield_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_link_scan_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_comment_scan_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_message_scan_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_content_scan_enabled', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_review_threshold', 'setting_value' => '31', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'shield_block_threshold', 'setting_value' => '61', 'type' => 'number', 'is_public' => 0],
    ['setting_key' => 'shield_auto_pending', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
    ['setting_key' => 'shield_auto_block', 'setting_value' => '1', 'type' => 'boolean', 'is_public' => 0],
];

foreach ($settings as $setting) {
    upsert($pdo, 'settings', $setting, ['setting_key']);
}

$paymentProviders = [
    ['provider_key' => 'test', 'provider_name' => 'TestPaymentProvider', 'is_active' => 1, 'is_test_mode' => 1, 'config_json' => json_encode([
        'merchant_id' => 'test-merchant',
        'api_key' => 'test-api-key',
        'test_secret' => 'zalorox_test_payment_secret',
        'callback_url' => ($config['APP_URL'] ?? 'http://localhost:8080') . '/api/payment/callback/test',
        'success_url' => ($config['APP_URL'] ?? 'http://localhost:8080') . '/payment/success/{order_no}',
        'failed_url' => ($config['APP_URL'] ?? 'http://localhost:8080') . '/payment/failed/{order_no}',
        'installment_enabled' => true,
        'three_d_secure_enabled' => true,
        'secret_storage_todo' => 'Production icin app key tabanli encryption eklenecek; secret degerleri loglanmaz ve UI degeri maskeler.',
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'paytr', 'provider_name' => 'PayTRPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'iyzico', 'provider_name' => 'IyzicoPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true, 'tokenization_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'param', 'provider_name' => 'ParamPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'sipay', 'provider_name' => 'SipayPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'moka', 'provider_name' => 'MokaPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'paycell', 'provider_name' => 'PaycellPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode(['integration_status' => 'todo', 'installment_enabled' => true, 'three_d_secure_enabled' => true, 'tokenization_enabled' => true], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
    ['provider_key' => 'bank_pos', 'provider_name' => 'BankPosPaymentProvider', 'is_active' => 0, 'is_test_mode' => 1, 'config_json' => json_encode([
        'integration_status' => 'todo',
        'supported_banks' => ['Garanti BBVA', 'Is Bankasi', 'Yapi Kredi', 'Akbank', 'Ziraat', 'VakifBank', 'Halkbank', 'QNB Finansbank', 'DenizBank', 'Kuveyt Turk', 'Albaraka'],
        'installment_enabled' => true,
        'three_d_secure_enabled' => true,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)],
];

foreach ($paymentProviders as $provider) {
    upsert($pdo, 'payment_providers', $provider, ['provider_key']);
}

upsert($pdo, 'site_bank_accounts', [
    'bank_name' => 'Zalorox Test Bank',
    'account_holder' => 'Zalorox Dijital Hizmetler',
    'iban' => 'TR000000000000000000000001',
    'branch_code' => '0001',
    'account_no' => '00000001',
    'currency' => 'TRY',
    'is_default' => 1,
    'is_active' => 1,
    'description' => 'MVP manuel payout ve test odemeleri icin varsayilan site hesabi.',
], ['iban']);

$userBankSeeds = [
    [
        'user_id' => $userIds['creator'],
        'account_holder' => 'Zalorox Creator',
        'bank_name' => 'Creator Test Bank',
        'iban' => 'TR000000000000000000000002',
        'identity_or_tax_no' => '11111111110',
        'company_name' => null,
        'is_default' => 1,
        'is_verified' => 0,
    ],
    [
        'user_id' => $userIds['user'],
        'account_holder' => 'Zalorox User',
        'bank_name' => 'User Test Bank',
        'iban' => 'TR000000000000000000000003',
        'identity_or_tax_no' => '22222222220',
        'company_name' => null,
        'is_default' => 1,
        'is_verified' => 0,
    ],
];

foreach ($userBankSeeds as $bankSeed) {
    upsert($pdo, 'user_bank_accounts', $bankSeed, ['user_id', 'iban']);
}

$seedOrderNo = 'SEED-B11-CREATOR-EARNING';
$seedGross = 149.90;
$seedCommission = 14.99;
$seedTax = 29.98;
$seedProviderFee = 0.00;
$seedCreatorNet = 104.93;
$seedReference = 'seed_b11_paid';

upsert($pdo, 'orders', [
    'order_no' => $seedOrderNo,
    'user_id' => $userIds['user'],
    'creator_id' => $userIds['creator'],
    'package_id' => $premiumPackageId,
    'subscription_id' => null,
    'type' => 'subscription',
    'period_type' => 'monthly',
    'gross_amount' => $seedGross,
    'discount_amount' => 0,
    'provider_fee_rate' => 0,
    'provider_fee_fixed' => 0,
    'provider_fee_amount' => $seedProviderFee,
    'commission_rate' => 0.10,
    'commission_amount' => $seedCommission,
    'tax_rate' => 0.20,
    'tax_amount' => $seedTax,
    'creator_net_amount' => $seedCreatorNet,
    'platform_net_amount' => $seedCommission,
    'subtotal' => $seedGross,
    'platform_fee' => $seedCommission,
    'creator_amount' => $seedCreatorNet,
    'total' => $seedGross,
    'currency' => 'TRY',
    'payment_provider' => 'test',
    'provider_reference' => $seedReference,
    'status' => 'completed',
], ['order_no']);

$seedOrderStatement = $pdo->prepare('SELECT id FROM orders WHERE order_no = :order_no LIMIT 1');
$seedOrderStatement->execute(['order_no' => $seedOrderNo]);
$seedOrderId = (int) ($seedOrderStatement->fetchColumn() ?: 0);
if ($seedOrderId > 0) {
    $paymentExists = $pdo->prepare('SELECT id FROM payments WHERE order_id = :order_id AND provider_reference = :reference LIMIT 1');
    $paymentExists->execute(['order_id' => $seedOrderId, 'reference' => $seedReference]);
    if (!$paymentExists->fetchColumn()) {
        $pdo->prepare(
            'INSERT INTO payments
                (order_id, provider, provider_reference, provider_payment_id, payment_session_id, status, amount,
                 currency, card_type, card_brand, installment_count, is_3d_secure, raw_request, raw_response,
                 paid_at, created_at, updated_at)
             VALUES
                (:order_id, "test", :reference, :reference2, "seed_session_b11", "paid", :amount,
                 "TRY", "card", "visa", 1, 1, "{}", "{}", NOW(), NOW(), NOW())'
        )->execute(['order_id' => $seedOrderId, 'reference' => $seedReference, 'reference2' => $seedReference, 'amount' => $seedGross]);
    }

    $pdo->prepare(
        'INSERT INTO creator_balances
            (creator_id, user_id, pending_balance, available_balance, withdrawn_balance, rejected_balance, currency, created_at, updated_at)
         VALUES
            (:creator_id, :user_id, 0, :available_balance, 50.00, 0, "TRY", NOW(), NOW())
         ON DUPLICATE KEY UPDATE
            user_id = VALUES(user_id),
            available_balance = GREATEST(available_balance, VALUES(available_balance)),
            withdrawn_balance = GREATEST(withdrawn_balance, VALUES(withdrawn_balance)),
            updated_at = NOW()'
    )->execute(['creator_id' => $userIds['creator'], 'user_id' => $userIds['creator'], 'available_balance' => $seedCreatorNet]);

    $ledgerExists = $pdo->prepare('SELECT id FROM creator_ledgers WHERE order_id = :order_id AND type = "sale_income" LIMIT 1');
    $ledgerExists->execute(['order_id' => $seedOrderId]);
    if (!$ledgerExists->fetchColumn()) {
        $ledgerInsert = $pdo->prepare(
            'INSERT INTO creator_ledgers
                (creator_id, user_id, order_id, withdrawal_id, type, amount, balance_before, balance_after, currency, description, available_at, created_at)
             VALUES
                (:creator_id, :user_id, :order_id, NULL, :type, :amount, :balance_before, :balance_after, "TRY", :description, NOW(), NOW())'
        );
        foreach ([
            ['type' => 'sale_income', 'amount' => $seedCreatorNet, 'balance_before' => 0, 'balance_after' => $seedCreatorNet, 'description' => 'Seed paid order creator net kazanci.'],
            ['type' => 'commission_deducted', 'amount' => -$seedCommission, 'balance_before' => $seedCreatorNet, 'balance_after' => $seedCreatorNet, 'description' => 'Seed site komisyonu kesintisi.'],
            ['type' => 'tax_deducted', 'amount' => -$seedTax, 'balance_before' => $seedCreatorNet, 'balance_after' => $seedCreatorNet, 'description' => 'Seed vergi kesintisi.'],
        ] as $ledgerSeed) {
            $ledgerInsert->execute($ledgerSeed + ['creator_id' => $userIds['creator'], 'user_id' => $userIds['creator'], 'order_id' => $seedOrderId]);
        }
    }

    $creatorBankStatement = $pdo->prepare('SELECT id FROM user_bank_accounts WHERE user_id = :user_id ORDER BY is_default DESC, id DESC LIMIT 1');
    $creatorBankStatement->execute(['user_id' => $userIds['creator']]);
    $creatorBankId = (int) ($creatorBankStatement->fetchColumn() ?: 0);
    $siteBankId = (int) ($pdo->query('SELECT id FROM site_bank_accounts WHERE is_default = 1 ORDER BY id DESC LIMIT 1')->fetchColumn() ?: 0);
    $withdrawalExists = $pdo->query('SELECT id FROM withdrawal_requests WHERE transaction_reference = "seed-b11-sent" LIMIT 1');
    if (!$withdrawalExists->fetchColumn() && $creatorBankId > 0) {
        $pdo->prepare(
            'INSERT INTO withdrawal_requests
                (creator_id, user_id, bank_account_id, user_bank_account_id, site_bank_account_id, amount, currency,
                 status, admin_id, admin_note, user_note, transaction_reference, requested_at, approved_at,
                 processing_at, sent_at, processed_at, created_at, updated_at)
             VALUES
                (:creator_id, :user_id, :bank_account_id, :user_bank_account_id, :site_bank_account_id, 50.00, "TRY",
                 "sent", :admin_id, "Seed manuel gonderim", "Seed para cekme talebi", "seed-b11-sent",
                 DATE_SUB(NOW(), INTERVAL 1 DAY), DATE_SUB(NOW(), INTERVAL 23 HOUR),
                 DATE_SUB(NOW(), INTERVAL 22 HOUR), DATE_SUB(NOW(), INTERVAL 21 HOUR),
                 DATE_SUB(NOW(), INTERVAL 21 HOUR), NOW(), NOW())'
        )->execute([
            'creator_id' => $userIds['creator'],
            'user_id' => $userIds['creator'],
            'bank_account_id' => null,
            'user_bank_account_id' => $creatorBankId,
            'site_bank_account_id' => $siteBankId ?: null,
            'admin_id' => $userIds['admin'],
        ]);
        $seedWithdrawalId = (int) $pdo->lastInsertId();
        if ($seedWithdrawalId > 0) {
            $pdo->prepare(
                'INSERT INTO creator_ledgers
                    (creator_id, user_id, order_id, withdrawal_id, type, amount, balance_before, balance_after, currency, description, available_at, created_at)
                 VALUES
                    (:creator_id, :user_id, NULL, :withdrawal_id, "withdrawal_sent", 50.00, 0, 50.00, "TRY", "Seed para cekme gonderildi.", NOW(), NOW())'
            )->execute(['creator_id' => $userIds['creator'], 'user_id' => $userIds['creator'], 'withdrawal_id' => $seedWithdrawalId]);
        }
    }
}

$whitelistDomains = [
    ['domain' => 'drive.google.com', 'description' => 'Google Drive dosya saglayicisi'],
    ['domain' => 'dropbox.com', 'description' => 'Dropbox dosya saglayicisi'],
    ['domain' => 'onedrive.live.com', 'description' => 'OneDrive dosya saglayicisi'],
    ['domain' => 'mediafire.com', 'description' => 'MediaFire dosya saglayicisi'],
    ['domain' => 'sharemods.com', 'description' => 'ShareMods dosya saglayicisi'],
    ['domain' => 'mega.nz', 'description' => 'MEGA dosya saglayicisi'],
];

foreach ($whitelistDomains as $domain) {
    upsert($pdo, 'domain_whitelist', $domain, ['domain']);
}

$blacklistDomains = [
    ['domain' => 'malware-test.local', 'description' => 'Test malware domaini'],
    ['domain' => 'phishing-test.local', 'description' => 'Test phishing domaini'],
    ['domain' => 'scam-test.local', 'description' => 'Test scam domaini'],
];

foreach ($blacklistDomains as $domain) {
    upsert($pdo, 'domain_blacklist', $domain, ['domain']);
}

$forbiddenWords = [
    ['word' => 'spamlink', 'severity' => 35],
    ['word' => 'scamcoin', 'severity' => 60],
    ['word' => 'malware', 'severity' => 75],
    ['word' => 'phishing', 'severity' => 75],
    ['word' => 'illegaldownload', 'severity' => 70],
    ['word' => 'adultcontent', 'severity' => 65],
    ['word' => 'gambling', 'severity' => 50],
];

foreach ($forbiddenWords as $word) {
    upsert($pdo, 'forbidden_words', $word, ['word']);
}

$translations = [
    ['lang' => 'tr', 'translation_key' => 'app.name', 'translation_value' => 'Zalorox'],
    ['lang' => 'en', 'translation_key' => 'app.name', 'translation_value' => 'Zalorox'],
    ['lang' => 'de', 'translation_key' => 'app.name', 'translation_value' => 'Zalorox'],
    ['lang' => 'fr', 'translation_key' => 'app.name', 'translation_value' => 'Zalorox'],
    ['lang' => 'tr', 'translation_key' => 'auth.login', 'translation_value' => 'Giris Yap'],
    ['lang' => 'en', 'translation_key' => 'auth.login', 'translation_value' => 'Login'],
    ['lang' => 'de', 'translation_key' => 'auth.login', 'translation_value' => 'Anmelden'],
    ['lang' => 'fr', 'translation_key' => 'auth.login', 'translation_value' => 'Connexion'],
];

foreach ($translations as $translation) {
    upsert($pdo, 'translations', $translation, ['lang', 'translation_key']);
}

$pageSeed = static fn (string $title, string $slug, string $content, string $description, int $menu = 0): array => [
    'title' => $title,
    'slug' => $slug,
    'content' => $content,
    'language' => 'tr',
    'status' => 'published',
    'show_in_menu' => $menu,
    'show_in_header' => $menu,
    'show_in_footer' => 1,
    'seo_title' => $title,
    'seo_description' => $description,
    'created_by' => $userIds['admin'],
    'updated_by' => $userIds['admin'],
];

$pages = [
    $pageSeed('Mod Yukleme Rehberi', 'mod-yukleme-rehberi', <<<'HTML'
<h2>Baslamadan Once</h2>
<p>Mod yuklemeden once dosya adini, oyun surumunu, kapak gorselini ve indirme linkini hazirla. Kapak icin 16:9 oran onerilir.</p>
<blockquote><strong>Not:</strong> Harici linkler Zalorox Shield ile taranir ve riskli linkler incelemeye alinir.</blockquote>
<h2>Genel Mod Yukleme Adimlari</h2>
<ol><li>Studio uzerinden Mod Yukle sayfasini ac.</li><li>Baslik, aciklama, kategori ve oyun/seri bilgisini doldur.</li><li>Kapak, galeri, video ve varsa 3D model onizlemesini ekle.</li><li>Indirme linkini tarat ve guvenli sonucu bekle.</li><li>Taslak veya yayina gonder secenegiyle kaydet.</li></ol>
<h2>Oyuna Ozel Rehberler</h2>
<p>FS25, FS22 ve klasik seri modlari icin baslikta oyun kisaltmasi belirtmek arama kalitesini artirir.</p>
<h3>FS25</h3>
<p>Yeni oyun surumu icin kategori, marka ve ekipman turu etiketlerini birlikte kullan.</p>
<h3>FS22</h3>
<p>Arsiv modlari icin uyumluluk notu ve gereken DLC bilgisini aciklamaya ekle.</p>
<h2>Sorun Giderme</h2>
<ul><li>Link blocked olursa farkli bir dosya saglayici kullan.</li><li>Aciklama cok kisaysa AI onerilerinden SEO ozeti uret.</li><li>3D model gorunmuyorsa GLB/GLTF/ USDZ formatini kontrol et.</li></ul>
HTML, 'Zalorox Studio uzerinden mod yukleme ve inceleme adimlari.', 1),
    $pageSeed('Gizlilik Politikasi', 'gizlilik-politikasi', <<<'HTML'
<h2>Toplanan Bilgiler</h2>
<p>Zalorox hesap, profil, upload, yorum, mesaj, odeme testi ve guvenlik loglari gibi platformun calismasi icin gereken verileri saklar.</p>
<h2>Veri Kullanimi</h2>
<p>Veriler hesap guvenligi, icerik moderasyonu, bildirimler, odeme kayitlari ve cPanel oncesi local test sureclerinde kullanilir.</p>
<h2>Cerezler</h2>
<p>Zorunlu cerezler oturum ve CSRF icin kullanilir. Analitik ve tercih cerezleri kullanici onayina gore aktif olur.</p>
<h2>Haklarin</h2>
<p>Hesap bilgilerini Studio ayarlarindan guncelleyebilir, silme talebi olusturabilir ve gerekli durumlarda ZPanel incelemesi isteyebilirsin.</p>
HTML, 'Zalorox gizlilik ve veri isleme politikasi.'),
    $pageSeed('Kullanim Sartlari', 'kullanim-sartlari', <<<'HTML'
<h2>Platform Kullanimi</h2>
<p>Zalorox mod, muzik ve creator destek icerikleri icin guvenli ve saygili kullanim bekler.</p>
<h2>Yasakli Davranislar</h2>
<ul><li>Yetkisiz telifli muzik veya mod paylasmak.</li><li>Zararli link, spam veya phishing icerigi eklemek.</li><li>Mesaj ve yorum sistemini taciz icin kullanmak.</li></ul>
<h2>Moderasyon</h2>
<p>Zalorox Shield, Security Bot ve ZPanel adminleri riskli icerikleri yayindan kaldirabilir veya incelemeye alabilir.</p>
<h2>Degisiklikler</h2>
<p>Sartlar ZPanel sayfa yonetimi uzerinden guncellenebilir ve public dokuman olarak yayina alinabilir.</p>
HTML, 'Zalorox platform kullanim sartlari.'),
    $pageSeed('Cerez Politikasi', 'cerez-politikasi', <<<'HTML'
<h2>Cerez Turleri</h2>
<p>Zorunlu cerezler oturum, CSRF ve guvenlik icin gereklidir. Tercih cerezleri tema, dil ve player durumunu saklar.</p>
<h2>LocalStorage Kullanimi</h2>
<p>Dark/light/system tema tercihi ve kalici music player durumu localStorage icinde tutulur.</p>
<h2>Tercihleri Yonetme</h2>
<p>Cookie popup uzerinden tercihlerini yenileyebilir, tarayici ayarlarindan local verileri temizleyebilirsin.</p>
HTML, 'Zalorox cerez ve localStorage kullanim politikasi.'),
    $pageSeed('Hakkimizda', 'hakkimizda', <<<'HTML'
<h2>Zalorox Nedir?</h2>
<p>Zalorox modlar, muzikler, creator destek paketleri ve Studio/ZPanel yonetimi icin gelistirilen saf PHP tabanli bir platformdur.</p>
<h2>Odak Alanlari</h2>
<ul><li>Farming Simulator mod kataloglari.</li><li>Zalorox Music ve Artist Connect.</li><li>Creator abonelik ve kazanc sistemi.</li><li>Guvenlik botu ve manuel admin incelemesi.</li></ul>
<h2>Teknik Yaklasim</h2>
<p>Proje WordPress veya Laravel kullanmadan hafif MVC/router mimarisiyle cPanel uyumlu calismayi hedefler.</p>
HTML, 'Zalorox hakkinda kisa bilgi.', 1),
    $pageSeed('Iletisim', 'iletisim', <<<'HTML'
<h2>Destek Kanallari</h2>
<p>Genel destek, mod inceleme, muzik telif ve Artist Connect basvurulari icin bu sayfa ZPanel tarafindan guncellenebilir.</p>
<h2>Hangi Bilgileri Gondermelisin?</h2>
<ul><li>Hesap e-postasi veya nickname.</li><li>Ilgili mod, muzik veya sayfa linki.</li><li>Sorunu tekrar uretmek icin kisa adimlar.</li></ul>
<h2>Yanıt Sureci</h2>
<p>MVP asamasinda bildirimler ve ZPanel loglari uzerinden takip edilir. E-posta dogrulama ve destek kutusu TODO'dur.</p>
HTML, 'Zalorox ile iletisim bilgileri.', 1),
    $pageSeed('Topluluk Kurallari', 'topluluk-kurallari', <<<'HTML'
<h2>Saygili Iletisim</h2>
<p>Yorum, mesaj ve profil alanlari herkes icin guvenli kalacak sekilde kullanilmalidir.</p>
<h2>Icerik Paylasimi</h2>
<p>Kendi urettigin veya paylasma hakkina sahip oldugun mod ve muzikleri yukle. Kaynak, izin ve uyumluluk bilgisini net yaz.</p>
<h2>Yaptirimlar</h2>
<p>Spam, zararli link, taciz veya telif riski durumunda icerik pending_review, blocked veya archived durumuna alinabilir.</p>
HTML, 'Zalorox topluluk kurallari.'),
    $pageSeed('Icerik Politikasi', 'icerik-politikasi', <<<'HTML'
<h2>Mod Icerikleri</h2>
<p>Mod aciklamalari dogru oyun/seri, kategori, indirme linki ve kapak bilgisi icermelidir.</p>
<h2>Muzik Icerikleri</h2>
<p>Muzik yuklemek icin onayli Artist Connect profili ve hak sahipligi onayi gerekir. Riskli kayitlar telif incelemesine duser.</p>
<h2>Guvenlik Incelemesi</h2>
<p>Zalorox Shield linkleri ve metinleri tarar. Music Security Bot hash, duplicate ve keyword risklerini kaydeder.</p>
<h2>Manuel Review</h2>
<p>Local MVP tam telif tespiti garanti etmez; ZPanel uzerinden manuel onay, red veya block islemi uygulanabilir.</p>
HTML, 'Zalorox icerik politikasi.'),
];

foreach ($pages as $page) {
    upsert($pdo, 'pages', $page, ['slug', 'language']);
}

try {
    $translationBot = new \App\Services\Translate\ZaloroxTranslateBot($config, null, $pdo);
    $pageRows = $pdo->query('SELECT id, title, seo_description, content FROM pages WHERE language = "tr"')->fetchAll();
    foreach ($pageRows as $pageRow) {
        $translationBot->createDrafts(
            'page',
            (int) $pageRow['id'],
            (string) $pageRow['title'],
            (string) ($pageRow['seo_description'] ?? ''),
            (string) $pageRow['content'],
            $userIds['admin']
        );
    }
} catch (Throwable $exception) {
    echo "Ceviri seed taslaklari atlandi: " . $exception->getMessage() . "\n";
}

$adminLogExists = $pdo->prepare('SELECT id FROM admin_logs WHERE action = "seed.bolum12" AND admin_id = :admin_id LIMIT 1');
$adminLogExists->execute(['admin_id' => $userIds['admin']]);
if (!$adminLogExists->fetchColumn()) {
    $pdo->prepare(
        'INSERT INTO admin_logs (admin_id, action, target_type, target_id, entity_type, entity_id, ip_address, user_agent, details, created_at)
         VALUES (:admin_id, "seed.bolum12", "system", NULL, "system", NULL, "127.0.0.1", "seed", :details, NOW())'
    )->execute([
        'admin_id' => $userIds['admin'],
        'details' => json_encode(['message' => 'Bolum 12 ZPanel seed logu'], JSON_UNESCAPED_UNICODE),
    ]);
}

$notificationExists = $pdo->prepare('SELECT id FROM notifications WHERE user_id = :user_id AND type = "system" AND title = "ZPanel hazir" LIMIT 1');
$notificationExists->execute(['user_id' => $userIds['admin']]);
if (!$notificationExists->fetchColumn()) {
    $pdo->prepare(
        'INSERT INTO notifications (user_id, type, title, body, data, read_at, created_at)
         VALUES (:user_id, "system", "ZPanel hazir", "Bolum 12 gelismis ZPanel MVP seed edildi.", :data, NULL, NOW())'
    )->execute([
        'user_id' => $userIds['admin'],
        'data' => json_encode(['url' => '/zpanel'], JSON_UNESCAPED_UNICODE),
    ]);
}

echo "Seed tamamlandi.\n";
