<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\BusinessCentralService;
use App\Models\BudgetButcher;
use Illuminate\Support\Facades\Log;

class SyncBudgetButcher extends Command
{
    protected $signature = 'sync:budget-butcher';
    protected $description = 'Sync Budget Butcher from Business Central (getBudgetLost raw data)';

    public function handle()
    {
        try {
            Log::info('SyncBudgetButcher: mulai proses');

            $service = new BusinessCentralService();
            $data = $service->getBudgetLost();

            $raw = $data['raw'] ?? [];

            // ===========================
            // 1. Kosongkan table dahulu
            // ===========================
            BudgetButcher::truncate();

            // ===========================
            // 2. Isi ulang dari raw
            // ===========================
            foreach ($raw as $item) {
                BudgetButcher::create([
                    'ItemNo'          => $item['ItemNo'] ?? null,
                    'Description'     => $item['Description'] ?? null,
                    'LocationCode'    => $item['LocationCode'] ?? null,
                    'PostingDate'     => $item['PostingDate'] ?? null,
                    'CostAmountActual'=> $item['CostAmountActual'] ?? 0,
                ]);
            }

            Log::info('SyncBudgetButcher: selesai sukses');

            $this->info("Sync berhasil!");
            return Command::SUCCESS;

        } catch (\Throwable $e) {
            Log::error("SyncBudgetButcher error: ".$e->getMessage());
            $this->error($e->getMessage());
            return Command::FAILURE;
        }
    }
}
