<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use App\Models\Branch; 
use App\Models\DeliveryZone; 
use App\Models\Customer;
use App\Models\Sale;
use Carbon\Carbon;

class OnlineStoreController extends Controller
{
    /**
     * ========================================================================
     * FITUR BARU: AUTO-GRADING PELANGGAN BERDASARKAN UMUR PIUTANG (AR AGING)
     * ========================================================================
     */
    private function _calculateCustomerGrade($customerId)
    {
        // Tarik data 3 bulan terakhir (90 Hari)
        $threeMonthsAgo = Carbon::today()->subDays(90)->toDateString();

        $creditSales = DB::table('sales')
            ->where('customer_id', $customerId)
            ->where('payment_method', 'kredit')
            ->where('delivery_status', '!=', 'void')
            ->where('created_at', '>=', $threeMonthsAgo)
            ->get();

        if ($creditSales->isEmpty()) {
            return 'A'; 
        }

        $maxDaysToPay = 0;

        foreach ($creditSales as $sale) {
            $invoiceDate = Carbon::parse($sale->created_at);

            $lastPayment = DB::table('debt_payments')
                ->where('sale_id', $sale->id)
                ->where('payment_status', 'completed')
                ->orderBy('payment_date', 'desc')
                ->first();

            if ($sale->payment_status === 'paid' && $lastPayment) {
                $payDate = Carbon::parse($lastPayment->payment_date);
                $days = $invoiceDate->diffInDays($payDate);
            } else {
                $days = $invoiceDate->diffInDays(Carbon::today());
            }

            if ($days > $maxDaysToPay) {
                $maxDaysToPay = $days;
            }
        }

        if ($maxDaysToPay <= 30) return 'A'; 
        if ($maxDaysToPay <= 60) return 'B'; 
        if ($maxDaysToPay <= 90) return 'C'; 
        return 'D';                          
    }

    // ========================================================================
    // FITUR BARU: GANTI PASSWORD PELANGGAN (DENGAN BYPASS AKUN TANPA PASSWORD)
    // ========================================================================
    public function changePassword(Request $request)
    {
        $request->validate([
            'customer_id' => 'required',
            // old_password tidak diwajibkan (required) untuk jaga-jaga akun yang belum punya password
            'new_password' => 'required|min:6|confirmed', 
        ]);

        try {
            $customer = Customer::find($request->customer_id);
            
            if (!$customer) {
                return response()->json(['success' => false, 'message' => 'Akun pelanggan tidak ditemukan.'], 404);
            }

            // LOGIKA PINTAR: Cek apakah di database sudah ada password atau masih KOSONG
            if (!empty($customer->password)) {
                // Jika SUDAH punya password, wajib masukkan password lama yang benar
                if (!$request->filled('old_password') || !Hash::check($request->old_password, $customer->password)) {
                    return response()->json(['success' => false, 'message' => 'Password lama yang Anda masukkan salah!'], 400);
                }
            }

            // Jika BELUM punya password, sistem akan langsung update ke password baru
            $customer->password = Hash::make($request->new_password);
            $customer->save();

            return response()->json([
                'success' => true,
                'message' => 'Password berhasil diperbarui dengan aman.'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan server saat mengubah password: ' . $e->getMessage()
            ], 500);
        }
    }

    public function checkCoverage(Request $request)
    {
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);

        $lat = $request->latitude;
        $lng = $request->longitude;

