<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Asset, Repair, AssetAssignment};
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\AssetOverviewExport;


class AssetDashboardController 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 (for chart)
        $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();

        // Paginated Asset Health Snapshot (same columns you see in the table)
        $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 (right section)
        $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'
        ));
    }

    public function export(Request $request)
    {
        // Same metrics for header rows
        $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();
        $totalRepairCostThisMonth = Repair::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('cost');

        // Full (not paginated) list for export
        $list = 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.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.asset_tag', 'assets.device_type', 'e.name')
            ->orderBy('assets.asset_tag')
            ->get();

        // Build the worksheet rows: Summary block + blank + table header + table rows
        $rows = [];
        $rows[] = ['Asset Dashboard Export - '.now()->format('M d, Y H:i')];
        $rows[] = [];
        $rows[] = ['SUMMARY'];
        $rows[] = ['Total Assets', $totalAssets];
        $rows[] = ['Assigned', $assignedCount];
        $rows[] = ['In-Stock', $inStockCount];
        $rows[] = ['Under Repair', $repairCount];
        $rows[] = ['Scrapped', $scrapCount];
        $rows[] = ['Repair Cost ('.now()->format('M Y').')', $totalRepairCostThisMonth];
        $rows[] = [];
        $rows[] = ['ASSET LIST'];
        $rows[] = ['Asset Tag', 'Device Type', 'Employee', 'Repairs', 'Repair Cost (₹)'];

        foreach ($list as $r) {
            $rows[] = [
                $r->asset_tag,
                $r->device_type,
                $r->employee_name,
                (int)$r->repairs_count,
                (float)$r->repairs_cost,
            ];
        }

        $file = 'asset_overview_'.now()->format('Ymd_His').'.xlsx';
        return Excel::download(new AssetOverviewExport($rows), $file);
    }
}
