<?php

namespace App\Services\Dashboard;

use App\Models\InventoryBalance;
use App\Models\Location;
use App\Models\Order;
use App\Models\Product;
use App\Models\StockTransfer;
use App\Models\User;
use App\Models\WhatsappStoreCredits;
use App\Services\LocationService;
use App\Services\OtpService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;

class OverviewDashboardService
{
    public function __construct(
        protected LocationService $locationService,
        protected OtpService $otpService
    ) {
    }

    /**
     * @return array<string, mixed>
     */
    public function build(User $user, Collection $allLocations): array
    {
        $locationIds = $allLocations->pluck('id');
        $hasLocationColumn = Schema::hasColumn('orders', 'fulfillment_location_id');

        $paid = Order::query()->paid();
        $orders = Order::query();

        $todaySales = (clone $paid)->whereDate('created_at', today())->sum('total_payable');
        $todayOrders = (clone $orders)->whereDate('created_at', today())->count();
        $monthSales = (clone $paid)
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('total_payable');
        $pendingOrders = (clone $orders)->where('status', 'placed')->count();

        $locationCards = $allLocations->map(function (Location $loc) use ($hasLocationColumn) {
            $salesToday = 0.0;
            $ordersToday = 0;
            if ($hasLocationColumn) {
                $salesToday = (float) Order::query()
                    ->paid()
                    ->where('fulfillment_location_id', $loc->id)
                    ->whereDate('created_at', today())
                    ->sum('total_payable');
                $ordersToday = Order::query()
                    ->where('fulfillment_location_id', $loc->id)
                    ->whereDate('created_at', today())
                    ->count();
            }

            $onHand = 0;
            if (Schema::hasTable('inventory_balances')) {
                $onHand = (int) InventoryBalance::query()
                    ->where('location_id', $loc->id)
                    ->sum('on_hand');
            }

            return (object) [
                'id' => $loc->id,
                'name' => $loc->name,
                'type' => $loc->type,
                'sales_today' => $salesToday,
                'orders_today' => $ordersToday,
                'on_hand' => $onHand,
            ];
        });

        $openTransfers = 0;
        if (Schema::hasTable('stock_transfers')) {
            $openTransfers = StockTransfer::query()
                ->whereIn('status', [
                    StockTransfer::STATUS_DRAFT,
                    StockTransfer::STATUS_APPROVED,
                    StockTransfer::STATUS_IN_TRANSIT,
                ])
                ->count();
        }

        $storeStockUnits = 0;
        $warehouseStockUnits = 0;
        if (Schema::hasTable('inventory_balances')) {
            $storeIds = $allLocations->where('type', Location::TYPE_STORE)->pluck('id');
            $whIds = $allLocations->where('type', Location::TYPE_WAREHOUSE)->pluck('id');
            $storeStockUnits = $storeIds->isNotEmpty()
                ? (int) InventoryBalance::query()->whereIn('location_id', $storeIds)->sum('on_hand')
                : 0;
            $warehouseStockUnits = $whIds->isNotEmpty()
                ? (int) InventoryBalance::query()->whereIn('location_id', $whIds)->sum('on_hand')
                : 0;
        }

        $totalCustomers = User::whereDoesntHave('roles')->count();
        $totalProducts = Product::count();
        $activeProducts = Product::active()->count();

        $whatsApp = WhatsappStoreCredits::where('id', 1)->first();
        $response = $this->otpService->smsWalletBalance();
        $SMScount = ! empty($response['sms_count']) ? (int) $response['sms_count'] : 0;
        $SmsWallet = ! empty($response['wallet']) ? number_format($response['wallet'], 2) : 0;
        $smsUrl = ! empty($response['smsUrl']) ? $response['smsUrl'] : 'https://sms.kiyosolutions.com/';

        return [
            'todaySales' => $todaySales,
            'todayOrders' => $todayOrders,
            'monthSales' => $monthSales,
            'pendingOrders' => $pendingOrders,
            'locationCards' => $locationCards,
            'openTransfers' => $openTransfers,
            'storeStockUnits' => $storeStockUnits,
            'warehouseStockUnits' => $warehouseStockUnits,
            'totalCustomers' => $totalCustomers,
            'totalProducts' => $totalProducts,
            'activeProducts' => $activeProducts,
            'whatsApp' => $whatsApp,
            'SMScount' => $SMScount,
            'SmsWallet' => $SmsWallet,
            'smsUrl' => $smsUrl,
            'locationCount' => $locationIds->count(),
        ];
    }
}
