<?php

use App\Models\Tour;
use Illuminate\Support\Str;

echo "Starting slug update...\n";
$tours = Tour::all();
$count = 0;

foreach ($tours as $tour) {
    // Determine title
    $title = '';
    if (is_array($tour->title)) {
        $title = $tour->title['tr'] ?? $tour->title['en'] ?? '';
    } elseif (is_string($tour->title)) {
        // Try decoding if it resembles JSON
        if (Str::startsWith(trim($tour->title), '{')) {
             $decoded = json_decode($tour->title, true);
             if (json_last_error() === JSON_ERROR_NONE) {
                 $title = $decoded['tr'] ?? $decoded['en'] ?? '';
             } else {
                 $title = $tour->title;
             }
        } else {
            $title = $tour->title;
        }
    }

    if (!empty($title)) {
        $slug = Str::slug($title);
        // Only update if slug is empty OR to force update all (user said "tüm turlarda", implies enforcing it)
        // I will update it if it's empty/different to ensure consistency, but usually preserving existing slugs is better for SEO.
        // However, user said "let it write itself automatically".
        // I'll prioritize filling empty ones, and maybe rewriting ones that look like defaults?
        // Let's just fill if empty or if requested.
        // User said: "tüm turlarda otoamtik kendisi yazsın" -> "let it write itself automatically in all tours".
        // I will update ALL slugs to match the title.
        
        $tour->slug = $slug;
        $tour->saveQuietly(); // Use saveQuietly to avoid triggering other events if any
        $count++;
        echo "Updated tour {$tour->id}: {$slug}\n";
    }
}

echo "Updated {$count} tours.\n";
