<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Cache;

use App\Models\SilverCompany;
use App\Models\SilverCompanyItem;

class SyncSilverBullionData extends Command
{
    protected $signature = 'silver:sync';
    protected $description = 'Sync silver bullion companies and items from GoldArabi API';


    public function handle()
    {
        $this->info('Fetching silver bullion data...');

        $response = Http::timeout(60)
            ->get('https://api.goldarabi.app/external/silver-bullion-data.php');

        if (!$response->successful()) {
            $this->error('API request failed');
            return 1;
        }

        $data = $response->json();
        // dd($data);

        if (!isset($data['data'])) {
            $this->error('Invalid API response');
            return 1;
        }

        DB::beginTransaction();

        try {

            foreach ($data['data'] as $companyData) {

            // dd($companyData);
                // نتأكد أنه فضة فقط
                // if ($companyData['field'] != 'silver') {
                //     continue;
                // }

                // dd($companyData);
                $company = SilverCompany::updateOrCreate(
                    ['name' => $companyData['name']],
                    [
                        'slug'        => Str::slug($companyData['name']),
                        'logo'        => $this->cleanLogoUrl($companyData['logo']),
                        'description' => $companyData['description'] ?? null,
                        'phone'       => $companyData['phone'] ?? null,
                        'website'     => $companyData['website'] ?? null,
                        'field'       => 'silver',
                    ]
                );
                // dd($company);

                foreach ($companyData['items'] as $itemData) {
                    $company = SilverCompany::where('name', $companyData['name'])->first();

                    SilverCompanyItem::updateOrCreate(
                        [
                            'silver_company_id' => $company->id,
                            'name'              => $itemData['name'],
                        ],
                        [
                            'type'                  => $itemData['type'],
                            'weight'                => $itemData['weight'],
                            'price_per_gram'        => $itemData['price_per_gram'],
                            'manufacturing_cost'    => $itemData['manufacturing_cost'],
                            'total_price'           => $itemData['total_price'],
                            'cashback'              => $itemData['cashback'],
                            'resale_price'          => $itemData['resale_price'],
                            'unsealed_resale_price' => $itemData['unsealed_resale_price'],
                            'last_updated_at'       => Carbon::createFromTimestamp($itemData['last_updated_ts']),
                        ]
                    );
                }

                $this->info("Synced Silver Company: {$company->name}");
            }

            DB::commit();

            Cache::forget('silver_companies_with_items');

            $this->info('Silver bullion sync completed successfully.');

        } catch (\Exception $e) {

            DB::rollBack();

            $this->error($e->getMessage());

            return 1;
        }

        return 0;
    }

    private function cleanLogoUrl($logo)
    {
        if (!$logo) return null;

        $baseUrl = rtrim(config('services.url'), '/');

        $logo = preg_replace('#^/?external#', '', $logo);

        if (substr_count($logo, 'http') > 1) {
            $parts = explode('http', $logo);
            $logo = 'http' . end($parts);
        }

        $logo = preg_replace('#^https?:/{1,}#', 'https://', $logo);

        $parsed = parse_url($logo);
        if (isset($parsed['path'])) {
            $logo = $parsed['path'];
        }

        $logo = preg_replace('#/+#', '/', $logo);

        return $baseUrl . '/' . ltrim($logo, '/');
    }
}
