<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ProductStock;
use App\Models\Branch;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;

class CheckLowStock extends Command
{
    // Nama perintah: php artisan app:check-low-stock
    protected $signature = 'app:check-low-stock';
    protected $description = 'Kirim notifikasi stok rendah ke Telegram Owner';

    public function handle()
    {
        $botToken = env('TELEGRAM_BOT_TOKEN'); 
        $chatId   = env('TELEGRAM_CHAT_ID'); 
        $lowLimit = 10; // Batas stok rendah (bisa Anda ubah sesuai kebutuhan)

        if (empty($botToken) || empty($chatId)) {
            $this->error('Gagal: Token Telegram belum diisi di .env');
            return;
        }

        // Ambil data stok rendah yang HANYA merupakan varian
        // Kita exclude produk yang bertindak sebagai induk
        $lowStocks = ProductStock::where('quantity', '<=', $lowLimit)
            ->whereHas('product', function ($q) {
                $q->whereNotNull('variant_group_id'); // Hanya varian
            })
            ->with(['product', 'branch'])
            ->get()
            ->groupBy('branch.name');

        if ($lowStocks->isEmpty()) {
            $this->info('Semua stok dalam kondisi aman.');
            return;
        }

        // --- KONSTRUKSI PESAN ---
        $message = "⚠️ *PERINGATAN STOK RENDAH* ⚠️\n";
        $message .= "📅 " . Carbon::now()->translatedFormat('d M Y H:i') . "\n";
        $message .= "----------------------------------\n\n";

        foreach ($lowStocks as $branchName => $items) {
            $message .= "🏪 *CABANG: {$branchName}*\n";
            foreach ($items as $item) {
                $productName = $item->product->name;
                $variant = $item->product->variant_name;
                $qty = number_format($item->quantity, 0);
                $unit = $item->product->unit ?? 'Pcs';

                $message .= "• {$productName} ({$variant}): *{$qty} {$unit}*\n";
            }
            $message .= "\n";
        }

        $message .= "----------------------------------\n";
        $message .= "💡 _Segera lakukan pemesanan ulang!_";

        // Kirim ke Telegram
        try {
            Http::post("https://api.telegram.org/bot{$botToken}/sendMessage", [
                'chat_id' => $chatId,
                'text' => $message,
                'parse_mode' => 'Markdown',
            ]);
            $this->info('Notifikasi stok rendah berhasil dikirim.');
        } catch (\Exception $e) {
            $this->error('Gagal mengirim ke Telegram: ' . $e->getMessage());
        }
    }
}