<?php

require __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use App\Models\Category;
use App\Models\Subcategory;
use App\Models\Product;
use Illuminate\Support\Str;

$newNames = [
    1 => "Oil & Ghee",
    2 => "Organic",
    3 => "Honey",
    4 => "Dates",
    5 => "Spices",
    6 => "Nuts & Seeds",
    7 => "Beverage",
    8 => "Rice",
    9 => "Flours & Lentils",
    10 => "Functional Food"
];

// 1. Rename the first 10 categories
foreach ($newNames as $id => $newName) {
    $cat = Category::find($id);
    if ($cat) {
        echo "Renaming ID {$id}: '{$cat->name}' -> '{$newName}'\n";
        $cat->name = $newName;
        $cat->slug = Str::slug($newName);
        $cat->save();
    }
}

// 2. Move products to correct categories based on keywords/subcategories
// This helps "Beverage", "Rice", "Spices" etc. get their products.

$mappings = [
    'Beverage' => ['keywords' => ['Tea', 'Drink', 'Coca-Cola', 'Sprite', 'Fanta', 'RC', 'Water', 'Juice', 'Beverage'], 'sub' => 'Beverage'],
    'Rice' => ['keywords' => ['Rice', 'Chini Gura', 'Basmati'], 'sub' => 'Rice'],
    'Spices' => ['keywords' => ['Spice', 'Masala', 'Turmeric', 'Chilli', 'Coriander'], 'sub' => 'Spice'],
    'Oil & Ghee' => ['keywords' => ['Oil', 'Ghee', 'Soyabean', 'Mustard'], 'sub' => 'Oil'],
    'Honey' => ['keywords' => ['Honey', 'Modhu'], 'sub' => 'Honey'],
    'Dates' => ['keywords' => ['Date', 'Khejuri'], 'sub' => 'Date'],
    'Organic' => ['keywords' => ['Organic'], 'sub' => 'Organic'],
    'Flours & Lentils' => ['keywords' => ['Flour', 'Lentil', 'Dal', 'Atta', 'Maida'], 'sub' => 'Lentil'],
];

foreach ($newNames as $catId => $catName) {
    if (isset($mappings[$catName])) {
        $m = $mappings[$catName];
        
        // Move by keyword
        foreach ($m['keywords'] as $kw) {
            $updated = Product::where('name', 'like', "%{$kw}%")
                ->update(['category_id' => $catId]);
            if ($updated > 0) echo "Moved {$updated} products to '{$catName}' (keyword: {$kw})\n";
        }
        
        // Move by subcategory name
        $subIds = Subcategory::where('subcategoryName', 'like', "%{$m['sub']}%")->pluck('id');
        if ($subIds->isNotEmpty()) {
            $updated = Product::whereIn('subcategory_id', $subIds)
                ->update(['category_id' => $catId]);
            if ($updated > 0) echo "Moved {$updated} products to '{$catName}' (subcategory match)\n";
        }
    }
}

// 3. Final check: remove (disable) any category with no products
$allCategories = Category::all();
foreach ($allCategories as $cat) {
    $productCount = Product::where('category_id', $cat->id)->count();
    
    // Also check if it's one of the new 10
    $isNew = in_array($cat->name, $newNames);
    
    if ($productCount == 0) {
        echo "Disabling ID {$cat->id}: '{$cat->name}' (0 products)\n";
        $cat->status = 0;
    } elseif (!$isNew && $cat->id > 10) {
         echo "Disabling ID {$cat->id}: '{$cat->name}' (Not in new list)\n";
         $cat->status = 0;
    } else {
        echo "Keeping ID {$cat->id}: '{$cat->name}' ({$productCount} products)\n";
        $cat->status = 1;
    }
    $cat->save();
}
