<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Str;

class UploadCategoryImagesFromFolder extends Command
{
    protected $signature = 'categories:upload-from-folder {folder : Folder path containing images}';
    protected $description = 'Upload images from folder and auto-match to categories by filename';

    private $stats = ['matched' => 0, 'failed' => 0, 'skipped' => 0];

    public function handle()
    {
        $folderPath = $this->argument('folder');

        if (!is_dir($folderPath)) {
            $this->error("Folder not found: {$folderPath}");
            return 1;
        }

        $this->info('📁 Scanning folder for images...');
        
        // Get all image files
        $files = glob($folderPath . '/*.{jpg,jpeg,png,webp,gif}', GLOB_BRACE);
        
        if (empty($files)) {
            $this->error('No image files found in folder!');
            return 1;
        }

        $this->info("Found " . count($files) . " images");
        $this->newLine();

        // Get all categories
        $categories = DB::table('categories')->get()->keyBy('id');

        $this->info('🔍 Matching images to categories...');
        $this->newLine();

        $bar = $this->output->createProgressBar(count($files));
        $bar->start();

        foreach ($files as $filePath) {
            $this->processFile($filePath, $categories);
            $bar->advance();
        }

        $bar->finish();
        $this->newLine(2);

        $this->info('📊 Summary:');
        $this->line("  ✅ Matched: {$this->stats['matched']}");
        $this->line("  ⏭️  Skipped: {$this->stats['skipped']}");
        $this->line("  ❌ Failed: {$this->stats['failed']}");

        return 0;
    }

    private function processFile($filePath, $categories)
    {
        $fileName = pathinfo($filePath, PATHINFO_FILENAME);
        $fileName = strtolower($fileName);

        // Try to match filename to category name
        $matchedCategory = null;

        foreach ($categories as $category) {
            $categoryName = strtolower($category->name);
            $categorySlug = strtolower($category->slug);
            
            // Match strategies:
            // 1. Exact match
            if ($fileName === $categorySlug || $fileName === str_replace(' ', '-', $categoryName)) {
                $matchedCategory = $category;
                break;
            }
            
            // 2. Contains match
            if (str_contains($fileName, $categorySlug) || str_contains($categorySlug, $fileName)) {
                $matchedCategory = $category;
                break;
            }
            
            // 3. Fuzzy match (remove spaces, special chars)
            $cleanFileName = preg_replace('/[^a-z0-9]/', '', $fileName);
            $cleanCategoryName = preg_replace('/[^a-z0-9]/', '', $categoryName);
            
            if ($cleanFileName === $cleanCategoryName || 
                str_contains($cleanFileName, $cleanCategoryName) ||
                str_contains($cleanCategoryName, $cleanFileName)) {
                $matchedCategory = $category;
                break;
            }
        }

        if (!$matchedCategory) {
            $this->stats['skipped']++;
            return;
        }

        try {
            // Process and save image
            $newFileName = 'cat-' . Str::slug($matchedCategory->name) . '-' . time() . '.webp';
            $savePath = 'categories/' . $newFileName;

            // Convert to WebP
            $manager = new ImageManager(new Driver());
            $image = $manager->read($filePath);
            $image->scale(width: 400);
            $image->toWebp(75)->save(storage_path('app/public/' . $savePath));

            // Update database
            DB::table('categories')->where('id', $matchedCategory->id)->update([
                'image' => $savePath,
                'manual_image' => true,
                'updated_at' => now()
            ]);

            $this->stats['matched']++;

        } catch (\Exception $e) {
            $this->stats['failed']++;
        }
    }
}