<?php
set_time_limit(0);
require_once __DIR__ . '/core/bootstrap.php';

$db  = Core\Database::getInstance();
$dir = __DIR__ . '/public/uploads/items/';
if (!is_dir($dir)) mkdir($dir, 0755, true);

// loremflickr.com — real tagged Flickr photos, free, keyword-based
// Format: https://loremflickr.com/400/300/keyword1,keyword2/all
$keywords = [
    'Classic Beef Burger'       => 'beef,burger',
    'Chicken Zinger Burger'     => 'chicken,burger',
    'Double Beef Burger'        => 'double,burger',
    'BBQ Smoky Burger'          => 'bbq,burger',
    'Spicy Volcano Burger'      => 'spicy,burger',
    'Mushroom Swiss Burger'     => 'mushroom,burger',
    'Cheese Burger'             => 'cheese,burger',
    'Grilled Chicken Burger'    => 'grilled,chicken,sandwich',
    'Crispy Chicken Burger'     => 'fried,chicken,sandwich',
    'Beef Smash Burger'         => 'smash,burger',
    'Chicken Fillet Burger'     => 'chicken,fillet,burger',
    'Margherita Pizza'          => 'margherita,pizza',
    'Chicken Tikka Pizza'       => 'chicken,pizza',
    'BBQ Chicken Pizza'         => 'bbq,pizza',
    'Pepperoni Pizza'           => 'pepperoni,pizza',
    'Veggie Supreme Pizza'      => 'vegetable,pizza',
    'Beef Fajita Pizza'         => 'beef,pizza',
    'Four Cheese Pizza'         => 'cheese,pizza',
    'Peri Peri Chicken Pizza'   => 'spicy,chicken,pizza',
    'Seekh Kebab Pizza'         => 'kebab,pizza',
    'Chicken Tikka Pizza Large' => 'large,chicken,pizza',
    'Chicken Karahi Half'       => 'chicken,curry,karahi',
    'Daal Makhani'              => 'dal,lentil,indian',
    'Aloo Gosht'                => 'mutton,potato,curry',
    'Palak Paneer'              => 'spinach,paneer,curry',
    'Nihari'                    => 'beef,stew,curry',
    'Haleem'                    => 'haleem,lentil,stew',
    'Paye Trotters'             => 'goat,stew,curry',
    'Chana Masala'              => 'chickpea,curry',
    'Chicken Qorma'             => 'chicken,korma,curry',
    'Broast Chicken 2 pcs'      => 'fried,chicken,crispy',
    'Broast Chicken 4 pcs'      => 'fried,chicken,pieces',
    'Broast Chicken 8 pcs'      => 'fried,chicken,bucket',
    'Crispy Fried Wings 6 pcs'  => 'chicken,wings,crispy',
    'Spicy Wings 6 pcs'         => 'spicy,chicken,wings',
    'Fish and Chips'            => 'fish,chips',
    'Fried Chicken Strips'      => 'chicken,strips,fried',
    'Chicken Nuggets 12 pcs'    => 'chicken,nuggets',
    'Chicken Popcorn'           => 'popcorn,chicken',
    'Chicken Biryani'           => 'chicken,biryani',
    'Beef Biryani'              => 'beef,biryani',
    'Mutton Biryani'            => 'mutton,biryani',
    'Prawn Biryani'             => 'prawn,biryani',
    'Vegetable Biryani'         => 'vegetable,biryani',
    'Family Chicken Biryani'    => 'biryani,rice',
    'Sindhi Biryani'            => 'biryani,spicy',
    'Beef Yakhni Pulao'         => 'pulao,rice,beef',
    'Chicken Karahi Full'       => 'chicken,karahi,wok',
    'Beef Karahi Half'          => 'beef,curry,karahi',
    'Beef Karahi Full'          => 'beef,karahi',
    'Mutton Karahi Half'        => 'mutton,curry',
    'Handi Chicken'             => 'clay,pot,chicken',
    'Shinwari Karahi'           => 'white,chicken,curry',
    'Club Sandwich'             => 'club,sandwich',
    'Grilled Chicken Sub'       => 'grilled,chicken,sub',
    'BLT Sandwich'              => 'blt,sandwich',
    'Egg Mayo Sandwich'         => 'egg,sandwich',
    'Beef Steak Sandwich'       => 'steak,sandwich',
    'Cheese Grilled Sandwich'   => 'grilled,cheese,sandwich',
    'Chicken Tikka Roll'        => 'chicken,tikka,wrap',
    'Seekh Kebab Roll'          => 'kebab,wrap,roll',
    'Beef Shawarma'             => 'beef,shawarma',
    'Chicken Shawarma'          => 'chicken,shawarma',
    'Chapli Kebab Roll'         => 'kebab,wrap',
    'Peri Peri Chicken Wrap'    => 'chicken,wrap,spicy',
    'Veggie Wrap'               => 'vegetable,wrap',
    'Chicken Kathi Roll'        => 'chicken,roll,wrap',
    'Burger Deal 2 pax'         => 'burger,fries,meal',
    'Family Broast Deal'        => 'fried,chicken,family',
    'Pizza Wings Deal'          => 'pizza,wings,combo',
    'Biryani Combo'             => 'biryani,meal',
    'Karahi Night Deal'         => 'karahi,naan,dinner',
    'Student Deal'              => 'burger,drink,fries',
    'Breakfast Deal'            => 'paratha,egg,breakfast',
    'Coca Cola 330ml'           => 'coca,cola,drink',
    'Pepsi 330ml'               => 'pepsi,drink,cold',
    '7UP 330ml'                 => 'lemon,drink,cold',
    'Fanta 330ml'               => 'orange,drink,cold',
    'Mineral Water 500ml'       => 'water,bottle,cold',
    'Fresh Orange Juice'        => 'orange,juice,fresh',
    'Mango Shake'               => 'mango,milkshake',
    'Strawberry Shake'          => 'strawberry,milkshake',
    'Lassi Sweet'               => 'lassi,yogurt,drink',
    'Lassi Salty'               => 'lassi,yogurt,salty',
    'Green Tea'                 => 'green,tea,cup',
    'Kashmiri Chai'             => 'tea,pink,milk',
    'Rooh Afza Sharbat'         => 'rose,milk,drink',
    'Gulab Jamun 4 pcs'         => 'gulab,jamun,sweet',
    'Kheer'                     => 'rice,pudding,dessert',
    'Chocolate Brownie'         => 'chocolate,brownie',
    'Gajar Halwa'               => 'carrot,halwa,dessert',
    'Ice Cream 2 Scoops'        => 'ice,cream,scoops',
    'Ras Malai 2 pcs'           => 'rasmali,cream,dessert',
    'Chocolate Cake Slice'      => 'chocolate,cake,slice',
    'Chicken Corn Soup'         => 'chicken,corn,soup',
    'Hot and Sour Soup'         => 'hot,sour,soup',
    'Lentil Soup'               => 'lentil,soup',
    'Tomato Soup'               => 'tomato,soup',
    'Paya Soup'                 => 'bone,broth,soup',
];

