<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\{Asset, Repair, AssetAssignment};
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AssetOverviewController extends Controller
{
    public function index(Request $request)
    {
        // summary cards
        $totalAssets   = Asset::count();
        $assignedCount = Asset::where('status', 'Assigned')->count();
        $inStockCount  = Asset::where('status', 'In-Stock')->count();
        $repairCount   = Asset::where('status', 'Repair')->count();
        $scrapCount    = Asset::where('status', 'Scrap')->count();

        // month repair spend
        $totalRepairCostThisMonth = Repair::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('cost');

        // distribution
        $assetByType = Asset::selectRaw('device_type, COUNT(*) as total')
            ->groupBy('device_type')
            ->pluck('total', 'device_type');

        // top 5 most repaired (with current holder if any)
        $mostRepaired = Repair::query()
            ->leftJoin('assets', 'assets.id', '=', 'repairs.asset_id')
            ->leftJoin('asset_assignments as aa', function ($j) {
                $j->on('aa.asset_id', '=', 'repairs.asset_id')
                  ->whereNull('aa.returned_date');
            })
            ->leftJoin('employees as e', 'e.id', '=', 'aa.employee_id')
            ->select([
                'repairs.asset_id',
                'assets.asset_tag',
                'assets.device_type',
                DB::raw('COUNT(repairs.id) as total_repairs'),
                DB::raw('COALESCE(e.name, "—") as employee_name'),
            ])
            ->groupBy('repairs.asset_id', 'assets.asset_tag', 'assets.device_type', 'e.name')
            ->orderByDesc('total_repairs')
            ->limit(5)
            ->get();

        // NEW: Asset list (employee + repairs count + total cost), paginated
        $assetSummary = Asset::query()
            ->leftJoin('asset_assignments as aa', function ($j) {
                $j->on('aa.asset_id', '=', 'assets.id')
                  ->whereNull('aa.returned_date');
            })
            ->leftJoin('employees as e', 'e.id', '=', 'aa.employee_id')
            ->leftJoin('repairs as r', 'r.asset_id', '=', 'assets.id')
            ->select([
                'assets.id',
                'assets.asset_tag',
                'assets.device_type',
                DB::raw('COALESCE(e.name, "—") as employee_name'),
                DB::raw('COUNT(r.id) as repairs_count'),
                DB::raw('COALESCE(SUM(r.cost),0) as repairs_cost'),
            ])
            ->groupBy('assets.id', 'assets.asset_tag', 'assets.device_type', 'e.name')
            ->orderBy('assets.asset_tag')
            ->paginate(10)
            ->withQueryString();

        // recent assignments
        $recentAssignments = AssetAssignment::with(['asset:id,asset_tag', 'employee:id,name'])
            ->latest('assigned_date')->take(5)->get();

        return view('asset.assets.overview', compact(
            'totalAssets','assignedCount','inStockCount','repairCount','scrapCount',
            'totalRepairCostThisMonth','assetByType','mostRepaired','recentAssignments',
            'assetSummary'
        ));
    }
}
