<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class ShopCategoriesAndShopsSeeder extends Seeder
{
    public function run()
    {
        $now = date('Y-m-d H:i:s');

        $categories = [
            'Grocery & Supermarket',
            'Pharmacy',
            'Restaurant',
            'Cafe & Bakery',
            'Electronics',
            'Mobile Store',
            'Clothing & Fashion',
            'Footwear',
            'Jewellery',
            'Salon & Spa',
            'Gym & Fitness',
            'Furniture',
            'Hardware & Tools',
            'Stationery & Books',
            'Home Decor',
            'Optical Store',
            'Pet Store',
            'Sports Store',
            'Car Accessories',
            'Sweet & Snacks',
        ];

        $categoryIds = [];
        foreach ($categories as $name) {
            $row = $this->db->table('rewarder_shop_categories')->where('name', $name)->get()->getRow();
            if ($row) {
                $this->db->table('rewarder_shop_categories')->where('id', $row->id)->update([
                    'status' => 1,
                    'updated_at' => $now,
                ]);
                $categoryIds[] = (int) $row->id;
                continue;
            }
            $this->db->table('rewarder_shop_categories')->insert([
                'name' => $name,
                'status' => 1,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
            $categoryIds[] = (int) $this->db->insertID();
        }

        $cities = $this->db->table('rewarder_cities')->select('id, name')->orderBy('id', 'asc')->get()->getResult();

        $perCity = 40;
        $totalInserted = 0;
        $totalExisting = 0;
        $totalImages = 0;

        $uploadsDir = FCPATH . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'shops';
        if (!is_dir($uploadsDir)) {
            mkdir($uploadsDir, 0777, true);
        }
        $indexFile = $uploadsDir . DIRECTORY_SEPARATOR . 'index.html';
        if (!is_file($indexFile)) {
            file_put_contents($indexFile, '');
        }

        foreach ($cities as $city) {
            $existingCount = (int) $this->db->table('rewarder_shops')->where('city_id', $city->id)->countAllResults();
            $toCreate = max(0, $perCity - $existingCount);
            $totalExisting += min($perCity, $existingCount);

            for ($i = 1; $i <= $toCreate; $i++) {
                $catId = $categoryIds[array_rand($categoryIds)];
                $catName = $this->db->table('rewarder_shop_categories')->select('name')->where('id', $catId)->get()->getRow()->name ?? 'Shop';
                $shopName = $city->name . ' ' . $catName . ' ' . str_pad((string) ($existingCount + $i), 2, '0', STR_PAD_LEFT);
                $slug = $this->slugify($shopName) . '-' . $city->id . '-' . ($existingCount + $i);

                $this->db->table('rewarder_shops')->insert([
                    'name' => $shopName,
                    'slug' => $slug,
                    'phone' => $this->randomIndianPhone(),
                    'address' => $this->randomAddress($city->name),
                    'city_id' => (int) $city->id,
                    'category_id' => (int) $catId,
                    'status' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);

                $shopId = (int) $this->db->insertID();
                $imgPath = $uploadsDir . DIRECTORY_SEPARATOR . $shopId . '.jpg';

                $ok = $this->makeShopImage($imgPath, $shopName, (int) $city->id, $shopId);
                if ($ok) {
                    $this->db->table('rewarder_shops')->where('id', $shopId)->update([
                        'img_type' => 'jpg',
                        'updated_at' => $now,
                    ]);
                    $totalImages++;
                }

                $totalInserted++;
            }
        }

        echo "Shop categories: " . count($categoryIds) . "\n";
        echo "Cities: " . count($cities) . "\n";
        echo "Shops inserted: {$totalInserted}\n";
        echo "Shops already existed (counted up to per-city): {$totalExisting}\n";
        echo "Images generated: {$totalImages}\n";
    }

    private function slugify(string $str): string
    {
        $str = strtolower($str);
        $str = preg_replace('/[^a-z0-9]+/i', '-', $str);
        $str = trim((string) $str, '-');
        return $str ?: 'shop';
    }

    private function randomIndianPhone(): string
    {
        $first = (string) rand(6, 9);
        $rest = (string) rand(100000000, 999999999);
        return $first . $rest;
    }

    private function randomAddress(string $cityName): string
    {
        $areas = ['Main Road', 'Market Road', 'Station Road', 'Ring Road', 'Industrial Area', 'GIDC', 'Old City', 'New City', 'Town Center', 'High Street'];
        $suffix = ['Near Bus Stand', 'Opp. Park', 'Above Bank', 'Near Mall', 'Opp. Hospital', 'Near Temple', 'Near Lake', 'Near Railway Station', 'Opp. School', 'Near Circle'];
        return rand(1, 999) . ', ' . $areas[array_rand($areas)] . ', ' . $cityName . ', Gujarat, India - ' . rand(360000, 399999) . ' (' . $suffix[array_rand($suffix)] . ')';
    }

    private function makeShopImage(string $path, string $title, int $cityId, int $shopId): bool
    {
        $w = 640;
        $h = 360;

        if (!function_exists('imagecreatetruecolor')) {
            return false;
        }

        $im = imagecreatetruecolor($w, $h);
        if (!$im) {
            return false;
        }

        $seed = ($cityId * 100000) + $shopId;
        $r1 = ($seed * 37) % 200 + 30;
        $g1 = ($seed * 53) % 200 + 30;
        $b1 = ($seed * 91) % 200 + 30;
        $r2 = ($seed * 71) % 200 + 30;
        $g2 = ($seed * 29) % 200 + 30;
        $b2 = ($seed * 17) % 200 + 30;

        for ($y = 0; $y < $h; $y++) {
            $t = $y / max(1, $h - 1);
            $r = (int) round($r1 * (1 - $t) + $r2 * $t);
            $g = (int) round($g1 * (1 - $t) + $g2 * $t);
            $b = (int) round($b1 * (1 - $t) + $b2 * $t);
            $col = imagecolorallocate($im, $r, $g, $b);
            imageline($im, 0, $y, $w, $y, $col);
        }

        $overlay = imagecolorallocatealpha($im, 0, 0, 0, 90);
        imagefilledrectangle($im, 20, $h - 120, $w - 20, $h - 20, $overlay);

        $white = imagecolorallocate($im, 255, 255, 255);
        $muted = imagecolorallocate($im, 235, 235, 235);

        $line1 = $this->truncate($title, 42);
        $line2 = 'City ID: ' . $cityId . '   Shop ID: ' . $shopId;

        imagestring($im, 5, 36, $h - 108, $line1, $white);
        imagestring($im, 4, 36, $h - 78, $line2, $muted);
        imagestring($im, 3, 36, $h - 52, 'Rewarder Demo Image', $muted);

        $ok = imagejpeg($im, $path, 70);
        imagedestroy($im);
        return (bool) $ok;
    }

    private function truncate(string $s, int $max): string
    {
        $s = trim($s);
        if (strlen($s) <= $max) {
            return $s;
        }
        return substr($s, 0, $max - 3) . '...';
    }
}

