<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Order, Voucher, Router};

class DashboardController extends Controller
{
  public function index()
{
    $stats = [
        'routers'      => \App\Models\Router::count(),
        'vouchers'     => \App\Models\Voucher::count(),
        'sales_today'  => \App\Models\Order::paid()->whereDate('created_at', now()->toDateString())->sum('amount'),
    ];

    // recent orders for table
    $orders = \App\Models\Order::latest()->take(8)->get();

    // payment mix (last 30 days)
    $mixData = \App\Models\Order::where('created_at','>=',now()->subDays(30))
        ->selectRaw('gateway, COUNT(*) as c')->groupBy('gateway')->pluck('c','gateway');
    $total = max(1, $mixData->sum());
    $mix = $mixData->map(function($v,$k) use($total){ return ['name'=>strtoupper($k), 'val'=>round($v*100/$total)]; })->values();

    return view('dashboard', compact('stats','orders','mix'));
}
}
