<?php

namespace Database\Seeders;

use App\Models\Offer;
use App\Models\Operator;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class OfferDemoSeeder extends Seeder
{
    public function run(): void
    {
        // public/logos ফোল্ডার নিশ্চিত করি
        Storage::disk('public')->makeDirectory('logos');

        // ব্র্যান্ড কালার (same vibe with #2FAAA6)
        $brand = [
            'GP'     => '#2FAAA6',
            'BL'     => '#1F8F8B',
            'ROBI'   => '#2FAAA6',
            'AIRTEL' => '#1F8F8B',
            'TT'     => '#2FAAA6',
        ];

        // নিরাপত্তার জন্য কোন কলামটা আছে দেখে নেই (আপনার স্কিমা অনুযায়ী 'logo' আছে)
        $logoColumn = Schema::hasColumn('operators', 'logo')
            ? 'logo'
            : (Schema::hasColumn('operators', 'logo_path') ? 'logo_path' : null);

        if (!$logoColumn) {
            throw new \RuntimeException("operators টেবিলে 'logo' বা 'logo_path' কোনো কলামই নেই। আগে মাইগ্রেশন আপডেট করুন।");
        }

        // অপারেটর লিস্ট
        $ops = [
            ['name' => 'GP',         'code' => 'GP',     'sort_order' => 1],
            ['name' => 'Banglalink', 'code' => 'BL',     'sort_order' => 2],
            ['name' => 'Robi',       'code' => 'ROBI',   'sort_order' => 3],
            ['name' => 'Airtel',     'code' => 'AIRTEL', 'sort_order' => 4],
            ['name' => 'Teletalk',   'code' => 'TT',     'sort_order' => 5],
        ];

        $operators = [];

        foreach ($ops as $o) {
            $code  = $o['code'];
            $name  = $o['name'];
            $color = $brand[$code] ?? '#2FAAA6';
            $path  = "logos/{$code}.svg"; // storage/app/public/logos/{$code}.svg

            // SVG লোগো জেনারেট ও লিখে দিই
            $svg = $this->makeLogoSvg($name, $color);
            Storage::disk('public')->put($path, $svg);

            // Operator upsert (logoColumn অনুযায়ী)
            $operators[$code] = Operator::updateOrCreate(
                ['code' => $code],
                [
                    'name'        => $name,
                    $logoColumn   => $path,   // Blade: asset('storage/'.$op->logo)
                    'status'      => 'active',
                    'sort_order'  => $o['sort_order'],
                ]
            );
        }

        // ডেমো অফারগুলো
        Offer::firstOrCreate(
            ['operator_id' => $operators['BL']->id, 'title' => '50 GB + 700 Min'],
            [
                'regular_price' => 798,
                'sale_price'    => 650,
                'data_gb'       => 50,
                'minutes'       => 700,
                'validity_days' => 30,
                'status'        => 'active',
                'sort_order'    => 1,
            ]
        );

        Offer::firstOrCreate(
            ['operator_id' => $operators['BL']->id, 'title' => '45 GB + 600 Min'],
            [
                'regular_price' => 648,
                'sale_price'    => 590,
                'data_gb'       => 45,
                'minutes'       => 600,
                'validity_days' => 30,
                'status'        => 'active',
                'sort_order'    => 2,
            ]
        );
    }

    /**
     * Simple SVG badge: colored circle + up to 3 initials (Unicode-safe).
     */
    private function makeLogoSvg(string $name, string $fill = '#2FAAA6'): string
    {
        // Unicode-safe initials (max 3) — Stringable chain, no substr() on plain string
        $initials = Str::of($name)
            ->replaceMatches('/[^\p{L}]+/u', ' ')
            ->trim()
            ->explode(' ')
            ->filter()
            ->map(fn ($p) => Str::of($p)->substr(0, 1)->upper())
            ->take(3)
            ->implode('');

        return <<<SVG
<?xml version="1.0" encoding="UTF-8"?>
<svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="{$this->escapeAttr($name)}">
  <defs>
    <filter id="soft" x="-20%" y="-20%" width="140%" height="140%">
      <feDropShadow dx="0" dy="6" stdDeviation="6" flood-color="{$this->escapeAttr($fill)}" flood-opacity=".25"/>
    </filter>
  </defs>
  <g filter="url(#soft)">
    <circle cx="40" cy="40" r="32" fill="{$this->escapeAttr($fill)}"/>
  </g>
  <text x="50%" y="54%" dominant-baseline="middle" text-anchor="middle"
        font-family="ui-sans-serif, -apple-system, Segoe UI, Roboto, Helvetica, Arial"
        font-size="26" font-weight="700" fill="#FFFFFF">{$this->escapeText($initials)}</text>
</svg>
SVG;
    }

    private function escapeAttr(string $s): string
    {
        return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }

    private function escapeText(string $s): string
    {
        return htmlspecialchars($s, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}
