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

try {
    // 1. Check if slug column exists
    $stmt = $pdo->query("SHOW COLUMNS FROM companies LIKE 'slug'");
    $slugExists = $stmt->fetch();

    if (!$slugExists) {
        echo "Slug sütunu ekleniyor...\n";
        $pdo->exec("ALTER TABLE companies ADD COLUMN slug VARCHAR(255) DEFAULT NULL");
        $pdo->exec("ALTER TABLE companies ADD UNIQUE INDEX idx_slug (slug)");
        echo "Slug sütunu eklendi.\n";
    } else {
        echo "Slug sütunu zaten var.\n";
    }

    // 2. Populate/Fix slugs
    echo "Slug'lar güncelleniyor...\n";
    // Hepsini yeniden oluştur (bozuk olanları düzeltmek için)
    $stmt = $pdo->query("SELECT id, company_name FROM companies");
    $companies = $stmt->fetchAll();

    $count = 0;
    foreach ($companies as $comp) {
        $slug = createSlugForDb($comp['company_name']);

        // Ensure uniqueness
        $originalSlug = $slug;
        $i = 2;
        while (true) {
            $check = $pdo->prepare("SELECT id FROM companies WHERE slug = ? AND id != ?");
            $check->execute([$slug, $comp['id']]);
            if (!$check->fetch()) {
                break;
            }
            $slug = $originalSlug . '-' . $i;
            $i++;
        }

        $update = $pdo->prepare("UPDATE companies SET slug = ? WHERE id = ?");
        $update->execute([$slug, $comp['id']]);
        $count++;
    }

    echo "$count firma için slug güncellendi.\n";

} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}

function createSlugForDb($string)
{
    $turkish = ['ş', 'Ş', 'ı', 'İ', 'ğ', 'Ğ', 'ü', 'Ü', 'ö', 'Ö', 'ç', 'Ç'];
    $english = ['s', 's', 'i', 'i', 'g', 'g', 'u', 'u', 'o', 'o', 'c', 'c'];

    $string = str_replace($turkish, $english, $string);
    $string = mb_strtolower($string, 'UTF-8');
    $string = preg_replace('/[^a-z0-9-]+/', '-', $string);
    $string = trim($string, '-');

    return $string;
}