        $nearestBranch = Branch::select('branches.*')
            ->selectRaw("
                ( 6371 * acos( cos( radians(?) ) *
                cos( radians( latitude ) ) *
                cos( radians( longitude ) - radians(?) ) +
                sin( radians(?) ) *
                sin( radians( latitude ) ) ) ) AS distance
            ", [$lat, $lng, $lat]) 
            ->where(function($q) {
                $q->where('is_online_active', true)->orWhereNull('is_online_active');
            })
            ->having('distance', '<=', DB::raw('max_delivery_radius_km')) 
            ->orderBy('distance', 'asc') 
            ->first();

        if (!$nearestBranch) {
            return response()->json([
                'status' => 'error',
                'message' => 'Maaf, lokasi Anda berada di luar jangkauan pengiriman armada kami.',
            ], 400); 
        }

        $zone = DeliveryZone::where('branch_id', $nearestBranch->id)
            ->where('is_active', true)
            ->where('max_radius_km', '>=', $nearestBranch->distance)
            ->orderBy('max_radius_km', 'asc') 
            ->first();

        if (!$zone) {
            return response()->json([
                'status' => 'error',
                'message' => 'Tarif ongkos kirim untuk wilayah ini belum diatur oleh Admin toko.',
            ], 400);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Lokasi terjangkau armada pengiriman.',
            'data' => [
                'nearest_branch_id' => $nearestBranch->id,
                'branch_name' => $nearestBranch->name,
                'distance_km' => round($nearestBranch->distance, 2),
                'zone_name' => $zone->zone_name,
                'shipping_fee' => (float) $zone->shipping_fee,
                'min_order_value' => (float) $zone->min_order_value,
            ]
        ], 200);
    }

    public function getProducts(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id',
            'customer_id' => 'nullable'
        ]);

        $branchId = $request->branch_id;

        $branch = Branch::find($branchId);
        $branchSettings = [
            'credit_price_system' => $branch->credit_price_system ?? 'sama_dengan_tunai',
            'credit_markup_value' => (float) ($branch->credit_markup_value ?? 0),
        ];

        $customerLevel = 1; 
        $customerCreditLimit = 0; 
        $customerTypeId = null; // Penampung ID Tipe Outlet Pelanggan Live
        
        if ($request->filled('customer_id')) {
            $reqCustId = $request->customer_id;
            
            $customer = Customer::find($reqCustId);
            if (!$customer) {
                $customer = Customer::where('customer_code', $reqCustId)->first();
            }
            
            if ($customer) {
                preg_match('/\d+/', $customer->price_level ?? '1', $matches);
                $customerLevel = isset($matches[0]) ? (int)$matches[0] : 1;
                $customerCreditLimit = (float) $customer->credit_limit;
                $customerTypeId = $customer->customer_type_id; // Ekstrak Tipe Outlet
            }
        } elseif (auth('sanctum')->check()) {
            $user = auth('sanctum')->user();
            if ($user && $user->customer) {
                preg_match('/\d+/', $user->customer->price_level ?? '1', $matches);
                $customerLevel = isset($matches[0]) ? (int)$matches[0] : 1;
                $customerCreditLimit = (float) $user->customer->credit_limit;
                $customerTypeId = $user->customer->customer_type_id; // Ekstrak Tipe Outlet
            }
        }

        $productsQuery = \App\Models\Product::with([
            'category',
            'prices', 
            'stocks' => function($query) use ($branchId) {
                $query->where('branch_id', $branchId);
            }
        ]);

        if (Schema::hasColumn('products', 'parent_id')) {
            $productsQuery->whereNull('parent_id');
        }
        if (Schema::hasColumn('products', 'variant_group_id')) {
            $productsQuery->where(function($q) {
                $q->whereNull('variant_group_id')->orWhere('variant_group_id', '');
            });
        }

        $products = $productsQuery
            ->whereIn('product_type', ['trading', 'finished_good'])
            ->where(function($q) {
                $q->where('is_active', true)->orWhereNull('is_active');
            })
            ->where(function($q) {
                $q->where('is_available_online', true)->orWhereNull('is_available_online');
            })
            ->get(); 

        foreach ($products as $product) {
            if ($product->image_path) {
                $product->image_url = url('storage/' . $product->image_path);
            }

            if ($product->relationLoaded('prices') && $product->prices->isEmpty()) {
                $product->unsetRelation('prices');
            }

            $variants = [];

            if (Schema::hasColumn('products', 'variant_group_id')) {
                $groupId = 'VAR-' . $product->id;
                $rawVariants = \App\Models\Product::with(['prices', 'stocks' => function($q) use ($branchId) {
                    $q->where('branch_id', $branchId);
                }])->where('variant_group_id', $groupId)->get();
                
                foreach ($rawVariants as $v) {
                    if ($v->relationLoaded('prices') && $v->prices->isEmpty()) {
                        $v->unsetRelation('prices');
                    }
                    $v->variant_name = $v->variant_name ?? $v->name ?? 'Varian';
                    if ($v->image_path) $v->image_url = url('storage/' . $v->image_path);
                    $variants[] = $v;
                }
            }

            if (empty($variants) && Schema::hasColumn('products', 'parent_id')) {
                $rawVariants = \App\Models\Product::with(['prices', 'stocks' => function($q) use ($branchId) {
                    $q->where('branch_id', $branchId);
                }])->where('parent_id', $product->id)->get();
                
                foreach ($rawVariants as $v) {
                    if ($v->relationLoaded('prices') && $v->prices->isEmpty()) {
                        $v->unsetRelation('prices');
                    }
                    $v->variant_name = $v->variant_name ?? $v->name ?? 'Varian';
                    if ($v->image_path) $v->image_url = url('storage/' . $v->image_path);
                    $variants[] = $v;
                }
            }

            if (empty($variants) && Schema::hasTable('product_variants')) {
                $rawVariants = DB::table('product_variants')->where('product_id', $product->id)->get();
                foreach ($rawVariants as $v) {
                    if (Schema::hasTable('product_prices')) {
                        $prices = DB::table('product_prices')->where('variant_id', $v->id)->get();
                        if ($prices->count() > 0) {
                            $v->prices = $prices;
                        }
                    }
                    $v->stocks = DB::table('product_stocks')->where('variant_id', $v->id)->where('branch_id', $branchId)->get();
                    $v->variant_name = $v->name ?? $v->variant_name ?? 'Varian';
                    if (isset($v->image_path) && $v->image_path) $v->image_url = url('storage/' . $v->image_path);
                    $variants[] = $v;
                }
            }

            if (count($variants) > 0) {
                $product->setAttribute('variants', $variants);
                $product->setAttribute('has_variants', true);
            } else {
                $product->setAttribute('variants', []);
                $product->setAttribute('has_variants', false);
            }
        }

        $today = date('Y-m-d');
        $activePrograms = DB::table('sales_programs')
            ->where('is_active', 1)
            ->whereDate('start_date', '<=', $today)
            ->whereDate('end_date', '>=', $today)
            ->get();

        $programIds = $activePrograms->pluck('id')->toArray();
        $allTiers = collect();
        if (!empty($programIds)) {
            $allTiers = DB::table('sales_program_tiers')
                ->leftJoin('products', 'sales_program_tiers.bonus_product_id', '=', 'products.id')
                ->whereIn('sales_program_tiers.sales_program_id', $programIds)
                ->select('sales_program_tiers.*', 'products.name as bonus_product_name', 'products.variant_name as bonus_variant_name', 'products.unit as bonus_unit')
                ->get();
        }

        $tiersGrouped = [];
        foreach ($allTiers as $tier) {
            if (!empty($tier->bonus_variant_name)) {
                $tier->bonus_product_name .= ' - ' . $tier->bonus_variant_name;
            }
            $tiersGrouped[$tier->sales_program_id][] = $tier;
        }

        // --- PERBAIKAN: PENYARINGAN PROMO UNTUK KLIEN / BANNER PWA ---
        $filteredPrograms = [];
        foreach ($activePrograms as $program) {
            $targetTypes = is_string($program->target_customer_types) ? json_decode($program->target_customer_types, true) : $program->target_customer_types;
            
            if (!empty($targetTypes) && is_array($targetTypes) && count($targetTypes) > 0) {
                // Jika promo khusus, dan akun pembeli tidak cocok (atau tamu), jangan tampilkan program ini
                if ($customerTypeId === null || !in_array($customerTypeId, $targetTypes)) {
                    continue; 
                }
            }
            
            $program->tiers = $tiersGrouped[$program->id] ?? [];
            $filteredPrograms[] = $program;
        }

        // ========================================================================
        // MODUL BARU: TARIK LIVE BANNER DARI BACKEND DENGAN SEKUENS TERKONTROL
        // ========================================================================
        $liveBanners = DB::table('banners')
            ->where('is_active', 1)
            ->orderBy('sequence', 'asc')
            ->get()
            ->map(function($b) {
                $b->image_url = $b->image_path ? url('storage/' . $b->image_path) : null;
                return $b;
            });

        return response()->json([
            'status' => 'success',
            'user_level' => $customerLevel,
            'credit_limit' => $customerCreditLimit, 
            'branch_settings' => $branchSettings,
            'active_programs' => $filteredPrograms, 
            'banners' => $liveBanners, // Suntikan data banner dinamis
            'data' => $products
        ], 200);
    }

    public function checkout(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id',
            'customer_name' => 'required|string|max:255',
            'customer_phone' => 'required|string|max:20',
            'customer_id' => 'nullable', 
            'delivery_lat' => 'required|numeric',
            'delivery_lng' => 'required|numeric',
            'shipping_fee' => 'required|numeric|min:0',
            'shipping_address' => 'nullable|string',
            'payment_type' => 'nullable|in:tunai,kredit', 
            
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.variant_id' => 'nullable', 
            'items.*.unit_name' => 'required|string', 
            'items.*.qty' => 'required|numeric|min:0.1', 
            'items.*.price' => 'required|numeric|min:0', 
        ]);

        $branchId = $request->branch_id;
        $items = $request->items;
        $paymentType = $request->payment_type ?? 'tunai';

        try {
            DB::beginTransaction();

            $cleanCustomerId = null;
            $customerLevel = 1;
            $customerTypeId = null; // Penampung Tipe Outlet untuk validasi checkout server
            
            if ($request->filled('customer_id')) {
                $reqCustId = $request->customer_id;
                $customer = Customer::find($reqCustId);
                if (!$customer) {
                    $customer = Customer::where('customer_code', $reqCustId)->first();
                }

                if ($customer) {
                    if (!$customer->is_active) {
                        throw new \Exception("Akun Anda berstatus Non-Aktif. Anda tidak dapat melakukan transaksi. Silakan hubungi Admin.");
                    }
                    if ($customer->registration_status === 'pending') {
                        throw new \Exception("Akun Anda masih dalam status 'Menunggu Approval'. Transaksi diblokir sementara.");
                    }
                    $cleanCustomerId = $customer->id; 
                    $customerTypeId = $customer->customer_type_id; // Ekstrak tipe outlet b2b
                    
                    // PERBAIKAN: EKSTRAK ANGKA DARI STRING "2_user"
                    preg_match('/\d+/', $customer->price_level ?? '1', $matches);
                    $customerLevel = isset($matches[0]) ? (int)$matches[0] : 1;
                }
            }

            $branch = Branch::findOrFail($branchId);
            $distance = $branch->calculateDistanceTo($request->delivery_lat, $request->delivery_lng);
            $deliveryStatus = 'pending'; 

            $today = date('Y-m-d');
            $activePrograms = DB::table('sales_programs')
                ->where('is_active', 1)
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->get();

            $subtotalKotor = 0; 
            $totalDiskonPromo = 0; 
            $processedItems = [];
            $bonusItems = [];

            foreach ($items as $item) {
                $productData = \App\Models\Product::find($item['product_id']);
                
                if (!$productData) {
                    throw new \Exception("Produk tidak ditemukan di database.");
                }

                $multiplier = 1; 
                $unitLevel = 1;
                $uName = strtoupper(trim($item['unit_name']));
                
                if ($uName === strtoupper(trim($productData->buy_unit ?? $productData->satuan_besar ?? ''))) {
                    $multiplier = $productData->conversion_factor ?? 1;
                    $unitLevel = 2;
                } elseif ($uName === strtoupper(trim($productData->unit_3_name ?? $productData->satuan_l3 ?? ''))) {
                    $multiplier = $productData->conversion_3_qty ?? 1;
                    $unitLevel = 3;
                } elseif ($uName === strtoupper(trim($productData->unit_4_name ?? $productData->satuan_l4 ?? ''))) {
                    $multiplier = $productData->conversion_4_qty ?? 1;
                    $unitLevel = 4;
                }
                
                $totalBaseQtyRequired = (float)$item['qty'] * (float)$multiplier;

                // --- VALIDASI STOK AMAN ---
                $stockQuery = \App\Models\ProductStock::where('branch_id', $branchId)->where('product_id', $item['product_id']);
                if (!empty($item['variant_id']) && Schema::hasColumn('product_stocks', 'variant_id')) {
                    $stockQuery->where('variant_id', $item['variant_id']);
                }
                $stockRecord = $stockQuery->orderBy('id', 'desc')->first();

                $availableStock = 0;
                if ($stockRecord) {
                    $qtyFisik = (float)($stockRecord->quantity ?? $stockRecord->qty ?? $stockRecord->stock ?? 0);
                    $qtyBooking = (float)($stockRecord->reserved_qty ?? 0);
                    $availableStock = $qtyFisik - $qtyBooking;
                } elseif ($productData) {
                    $qtyFisik = (float)($productData->stock_qty ?? $productData->stock ?? $productData->qty ?? 0);
                    $qtyBooking = (float)($productData->reserved_qty ?? 0);
                    $availableStock = $qtyFisik - $qtyBooking;
                }

                if ($availableStock < $totalBaseQtyRequired) { 
                    $unitName = $productData->satuan_dasar ?? 'PCS';
                    throw new \Exception("Stok Tersedia Tidak Mencukupi. Anda butuh {$totalBaseQtyRequired} {$unitName}, tapi sisa stok aman hanya {$availableStock}.");
                }

                // ========================================================================
                // CORE SERVER-SIDE PRICE RESOLVER DENGAN PENGENAL STRING "2_user"
                // ========================================================================
                $targetPriceLevel = $customerLevel;
                if ($paymentType === 'kredit' && ($branch->credit_price_system ?? '') === 'turun_level') {
                    $penalty = (int)($branch->credit_markup_value ?? 0);
                    $targetPriceLevel = max(1, $customerLevel - $penalty);
                }

                // Ambil harga asli dari database dengan LIKE atau exact match
                $priceRecord = DB::table('product_prices')
                    ->where('product_id', $item['product_id'])
                    ->where(function($q) use ($targetPriceLevel) {
                        $q->where('level', (string)$targetPriceLevel)
                          ->orWhere('level', $targetPriceLevel . '_user');
                    })
                    ->where('unit_level', $unitLevel)
                    ->first();

                if ($priceRecord) {
                    $basePrice = (float) $priceRecord->amount;
                } else {
                    $priceRecordFallback = DB::table('product_prices')
                        ->where('product_id', $item['product_id'])
                        ->where(function($q) {
                            $q->where('level', '1')
                              ->orWhere('level', '1_user');
                        })
                        ->where('unit_level', $unitLevel)
                        ->first();
                    $basePrice = $priceRecordFallback ? (float)$priceRecordFallback->amount : (float)$item['price'];
                }

                if ($paymentType === 'kredit') {
                    if (($branch->credit_price_system ?? '') === 'markup_persen') {
                        $markupPercent = (float)($branch->credit_markup_value ?? 0);
                        $basePrice = ceil($basePrice + ($basePrice * ($markupPercent / 100)));
                    } elseif (($branch->credit_price_system ?? '') === 'markup_nominal') {
                        $markupNominal = (float)($branch->credit_markup_value ?? 0);
                        $basePrice = $basePrice + $markupNominal;
                    }
                }

                $itemHargaKotor = $basePrice * (float)$item['qty'];
                $itemDiscount = 0;
                $appliedProgramId = null;

                // ========================================================================
                // LOGIKA PROMO DENGAN FILTER MULTIPLE CHECKBOX TIPE OUTLET SERVER-SIDE
                // ========================================================================
                foreach ($activePrograms as $promo) {
                    // --- SECURITY GATE: CEK KECOCOKAN MULTIPLE CHANNELS ---
                    $targetTypes = is_string($promo->target_customer_types) ? json_decode($promo->target_customer_types, true) : $promo->target_customer_types;
                    
                    if (!empty($targetTypes) && is_array($targetTypes) && count($targetTypes) > 0) {
                        // Jika target dispesifikkan, pembeli wajib terautentikasi & tipe outletnya ada di dalam daftar array
                        if ($customerTypeId === null || !in_array($customerTypeId, $targetTypes)) {
                            continue; // Skip skema diskon/hadiah dari promo ini
                        }
                    }
                    // ------------------------------------------------------

                    $isMatch = false;
                    $scope = strtolower(trim($promo->scope));
                    
                    if ($scope === 'global') {
                        $isMatch = true;
                    } elseif ($scope === 'category' && (int)$promo->category_id === (int)$productData->category_id) {
                        $isMatch = true;
                    } elseif ($scope === 'product' && (int)$promo->product_id === (int)$productData->id) {
                        $isMatch = true;
                    }

                    if ($isMatch) {
                        $validTiers = DB::table('sales_program_tiers')->where('sales_program_id', $promo->id)->get();
                        $validTier = $validTiers->filter(function($t) use ($totalBaseQtyRequired) {
                            return (float)$t->min_qty <= (float)$totalBaseQtyRequired;
                        })->sortByDesc(function($t) {
                            return (float)$t->min_qty;
                        })->first();

                        if ($validTier) {
                            $appliedProgramId = $promo->id;
                            $minReq = (float)$validTier->min_qty;
                            $promoMultiplier = ($validTier->is_multiple && $minReq > 0) ? floor((float)$totalBaseQtyRequired / $minReq) : 1;
                            $rType = strtolower(trim($validTier->reward_type));
                            
                            if ($rType === 'discount_percent') {
                                $pct = (float) $validTier->reward_value;
                                $itemDiscount = $itemHargaKotor * ($pct / 100);
                            } elseif ($rType === 'discount_nominal') {
                                $itemDiscount = (float) $validTier->reward_value * $promoMultiplier;
                            } elseif ($rType === 'bonus_item') {
                                $bonusProduct = DB::table('products')->where('id', $validTier->bonus_product_id)->first();
                                if ($bonusProduct) {
                                    $bQtyRequired = (float)$validTier->bonus_qty * $promoMultiplier;
                                    $bonusItems[] = [
                                        'product_id' => $bonusProduct->id,
                                        'unit_name' => $bonusProduct->satuan_dasar ?? 'PCS', 
                                        'qty' => $bQtyRequired,
                                        'applied_program_id' => $promo->id,
                                        'total_base_qty' => $bQtyRequired 
                                    ];
                                }
                            }
                            break; 
                        }
                    }
                }

                $subtotalKotor += $itemHargaKotor;
                $totalDiskonPromo += $itemDiscount;
                $itemHargaBersih = $itemHargaKotor - $itemDiscount;

                $processedItems[] = [
                    'product_id' => $item['product_id'],
                    'unit_name' => $item['unit_name'],
                    'qty' => $item['qty'],
                    'price' => $basePrice,
                    'discount_nominal' => $itemDiscount,
                    'total_price' => $itemHargaBersih, 
                    'applied_program_id' => $appliedProgramId,
                    'total_base_qty' => $totalBaseQtyRequired,
                    'variant_id' => $item['variant_id'] ?? null
                ];
            }

            $grandTotal = ($subtotalKotor - $totalDiskonPromo) + (float)$request->shipping_fee;
            $catatanKredit = '';

            // ========================================================================
            // PENAMBAHAN: GATEWAY PENGECEKAN LIMIT KREDIT & AUTO-GRADING UNTUK PWA
            // ========================================================================
            if ($paymentType === 'kredit' && $cleanCustomerId && isset($customer)) {
                $limit = (float) ($customer->credit_limit ?? 0);
                if ($limit <= 0) {
                    throw new \Exception("Transaksi gagal. Akun Anda tidak memiliki limit kredit (Limit: Rp 0). Silakan gunakan metode pembayaran Tunai/COD.");
                }

                $creditCheck = \App\Models\SalesOrder::checkCreditHold($customer->id, $grandTotal);
                
                // Minta bantuan mesin Auto-Grading
                $grade = $this->_calculateCustomerGrade($customer->id);
                $isGradeHold = in_array($grade, ['B', 'C', 'D']); 

                if ($creditCheck['is_hold'] || $isGradeHold) {
                    // Pesanan masuk penjara (Credit Hold)
                    $deliveryStatus = \App\Models\SalesOrder::STATUS_CREDIT_HOLD ?? 'credit_hold';
                    
                    $reasons = [];
                    if ($creditCheck['is_hold']) $reasons[] = $creditCheck['message'];
                    if ($isGradeHold) $reasons[] = "Pelanggan Grade $grade (Ada histori telat bayar > 30 hari dalam 3 bln terakhir)";
                    
                    $catatanKredit = "\n[" . implode(" | ", $reasons) . "]";
                }
            }

            $soNumber = 'SO-ONL-' . date('Ymd') . '-' . rand(1000, 9999);
            
            $salesOrderId = DB::table('sales_orders')->insertGetId([
                'so_number' => $soNumber,
                'branch_id' => $branchId, 
                'fulfillment_branch_id' => $branchId, 
                'customer_id' => $cleanCustomerId,
                'user_id' => 1, 
                'customer_name' => $request->customer_name,
                'customer_phone' => $request->customer_phone,
                'shipping_address' => $request->shipping_address,
                'delivery_lat' => $request->delivery_lat,
                'delivery_lng' => $request->delivery_lng,
                'subtotal' => $subtotalKotor,          
                'shipping_fee' => $request->shipping_fee,
                'discount_amount' => $totalDiskonPromo, 
                'grand_total' => $grandTotal,          
                'payment_method' => $paymentType === 'kredit' ? 'kredit' : 'cash',
                'status' => $deliveryStatus,
                'note' => 'Pesanan dari Toko Online (PWA)' . $catatanKredit,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            foreach ($processedItems as $pItem) {
                DB::table('sales_order_items')->insert([
                    'sales_order_id' => $salesOrderId,
                    'product_id' => $pItem['product_id'],
                    'unit_name' => $pItem['unit_name'],
                    'qty' => $pItem['qty'],
                    'price' => $pItem['price'],
                    'discount_nominal' => $pItem['discount_nominal'], 
                    'total_price' => $pItem['total_price'],
                    'is_free_item' => 0,
                    'applied_program_id' => $pItem['applied_program_id'], 
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                
                $stockQuery = \App\Models\ProductStock::where('branch_id', $branchId)->where('product_id', $pItem['product_id']);
                if (!empty($pItem['variant_id']) && Schema::hasColumn('product_stocks', 'variant_id')) {
                    $stockQuery->where('variant_id', $pItem['variant_id']);
                }
                $existingStock = $stockQuery->orderBy('id', 'desc')->first();
                if ($existingStock) {
                    $existingStock->reserved_qty += $pItem['total_base_qty'];
                    $existingStock->save();
                } else {
                    $prod = \App\Models\Product::find($pItem['product_id']);
                    if ($prod && Schema::hasColumn('products', 'reserved_qty')) {
                        $prod->reserved_qty += $pItem['total_base_qty'];
                        $prod->save();
                    }
                }
            }

            // ========================================================================
            // PERBAIKAN: MEMOTONG STOK BONUS ITEM SECARA AMAN MENGHINDARI STDCLASS ERROR
            // ========================================================================
            foreach ($bonusItems as $bItem) {
                DB::table('sales_order_items')->insert([
                    'sales_order_id' => $salesOrderId,
                    'product_id' => $bItem['product_id'],
                    'unit_name' => $bItem['unit_name'],
                    'qty' => $bItem['qty'],
                    'price' => 0,
                    'discount_nominal' => 0,
                    'total_price' => 0,
                    'is_free_item' => 1, 
                    'applied_program_id' => $bItem['applied_program_id'],
                    'created_at' => now(),
                    'updated_at' => now()
                ]);

                // Gunakan fungsi Update pada Query Builder (bukan memanggil $bStock->increment langsung)
                $bStock = DB::table('product_stocks')->where('branch_id', $branchId)->where('product_id', $bItem['product_id'])->first();
                if ($bStock) {
                    DB::table('product_stocks')->where('id', $bStock->id)->update([
                        'reserved_qty' => DB::raw("reserved_qty + " . $bItem['total_base_qty'])
                    ]);
                } else {
                    $prod = \App\Models\Product::find($bItem['product_id']);
                    if ($prod && Schema::hasColumn('products', 'reserved_qty')) {
                        $prod->reserved_qty += $bItem['total_base_qty'];
                        $prod->save();
                    }
                }
            }

            DB::commit();

            // PWA Message
            $msg = $deliveryStatus === 'credit_hold'
                ? "Pesanan berhasil dibuat, namun menunggu verifikasi Admin (Credit Hold) karena batasan limit atau grade toko."
                : "Pesanan berhasil dibuat dan stok telah di-booking.";

            return response()->json([
                'status' => 'success',
                'message' => $msg,
                'data' => [
                    'invoice_number' => $soNumber, 
                    'grand_total' => $grandTotal,
                    'delivery_status' => $deliveryStatus, 
                    'distance_km' => $distance 
                ]
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => 'error',
                'message' => 'Checkout gagal: ' . $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ], 400);
        }
    }

    public function getCustomerOrders(Request $request)
    {
        $reqCustId = $request->query('customer_id');

        if (!$reqCustId) {
            return response()->json([
                'success' => false,
                'message' => 'Sesi login tidak terbaca oleh sistem.'
            ], 400);
        }

        $customer = Customer::where('id', $reqCustId)
            ->orWhere('customer_code', $reqCustId)
            ->first();

        if (!$customer) {
             return response()->json([
                'success' => false,
                'message' => 'Data pelanggan tidak ditemukan.'
            ], 404);
        }

        $formattedOrders = [];

        $sales = DB::table('sales')
            ->where('customer_id', $customer->id)
            ->whereIn('payment_status', ['pending', 'partial'])
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($sales as $sale) {
            $pwaStatus = 'Diproses';
            if (in_array($sale->delivery_status, ['void', 'batal', 'cancelled'])) {
                $pwaStatus = 'Batal';
            } elseif (in_array($sale->delivery_status, ['dikirim', 'terkirim'])) {
                $pwaStatus = 'Dikirim';
            } elseif ($sale->delivery_status === 'selesai') {
                $pwaStatus = 'Selesai';
            }

            $itemsCount = DB::table('sale_items')->where('sale_id', $sale->id)->count();

            $formattedOrders[] = [
                'id' => 'INV_' . $sale->id, 
                'invoice_number' => $sale->invoice_number,
                'created_at' => $sale->created_at,
                'status' => $pwaStatus,
                'total_amount' => (float) $sale->grand_total,
                'items_count' => $itemsCount,
                'payment_status' => $sale->payment_method === 'kredit' ? 'TEMPO' : 'COD',
                'driver' => null
            ];
        }

        $orders = DB::table('sales_orders')
            ->where('customer_id', $customer->id)
            ->whereIn('status', ['pending', 'reschedule', 'batal', 'cancelled', 'credit_hold', 'partially_delivered'])
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($orders as $order) {
            $pwaStatus = 'Diproses';
            if (in_array($order->status, ['batal', 'cancelled'])) {
                $pwaStatus = 'Batal';
            } elseif ($order->status === 'reschedule') {
                $pwaStatus = 'Diproses (Jadwal Ulang)';
            } elseif ($order->status === 'credit_hold') {
                $pwaStatus = 'Menunggu Approval';
            }

            $invoiceName = $order->so_number;
            if ($order->status === 'partially_delivered') {
                $invoiceName .= ' (Antrean Sisa Barang)'; 
            }

            $itemsCount = DB::table('sales_order_items')->where('sales_order_id', $order->id)->count();

            $formattedOrders[] = [
                'id' => 'SO_' . $order->id, 
                'invoice_number' => $invoiceName,
                'created_at' => $order->created_at,
                'status' => $pwaStatus,
                'total_amount' => (float) $order->grand_total,
                'items_count' => $itemsCount,
                'payment_status' => $order->payment_method === 'kredit' ? 'TEMPO' : 'COD',
                'driver' => null
            ];
        }

        usort($formattedOrders, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });

        return response()->json([
            'success' => true,
            'data' => array_values($formattedOrders)
        ]);
    }

    public function getOrderDetails(Request $request, $id)
    {
        $reqCustId = $request->query('customer_id');

        if (!$reqCustId) {
            return response()->json([
                'success' => false,
                'message' => 'ID Pelanggan tidak dikirim dari aplikasi.'
            ], 400);
        }

        $customer = \App\Models\Customer::where('id', $reqCustId)
            ->orWhere('customer_code', $reqCustId)
            ->first();

        if (!$customer) {
             return response()->json([
                'success' => false,
                'message' => 'Data pelanggan tidak ditemukan.'
            ], 404);
        }

        if (str_starts_with($id, 'INV_')) {
            $realId = str_replace('INV_', '', $id);
            $sale = DB::table('sales')->where('id', $realId)->where('customer_id', $customer->id)->first();
            
            if (!$sale) return response()->json(['success' => false, 'message' => 'Faktur tidak ditemukan.'], 404);

            $pwaStatus = 'Diproses';
            if (in_array($sale->delivery_status, ['void', 'batal', 'cancelled'])) $pwaStatus = 'Batal'; 
            elseif (in_array($sale->delivery_status, ['dikirim', 'terkirim'])) $pwaStatus = 'Dikirim';
            elseif ($sale->delivery_status === 'selesai') $pwaStatus = 'Selesai';

            $items = DB::table('sale_items')->where('sale_id', $sale->id)->get();
            $formattedItems = $items->map(function ($item) {
                return [
                    'product_name' => $item->product_name ?? 'Item P-LINK', 
                    'qty' => $item->quantity ?? 1,
                    'unit' => $item->unit ?? 'Pcs',
                    'price' => $item->unit_price ?? 0,
                    'total_price' => $item->total_price ?? 0,
                ];
            });

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $id,
                    'invoice_number' => $sale->invoice_number,
                    'created_at' => $sale->created_at,
                    'status' => $pwaStatus,
                    'payment_status' => $sale->payment_method === 'kredit' ? 'tempo' : 'cod',
                    'due_date' => $sale->due_date ?? null,
                    'sub_total' => $sale->subtotal ?? 0,
                    'shipping_fee' => $sale->shipping_fee ?? 0,
                    'grand_total' => $sale->grand_total,
                    'items' => $formattedItems
                ]
            ]);

        } else {
            $realId = str_replace('SO_', '', $id);
            $order = DB::table('sales_orders')->where('id', $realId)->where('customer_id', $customer->id)->first();
            
            if (!$order) return response()->json(['success' => false, 'message' => 'Pesanan tidak ditemukan.'], 404);

            $pwaStatus = 'Diproses';
            if (in_array($order->status, ['batal', 'cancelled'])) $pwaStatus = 'Batal';
            elseif ($order->status === 'reschedule') $pwaStatus = 'Diproses (Jadwal Ulang)';
            elseif ($order->status === 'credit_hold') $pwaStatus = 'Menunggu Approval';

            $items = DB::table('sales_order_items')
                ->join('products', 'sales_order_items.product_id', '=', 'products.id')
                ->where('sales_order_items.sales_order_id', $order->id)
                ->select('sales_order_items.*', 'products.name as product_name', 'products.variant_name')
                ->get();

            $formattedItems = $items->map(function ($item) {
                $productName = $item->variant_name ? $item->product_name . ' - ' . $item->variant_name : $item->product_name;
                if ($item->is_free_item) {
                    $productName .= " ( BONUS )";
                }
                return [
                    'product_name' => $productName ?? 'Item P-LINK', 
                    'qty' => $item->qty ?? 1,
                    'unit' => $item->unit_name ?? 'Pcs',
                    'price' => $item->price ?? 0,
                    'total_price' => $item->total_price ?? 0,
                ];
            });

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $id,
                    'invoice_number' => $order->so_number . ($order->status === 'partially_delivered' ? ' (Antrean Sisa Barang)' : ''),
                    'created_at' => $order->created_at,
                    'status' => $pwaStatus,
                    'payment_status' => $order->payment_method === 'kredit' ? 'tempo' : 'cod',
                    'due_date' => $order->delivery_date ?? null,
                    'sub_total' => $order->subtotal ?? 0,
                    'shipping_fee' => $order->shipping_fee ?? 0,
                    'grand_total' => $order->grand_total,
                    'items' => $formattedItems
                ]
            ]);
        }
    }

    public function register(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'shop_name'  => 'required|string|max:255',
                'owner_name' => 'required|string|max:255',
                'address'    => 'required|string',
                'benchmark'  => 'nullable|string|max:255',
                'latitude'   => 'nullable|numeric',
                'longitude'  => 'nullable|numeric',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'status'  => 'error',
                    'message' => 'Data pendaftaran tidak lengkap.',
                    'errors'  => $validator->errors()
                ], 422);
            }

            $customer = Customer::create([
                'name'           => $request->shop_name, 
                'owner_name'     => $request->owner_name,
                'address'        => $request->address,
                'benchmark'      => $request->benchmark,
                'latitude'       => $request->latitude,
                'longitude'      => $request->longitude,
                'is_active'      => false, 
                'price_level'    => 1,     
                'due_days'       => 0,
                'loyalty_points' => 0,
                'is_pkp'         => 0,
            ]);

            return response()->json([
                'success' => true,
                'status'  => 'success',
                'message' => 'Pendaftaran berhasil disimpan. Menunggu verifikasi admin.',
                'data'    => $customer
            ], 201);

        } catch (\Exception $e) {
            Log::error('API Registrasi Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'status'  => 'error',
                'message' => 'Terjadi kesalahan pada server saat menyimpan pendaftaran.'
            ], 500);
        }
    }

    // ========================================================================
    // PERBAIKAN: Fungsi Selesai Kiriman Mendukung "Fallback" Admin Tanpa Foto/GPS
    // ========================================================================
    public function completeDelivery(Request $request, $id)
    {
        try {
            $user = $request->user();
            $sale = Sale::find($id);
            if (!$sale) {
                return response()->json([
                    'success' => false,
                    'status'  => 'error',
                    'message' => 'Data pesanan/pengiriman tidak ditemukan di sistem.'
                ], 404);
            }

            // PERBAIKAN ENTERPRISE: Proteksi Eksekusi Silang Cabang untuk Admin Gudang
            if ($user && !in_array($user->role, ['owner', 'driver']) && $sale->branch_id !== $user->branch_id) {
                return response()->json([
                    'success' => false, 
                    'status' => 'error', 
                    'message' => 'Akses ditolak: Pesanan ini bukan wewenang cabang Anda.'
                ], 403);
            }

            // PERBAIKAN: Aturan `required` diubah jadi `nullable` 
            // agar Admin Gudang bisa eksekusi tanpa memicu validasi error.
            $validator = Validator::make($request->all(), [
                'pod_photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048', 
                'pod_lat'   => 'nullable|numeric',
                'pod_lng'   => 'nullable|numeric',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'status'  => 'error',
                    'message' => 'Format foto atau data koordinat tidak valid.',
                    'errors'  => $validator->errors()
                ], 422);
            }

            $podPath = $sale->pod_photo; // Pertahankan jika sudah ada
            if ($request->hasFile('pod_photo')) {
                $file = $request->file('pod_photo');
                $filename = 'POD_' . str_replace('/', '-', $sale->invoice_number) . '_' . time() . '.' . $file->getClientOriginalExtension();
                $podPath = $file->storeAs('pod_deliveries', $filename, 'public');
            }

            $sale->delivery_status = 'selesai';
            $sale->pod_photo = $podPath; 
            
            // Masukkan data GPS jika dikirim oleh aplikasi Kurir (jika tidak dikirim, abaikan / biarkan NULL)
            if ($request->filled('pod_lat')) {
                $sale->pod_lat = $request->pod_lat;
            }
            if ($request->filled('pod_lng')) {
                $sale->pod_lng = $request->pod_lng;
            }

            $sale->save();

            return response()->json([
                'success' => true,
                'status'  => 'success',
                'message' => 'Pengiriman berhasil diselesaikan.',
                'data' => [
                    'invoice_number' => $sale->invoice_number,
                    'delivery_status' => $sale->delivery_status,
                    'pod_photo_url' => $podPath ? asset('storage/'.$podPath) : null
                ]
            ], 200);

        } catch (\Exception $e) {
            Log::error('API Upload POD Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'status'  => 'error',
                'message' => 'Terjadi kesalahan internal server saat memproses penyelesaian.'
            ], 500);
        }
    }

    public function processOrder(Request $request)
    {
        $request->validate([
            'sale_id' => 'required|exists:sales,id',
            'driver_id' => 'required' 
        ]);

        try {
            $user = $request->user();
            $sale = \App\Models\Sale::findOrFail($request->sale_id);
            
            // PERBAIKAN ENTERPRISE: Proteksi API Tampering Silang Cabang
            if ($user && $user->role !== 'owner' && $sale->branch_id !== $user->branch_id) {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Akses ditolak: Pesanan ini bukan wewenang cabang Anda.'
                ], 403);
            }

            if ($sale->delivery_status === 'batal') {
                return response()->json(['status' => 'error', 'message' => 'Pesanan ini sudah dibatalkan sebelumnya.'], 400);
            }
            if ($sale->delivery_status === 'diproses' || $sale->delivery_status === 'dikirim' || $sale->delivery_status === 'selesai') {
                return response()->json(['status' => 'error', 'message' => 'Pesanan ini sudah diproses.'], 400);
            }

            DB::table('sales')->where('id', $sale->id)->update([
                'driver_id' => $request->driver_id,
                'delivery_status' => 'diproses',
                'updated_at' => now(),
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'Pesanan berhasil diproses dan kurir ditugaskan.',
                'data' => clone $sale 
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal memproses pesanan: ' . $e->getMessage()
            ], 500);
        }
    }

    public function cancelOrder(Request $request)
    {
        $request->validate([
            'sale_id' => 'required' 
        ]);

        try {
            $user = $request->user();
            DB::beginTransaction();
            $so = DB::table('sales_orders')->where('id', $request->sale_id)->first();
            
            if (!$so) {
                throw new \Exception("Data pesanan tidak ditemukan.");
            }

            // PERBAIKAN ENTERPRISE: Proteksi Pembatalan Silang Cabang
            if ($user && $user->role !== 'owner' && $so->fulfillment_branch_id !== $user->branch_id) {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Akses ditolak: Pesanan ini bukan wewenang cabang Anda.'
                ], 403);
            }

            if ($so->status === 'batal') {
                return response()->json(['status' => 'error', 'message' => 'Pesanan sudah dibatalkan sebelumnya.'], 400);
            }

            if (!in_array($so->status, ['pending', 'reschedule'])) {
                return response()->json(['status' => 'error', 'message' => 'Pesanan sudah diproses (dikirim) dan tidak bisa dibatalkan dari antrean ini.'], 400);
            }

            $soItems = DB::table('sales_order_items')->where('sales_order_id', $so->id)->get();

            foreach ($soItems as $item) {
                $product = \App\Models\Product::find($item->product_id);
                $multiplier = 1;
                
                if ($product) {
                    $uName = strtoupper(trim($item->unit_name));
                    if ($uName === strtoupper(trim($product->buy_unit ?? $product->satuan_besar ?? ''))) $multiplier = $product->conversion_factor ?? 1;
                    elseif ($uName === strtoupper(trim($product->unit_3_name ?? $product->satuan_l3 ?? ''))) $multiplier = $product->conversion_3_qty ?? 1;
                    elseif ($uName === strtoupper(trim($product->unit_4_name ?? $product->satuan_l4 ?? ''))) $multiplier = $product->conversion_4_qty ?? 1;
                }

                $totalBaseQty = $item->qty * $multiplier;
                $stock = \App\Models\ProductStock::where('branch_id', $so->fulfillment_branch_id)
                            ->where('product_id', $item->product_id)
                            ->first();

                if ($stock) {
                    $stock->reserved_qty -= $totalBaseQty;
                    if ($stock->reserved_qty < 0) {
                        $stock->reserved_qty = 0;
                    }
                    $stock->save();
                }
            }

            DB::table('sales_orders')->where('id', $so->id)->update([
                'status' => 'batal',
                'updated_at' => now()
            ]);

            DB::commit();
            return response()->json([
                'status' => 'success', 
                'message' => 'Pesanan berhasil dibatalkan. Booking stok telah dilepas dan barang kembali tersedia.'
            ], 200);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => 'error', 'message' => 'Gagal membatalkan: ' . $e->getMessage()], 500);
        }
    }

    public function getPendingOrders(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id'
        ]);

        $user = $request->user();
        
        // PERBAIKAN ENTERPRISE: Amankan Tarikan Data Antrean
        // Cegah Admin Cabang merequest antrean cabang lain dengan mengubah parameter branch_id
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->branch_id;

        // PERBAIKAN: Menggunakan whereIn untuk pengecekan array status query builder Laravel
        $orders = DB::table('sales_orders')
            ->where('fulfillment_branch_id', $branchId)
            ->whereIn('status', ['pending', 'reschedule'])
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($orders as $order) {
            $order->items = DB::table('sales_order_items')
                ->join('products', 'sales_order_items.product_id', '=', 'products.id')
                ->where('sales_order_items.sales_order_id', $order->id)
                ->select('sales_order_items.*', 'products.name as product_name', 'products.variant_name')
                ->get();

            foreach ($order->items as $item) {
                $item->product_name = $item->variant_name ? $item->product_name . ' - ' . $item->variant_name : $item->product_name;
                if ($item->is_free_item) {
                    $item->product_name .= " ( BONUS )";
                }
            }
        }

        $drivers = \App\Models\User::where('role', 'driver')
            ->where('branch_id', $branchId)
            ->get();

        return response()->json([
            'status' => 'success',
            'data' => $orders,
            'drivers' => $drivers
        ]);
    }

    // ========================================================================
    // FITUR BARU: AMBIL PROFIL LIVE & TOTAL PIUTANG PELANGGAN (DIPERBAIKI)
    // ========================================================================
    public function getCustomerProfile(Request $request)
    {
        $reqCustId = $request->query('customer_id');

        if (!$reqCustId) {
            return response()->json(['success' => false, 'message' => 'ID Pelanggan tidak valid.'], 400);
        }

        $customer = Customer::where('id', $reqCustId)->orWhere('customer_code', $reqCustId)->first();

        if (!$customer) {
            return response()->json(['success' => false, 'message' => 'Data pelanggan tidak ditemukan.'], 404);
        }

        // PERBAIKAN: Hitung Piutang dengan membaca tabel `sales` dan tabel `debt_payments`
        $sales = DB::table('sales')
            ->where('customer_id', $customer->id)
            ->whereIn('payment_status', ['pending', 'partial'])
            ->get();

        $totalDebt = 0;
        foreach($sales as $sale) {
            // Cek apakah faktur ini sudah pernah dicicil di tabel debt_payments
            $paid = DB::table('debt_payments')->where('sale_id', $sale->id)->sum('amount');
            $totalDebt += ($sale->grand_total - $paid);
        }

        $creditLimit = (float) $customer->credit_limit;
        
        // Sisa Limit = Limit Kredit dikurangi Total Piutang Berjalan
        $remainingCredit = max(0, $creditLimit - $totalDebt);

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $customer->id,
                'name' => $customer->name,
                'credit_limit' => $creditLimit,
                'current_debt' => (float) $totalDebt,
                'remaining_credit' => $remainingCredit
            ]
        ]);
    }
}