<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Sale;
use App\Models\StockMovement;
use App\Models\User;
use App\Models\WarehouseStock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    /**
     * GET /api/dashboard
     */
    public function index(Request $request)
    {
        $today = now()->toDateString();
        $month = now()->startOfMonth();
        $warehouseId = $request->integer('warehouse_id');

        // Penjualan hari ini (exclude voided sales)
        $salesToday = Sale::whereDate('created_at', $today)
            ->whereNull('voided_at')
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->sum('total');

        // Total pesanan menunggu void approval
        $pendingVoids = Sale::where('void_status', 'pending')
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->count();

        // Produk stok rendah
        if ($warehouseId) {
            $lowStockCount = WarehouseStock::where('warehouse_id', $warehouseId)->lowStock()->count();
        } else {
            $lowStockCount = Product::active()->lowStock()->count();
        }

        // PO menunggu
        $pendingPO = Purchase::whereIn('status', ['draft', 'sent', 'partial'])
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->count();

        // Penjualan bulan ini (exclude voided sales)
        $salesMonth = Sale::where('created_at', '>=', $month)
            ->whereNull('voided_at')
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->sum('total');

        // Top 5 produk terlaris bulan ini
        $topProductsQuery = DB::table('sale_items')
            ->join('sales', 'sales.id', '=', 'sale_items.sale_id')
            ->where('sales.created_at', '>=', $month)
            ->whereNull('sales.voided_at');

        if ($warehouseId) {
            $topProductsQuery->where('sales.warehouse_id', $warehouseId);
        }

        $topProducts = $topProductsQuery
            ->selectRaw('sale_items.product_name, SUM(sale_items.qty) as total_qty, SUM(sale_items.subtotal) as total_revenue')
            ->groupBy('sale_items.product_name')
            ->orderByDesc('total_qty')
            ->limit(5)
            ->get();

        // Tren penjualan 7 hari terakhir
        $salesTrend = collect(range(6, 0))->map(function ($daysAgo) use ($warehouseId) {
            $date = now()->subDays($daysAgo)->toDateString();
            $total = Sale::whereDate('created_at', $date)
                ->whereNull('voided_at')
                ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
                ->sum('total');
            return ['date' => $date, 'total' => (float) $total];
        })->values();

        // Gerakan stok terbaru
        $recentMovements = StockMovement::with(['user:id,name', 'warehouse:id,code,name'])
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->latest()
            ->limit(10)
            ->get()
            ->map(fn($m) => [
                'id'             => $m->id,
                'product_name'   => $m->product_name,
                'type'           => $m->type,
                'reason'         => $m->reason,
                'qty'            => $m->qty,
                'user_name'      => $m->user?->name ?? 'System',
                'warehouse_name' => $m->warehouse?->name ?? '-',
                'created_at'     => $m->created_at->toISOString(),
            ]);

        // Status pesanan per channel
        $salesByChannel = Sale::whereNull('voided_at')
            ->when($warehouseId, fn($q) => $q->where('warehouse_id', $warehouseId))
            ->selectRaw('channel, COUNT(*) as count, SUM(total) as revenue')
            ->groupBy('channel')
            ->get();

        return response()->json([
            'stats' => [
                'sales_today'    => $salesToday,
                'pending_voids'  => $pendingVoids,
                'low_stock'      => $lowStockCount,
                'pending_po'     => $pendingPO,
                'sales_month'    => $salesMonth,
                'total_products' => Product::active()->count(),
                'total_users'    => User::where('is_active', true)->count(),
            ],
            'top_products'     => $topProducts,
            'recent_movements' => $recentMovements,
            'sales_by_channel' => $salesByChannel,
            'sales_trend'      => $salesTrend,
        ]);
    }
}
