<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\Product;
use App\Services\ProfitService;

class FetchDigiflazzProducts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'digiflazz:fetch-products
                            {--force : Force fetch even if recently synced}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch and sync products from Digiflazz API';

    /**
     * Execute the console command.
     */
    public function handle(ProfitService $pricing)
    {
        $this->info('🔄 Fetching products from Digiflazz...');
        
        $endPoint = 'https://api.digiflazz.com/v1/price-list';
        $username = config('services.digiflazz.username');
        $apiKey   = config('services.digiflazz.api_key');

        // Validasi konfigurasi
        if (!$username || !$apiKey) {
            $this->error('❌ Digiflazz credentials not configured!');
            $this->warn('Please set DIGIFLAZZ_USERNAME and DIGIFLAZZ_API_KEY in .env');
            return Command::FAILURE;
        }

        $signature = sha1($username . $apiKey . 'pricelist');

        try {
            $response = Http::timeout(60)->post($endPoint, [
                'cmd'      => 'prepaid',
                'username' => $username,
                'sign'     => $signature,
            ]);

            if (!$response->successful()) {
                $errorMessage = $response->json('message') ?? 'Failed to connect to Digiflazz.';
                $this->error("❌ {$errorMessage}");
                return Command::FAILURE;
            }

            $products = $response->json()['data'] ?? [];

            if (!is_array($products) || !array_is_list($products)) {
                $message =
                    data_get($response->json(), 'data.message')
                    ?? data_get($response->json(), 'message')
                    ?? 'Failed to fetch data from Digiflazz.';
            
                $this->error("❌ {$message}");
                return Command::FAILURE;
            }

            $this->info("📦 Processing " . count($products) . " products...");
            
            $saved = 0;
            $skipped = 0;
            $bar = $this->output->createProgressBar(count($products));
            $bar->start();

            foreach ($products as $item) {
                if (!is_array($item) || !isset($item['buyer_sku_code'])) {
                    $skipped++;
                    $bar->advance();
                    continue;
                }
                
                $providerPrice = $item['price'];
                $sellingPrice = $pricing->applyProfit($providerPrice);
                $profit = $sellingPrice - $providerPrice;

                $productName = $this->cleanProductName($item['product_name']);

                Product::updateOrCreate(
                    ['code' => $item['buyer_sku_code']],
                    [
                        'brand'          => $item['brand'] ?? '-',
                        'product_name'   => $productName,
                        'category'       => $item['category'] ?? '-',
                        'type'           => $item['type'] ?? '-',
                        'provider_price' => $providerPrice,
                        'profit'         => $profit,
                        'selling_price'  => $sellingPrice,
                        'description'    => $item['desc'] ?? null,
                        'provider_name'  => 'Digiflazz',
                        'status' => ($item['seller_product_status'] ?? false) ? 'active' : 'inactive',
                    ]
                );

                $saved++;
                $bar->advance();
            }

            $bar->finish();
            $this->newLine(2);
            
            $this->info("✅ Successfully synced {$saved} products from Digiflazz.");
            
            if ($skipped > 0) {
                $this->warn("⚠️  Skipped {$skipped} invalid products.");
            }

            // Log activity (optional)
            activity()
                ->causedBy(null)
                ->withProperties([
                    'provider' => 'Digiflazz',
                    'synced' => $saved,
                    'skipped' => $skipped,
                    'total' => count($products),
                ])
                ->log('Products synced from Digiflazz');

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error("❌ Error: {$e->getMessage()}");
            
            // Log error (optional)
            \Log::error('Digiflazz Product Sync Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return Command::FAILURE;
        }
    }

    /**
     * Clean product name by removing brand prefix
     */
    private function cleanProductName($productName)
    {
        if (preg_match('/(\d.*)/', $productName, $matches)) {
            return trim($matches[1]);
        }
    
        return trim($productName);
    }
}
