<?php

namespace App\Console\Commands;

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

class SendDailyRecap extends Command
{
    protected $signature = 'app:send-daily-recap';
    protected $description = 'Kirim rekap harian otomatis ke Telegram Owner';

    public function handle()
    {
        $botToken = env('TELEGRAM_BOT_TOKEN'); 
        $chatId   = env('TELEGRAM_CHAT_ID'); 

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

        $today = Carbon::today();
        $branches = Branch::all();
        
        // --- HEADER ---
        $message = "📊 *LAPORAN TUTUP TOKO* 📊\n";
        $message .= "📅 " . $today->translatedFormat('l, d M Y') . "\n";
        $message .= "----------------------------------\n\n";

        // Variabel Penampung Global
        $globalOmzet = 0;
        $globalTunai = 0;
        $globalBank  = 0; // Transfer + QRIS
        $globalPiutang = 0; // Hutang
        $globalExpense = 0;

        foreach ($branches as $branch) {
            // Ambil penjualan hari ini (Exclude saldo awal)
            $sales = Sale::where('branch_id', $branch->id)
                ->whereDate('created_at', $today)
                ->where(function($q) {
                    $q->where('invoice_number', 'NOT LIKE', '%SALDO%')
                      ->where('invoice_number', 'NOT LIKE', '%AWAL%');
                })
                ->get();
            
            $omzetCabang = $sales->sum('grand_total');
            
            // --- PEMISAHAN KATEGORI KEUANGAN ---
            $tunaiCabang = $sales->where('payment_method', 'cash')->sum('grand_total');
            
            // Bank = Transfer + QRIS
            $bankCabang = $sales->whereIn('payment_method', ['transfer', 'qris'])->sum('grand_total');
            
            // Piutang = Tempo / Credit
            $piutangCabang = $sales->where('payment_method', 'credit')->sum('grand_total');

            // Hitung Biaya
            $expenseCabang = Expense::where('branch_id', $branch->id)
                ->whereDate('expense_date', $today)
                ->sum('amount');

            // Hitung Bersih (Omzet - Biaya) -> Ini profit kasar hari ini
            $bersihCabang = $omzetCabang - $expenseCabang;

            // Akumulasi ke Global
            $globalOmzet += $omzetCabang;
            $globalTunai += $tunaiCabang;
            $globalBank  += $bankCabang;
            $globalPiutang += $piutangCabang;
            $globalExpense += $expenseCabang;

            // --- TAMPILAN PER CABANG ---
            $message .= "🏠 *" . strtoupper($branch->name) . "*\n";
            $message .= "💰 Omzet: Rp " . number_format($omzetCabang, 0, ',', '.') . "\n";
            
            if ($omzetCabang > 0) {
                $message .= "   ├ 💵 Tunai: " . number_format($tunaiCabang, 0, ',', '.') . "\n";
                $message .= "   ├ 🏦 Bank: " . number_format($bankCabang, 0, ',', '.') . "\n";
                if ($piutangCabang > 0) {
                    $message .= "   └ 🔴 Piutang: " . number_format($piutangCabang, 0, ',', '.') . "\n";
                }
            }
            
            $message .= "💸 Biaya: Rp " . number_format($expenseCabang, 0, ',', '.') . "\n";
            
            // Indikator Profit
            $icon = $bersihCabang >= 0 ? '✅' : '🔻';
            $message .= "$icon *Net: Rp " . number_format($bersihCabang, 0, ',', '.') . "*\n\n";
        }

        // --- TAMPILAN TOTAL GROUP ---
        $globalNet = $globalOmzet - $globalExpense;
        
        $message .= "========================\n";
        $message .= "🏆 *TOTAL GROUP HARI INI*\n";
        $message .= "========================\n";
        
        $message .= "📈 *TOTAL OMZET: Rp " . number_format($globalOmzet, 0, ',', '.') . "*\n";
        $message .= "   ├ 💵 Tunai: " . number_format($globalTunai, 0, ',', '.') . "\n";
        $message .= "   ├ 🏦 Bank: " . number_format($globalBank, 0, ',', '.') . "\n";
        if ($globalPiutang > 0) {
            $message .= "   └ 🔴 Piutang: " . number_format($globalPiutang, 0, ',', '.') . "\n";
        }
        $message .= "\n";
        
        $message .= "📉 Total Biaya: Rp " . number_format($globalExpense, 0, ',', '.') . "\n";
        $message .= "🔥 *PROFIT BERSIH: Rp " . number_format($globalNet, 0, ',', '.') . "*\n";
        $message .= "----------------------------------\n";
        $message .= "🤖 _Laporan Otomatis System_";

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