<?php

namespace App\Console\Commands;

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

class BulkAssignCategoryImages extends Command
{
    protected $signature = 'categories:bulk-images {file : Path to CSV/JSON file with category=>url mapping}';
    protected $description = 'Bulk assign images to categories from URL list';

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

    public function handle()
    {
        $filePath = $this->argument('file');

        if (!file_exists($filePath)) {
            $this->error("File not found: {$filePath}");
            return 1;
        }

        $this->info('📥 Loading image URLs...');
        
        $mappings = $this->loadMappings($filePath);
        
        if (empty($mappings)) {
            $this->error('No valid mappings found!');
            return 1;
        }

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

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

        foreach ($mappings as $categoryName => $imageUrl) {
            $this->processMapping($categoryName, $imageUrl);
            $bar->advance();
        }

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

        $this->info('✅ Success: ' . $this->stats['success']);
        $this->error('❌ Failed: ' . $this->stats['failed']);

        return 0;
    }

    private function loadMappings($filePath)
    {
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);

        if ($extension === 'json') {
            return json_decode(file_get_contents($filePath), true) ?? [];
        }

        if ($extension === 'csv') {
            $mappings = [];
            $file = fopen($filePath, 'r');
            
            // Skip header
            fgetcsv($file);
            
            while (($row = fgetcsv($file)) !== false) {
                if (count($row) >= 2) {
                    $mappings[$row[0]] = $row[1];
                }
            }
            
            fclose($file);
            return $mappings;
        }

        return [];
    }

    private function processMapping($categoryName, $imageUrl)
    {
        try {
            // Find category
            $category = DB::table('categories')
                ->whereRaw('LOWER(name) LIKE ?', ['%' . strtolower($categoryName) . '%'])
                ->first();

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

            // Download image
            $response = Http::timeout(15)->get($imageUrl);

            if (!$response->successful()) {
                $this->stats['failed']++;
                return;
            }

            // Save & convert to WebP
            $fileName = 'cat-' . Str::slug($category->name) . '-' . time() . '.webp';
            $path = 'categories/' . $fileName;

            $manager = new ImageManager(new Driver());
            $image = $manager->read($response->body());
            $image->scale(width: 400);
            $image->toWebp(75)->save(storage_path('app/public/' . $path));

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

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

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