$ctx = stream_context_create([
    'http' => [
        'timeout'         => 20,
        'follow_location' => true,
        'max_redirects'   => 8,
        'user_agent'      => 'Mozilla/5.0 (food-delivery-dev/1.0)',
    ],
    'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
]);

function downloadTo(string $url, string $dest, $ctx): bool
{
    $data = @file_get_contents($url, false, $ctx);
    if (!$data || strlen($data) < 4000) return false;
    $tmp = tempnam(sys_get_temp_dir(), 'img');
    file_put_contents($tmp, $data);
    $mime = mime_content_type($tmp);
    unlink($tmp);
    if (!str_starts_with($mime ?: '', 'image/')) return false;
    file_put_contents($dest, $data);
    return true;
}

$items = $db->fetchAll("SELECT id, name, item_image FROM menu_items ORDER BY id");

$ok = $fail = $skip = 0;

foreach ($items as $item) {
    // Skip if already a real jpg
    if (!empty($item['item_image']) && str_ends_with((string)$item['item_image'], '.jpg')
        && file_exists(__DIR__ . '/public/uploads/' . $item['item_image'])) {
        echo "  — {$item['name']} (has jpg)\n";
        $skip++;
        continue;
    }

    $kw    = $keywords[$item['name']] ?? 'food';
    $url   = "https://loremflickr.com/400/300/{$kw}";
    $fname = 'item_' . $item['id'] . '_' . md5($item['name']) . '.jpg';
    $dest  = $dir . $fname;

    echo "  ↓ {$item['name']} [{$kw}] … ";
    flush();

    // Delete old SVG placeholder
    if (!empty($item['item_image'])) {
        $old = __DIR__ . '/public/uploads/' . $item['item_image'];
        if (file_exists($old) && str_ends_with($old, '.svg')) @unlink($old);
    }

    if (downloadTo($url, $dest, $ctx)) {
        $db->update('menu_items', ['item_image' => 'items/' . $fname], ['id' => $item['id']]);
        echo "✓ (" . round(filesize($dest)/1024) . "KB)\n";
        $ok++;
    } else {
        echo "✗\n";
        $fail++;
    }

    usleep(250000); // 0.25s between requests
}

echo "\nDone. ✓ {$ok}  ✗ {$fail}  skipped {$skip}\n";
