<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Property; // Sesuaikan dengan model kamu
use Illuminate\Support\Str;

class GeneratePropertySlugs extends Command
{
    protected $signature = 'properties:generate-slugs';
    protected $description = 'Generate slugs for existing properties';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $properties = Property::whereNull('slug')->get();
        
        if ($properties->isEmpty()) {
            $this->info('✅ Semua properties sudah punya slug!');
            return 0;
        }

        $this->info("Generating slugs untuk {$properties->count()} properties...");

        foreach ($properties as $property) {
            // Generate slug dari prop_name
            $baseSlug = Str::slug($property->prop_name);
            $slug = $baseSlug;
            $counter = 1;

            // Cek apakah slug sudah ada (hindari duplikat)
            while (Property::where('slug', $slug)->where('id', '!=', $property->id)->exists()) {
                $slug = $baseSlug . '-' . $counter;
                $counter++;
            }

            $property->slug = $slug;
            $property->save();

            $this->line("✅ Property ID {$property->id}: {$property->prop_name} → {$slug}");
        }

        $this->info('✅ Selesai! Semua properties sudah punya slug.');
        return 0;
    }
}