<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ConveyanceBill;
use App\Models\Customer;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Sale;
use App\Models\Supplier;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use App\Support\SaleInvoiceMetrics;

class ReportController extends Controller
{
    public function index(Request $request): View
    {
        $from = $request->input('from', now()->startOfMonth()->toDateString());
        $to = $request->input('to', now()->toDateString());
        $sales = Sale::whereBetween('sale_date', [$from, $to]);
        $purchases = Purchase::whereBetween('purchase_date', [$from, $to]);
        $expenses = ConveyanceBill::whereBetween('bill_date', [$from, $to]);

        $summary = [
            'sales' => SaleInvoiceMetrics::sumGrandTotal(clone $sales),
            'sales_due' => SaleInvoiceMetrics::sumDue(Sale::whereBetween('sale_date', [$from, $to])),
            'purchase' => (float) $purchases->sum('grand_total'),
            'expense' => (float) $expenses->sum('amount'),
            'profit' => (float) Sale::whereBetween('sale_date', [$from, $to])->sum('profit'),
            'customers' => Customer::count(),
            'suppliers' => Supplier::count(),
            'products' => Product::count(),
        ];

        $topProducts = Sale::select('product_name', DB::raw('SUM(quantity_sold) as qty'), DB::raw('SUM(total_amount) as amount'))
            ->whereBetween('sale_date', [$from, $to])
            ->groupBy('product_name')
            ->orderByDesc('qty')->limit(10)->get();

        $dailySales = SaleInvoiceMetrics::dailyGrandTotals($from, $to);

        $lowStock = Product::where('stock_quantity', '<=', 5)->orderBy('stock_quantity')->limit(20)->get();

        return view('admin.reports.index', compact('summary','topProducts','dailySales','lowStock','from','to'));
    }
}
