<?php
// app/Http/Controllers/Admin/ReportController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryRecord;
use App\Models\User;
use App\Models\Warehouse;
use App\Models\CommissionRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Response;

class ReportController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'verified', 'role:admin']);
    }

    /**
     * Main Report Dashboard
     */
    public function index()
    {
        // Quick stats for dashboard
        $stats = [
            'total_deliveries' => DeliveryRecord::count(),
            'total_commission' => DeliveryRecord::sum('commission_amount'),
            'active_users' => User::where('is_active', true)->whereIn('role', ['2wheel', '4wheel'])->count(),
            'active_warehouses' => Warehouse::where('is_active', true)->count(),
        ];

        // This month's performance
        $thisMonthStats = DeliveryRecord::whereMonth('delivery_date', Carbon::now()->month)
            ->whereYear('delivery_date', Carbon::now()->year)
            ->selectRaw('COUNT(*) as total_deliveries')
            ->selectRaw('SUM(parcel_count) as total_parcels')
            ->selectRaw('SUM(commission_amount) as total_commission')
            ->first();

        // Last month's performance for comparison
        $lastMonthStats = DeliveryRecord::whereMonth('delivery_date', Carbon::now()->subMonth()->month)
            ->whereYear('delivery_date', Carbon::now()->subMonth()->year)
            ->selectRaw('COUNT(*) as total_deliveries')
            ->selectRaw('SUM(parcel_count) as total_parcels')
            ->selectRaw('SUM(commission_amount) as total_commission')
            ->first();

        return view('admin.reports.index', compact('stats', 'thisMonthStats', 'lastMonthStats'));
    }

    /**
     * Delivery Report
     */
    public function delivery(Request $request)
    {
        // Get filter parameters
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        $warehouseCode = $request->input('warehouse');
        $vehicleType = $request->input('vehicle_type');
        $userId = $request->input('user_id');
        
        // Build query
        $query = DeliveryRecord::with(['user', 'user.warehouse'])
            ->whereBetween('delivery_date', [$startDate, $endDate]);
        
        // Apply filters
        if ($warehouseCode) {
            $query->whereHas('user', function ($q) use ($warehouseCode) {
                $q->where('warehouse_code', $warehouseCode);
            });
        }
        
        if ($vehicleType) {
            $query->whereHas('user', function ($q) use ($vehicleType) {
                $q->where('role', $vehicleType);
            });
        }

        if ($userId) {
            $query->where('user_id', $userId);
        }
        
        // Calculate statistics
        $stats = [
            'total_deliveries' => (clone $query)->count(),
            'total_parcels' => (clone $query)->sum('parcel_count'),
            'total_commission' => (clone $query)->sum('commission_amount'),
            'avg_parcels_per_delivery' => (clone $query)->avg('parcel_count'),
        ];
        
        // Get daily trend data
        $dailyTrend = (clone $query)
            ->selectRaw('DATE(delivery_date) as date')
            ->selectRaw('COUNT(*) as delivery_count')
            ->selectRaw('SUM(parcel_count) as parcel_count')
            ->selectRaw('SUM(commission_amount) as commission_amount')
            ->groupBy('date')
            ->orderBy('date')
            ->get();
        
        // Get top performers
        $topPerformers = (clone $query)
            ->select('user_id')
            ->selectRaw('COUNT(*) as delivery_count')
            ->selectRaw('SUM(parcel_count) as total_parcels')
            ->selectRaw('SUM(commission_amount) as total_commission')
            ->with('user')
            ->groupBy('user_id')
            ->orderByDesc('total_parcels')
            ->limit(10)
            ->get();
        
        // Get warehouse distribution
        $warehouseDistribution = (clone $query)
            ->join('users', 'delivery_records.user_id', '=', 'users.id')
            ->select('users.warehouse_code')
            ->selectRaw('COUNT(DISTINCT users.id) as user_count')
            ->selectRaw('COUNT(delivery_records.id) as delivery_count')
            ->selectRaw('SUM(delivery_records.parcel_count) as total_parcels')
            ->selectRaw('SUM(delivery_records.commission_amount) as total_commission')
            ->groupBy('users.warehouse_code')
            ->with(['user.warehouse'])
            ->get();
        
        // Get vehicle type distribution
        $vehicleTypeDistribution = (clone $query)
            ->join('users', 'delivery_records.user_id', '=', 'users.id')
            ->select('users.role')
            ->selectRaw('COUNT(DISTINCT users.id) as user_count')
            ->selectRaw('COUNT(delivery_records.id) as delivery_count')
            ->selectRaw('SUM(delivery_records.parcel_count) as total_parcels')
            ->selectRaw('SUM(delivery_records.commission_amount) as total_commission')
            ->groupBy('users.role')
            ->get();
        
        // Get data for table (paginated)
        $deliveries = $query->orderBy('delivery_date', 'desc')->paginate(50);
        
        // Get filter options
        $warehouses = Warehouse::active()->orderBy('code')->get();
        $users = User::whereIn('role', ['2wheel', '4wheel'])
            ->where('is_active', true)
            ->orderBy('first_name')
            ->get();
        
        return view('admin.reports.delivery', compact(
            'stats',
            'dailyTrend',
            'topPerformers',
            'warehouseDistribution',
            'vehicleTypeDistribution',
            'deliveries',
            'warehouses',
            'users',
            'startDate',
            'endDate',
            'warehouseCode',
            'vehicleType',
            'userId'
        ));
    }
    
    /**
     * Commission Report
     */
    public function commission(Request $request)
    {
        // Get filter parameters
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        $warehouseCode = $request->input('warehouse');
        $vehicleType = $request->input('vehicle_type');
        
        // Build query
        $query = DeliveryRecord::with(['user', 'user.warehouse'])
            ->whereBetween('delivery_date', [$startDate, $endDate]);
        
        // Apply filters
        if ($warehouseCode) {
            $query->whereHas('user', function ($q) use ($warehouseCode) {
                $q->where('warehouse_code', $warehouseCode);
            });
        }
        
        if ($vehicleType) {
            $query->whereHas('user', function ($q) use ($vehicleType) {
                $q->where('role', $vehicleType);
            });
        }
        
        // Calculate statistics
        $stats = [
            'total_commission' => (clone $query)->sum('commission_amount'),
            'total_parcels' => (clone $query)->sum('parcel_count'),
            'avg_commission_per_parcel' => 0,
            'avg_commission_per_user' => 0,
        ];
        
        // Calculate averages
        $totalParcels = $stats['total_parcels'];
        if ($totalParcels > 0) {
            $stats['avg_commission_per_parcel'] = $stats['total_commission'] / $totalParcels;
        }
        
        $activeUsers = User::whereIn('role', ['2wheel', '4wheel'])
            ->where('is_active', true)
            ->when($warehouseCode, function ($q) use ($warehouseCode) {
                $q->where('warehouse_code', $warehouseCode);
            })
            ->when($vehicleType, function ($q) use ($vehicleType) {
                $q->where('role', $vehicleType);
            })
            ->count();
            
        if ($activeUsers > 0) {
            $stats['avg_commission_per_user'] = $stats['total_commission'] / $activeUsers;
        }
        
        // Get monthly trend (last 12 months)
        $monthlyTrend = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $monthData = DeliveryRecord::whereMonth('delivery_date', $date->month)
                ->whereYear('delivery_date', $date->year)
                ->when($warehouseCode, function ($q) use ($warehouseCode) {
                    $q->whereHas('user', function ($q2) use ($warehouseCode) {
                        $q2->where('warehouse_code', $warehouseCode);
                    });
                })
                ->when($vehicleType, function ($q) use ($vehicleType) {
                    $q->whereHas('user', function ($q2) use ($vehicleType) {
                        $q2->where('role', $vehicleType);
                    });
                })
                ->selectRaw('SUM(commission_amount) as total_commission')
                ->selectRaw('SUM(parcel_count) as total_parcels')
                ->first();
                
            $monthlyTrend[] = [
                'month' => $date->format('M Y'),
                'commission' => $monthData->total_commission ?? 0,
                'parcels' => $monthData->total_parcels ?? 0,
            ];
        }
        
        // Get commission by tier analysis
        $tierAnalysis = DB::table('delivery_records')
            ->select(
                DB::raw('CASE 
                    WHEN parcel_count <= 100 THEN "Tier 1 (1-100)"
                    WHEN parcel_count <= 200 THEN "Tier 2 (101-200)"
                    WHEN parcel_count <= 300 THEN "Tier 3 (201-300)"
                    WHEN parcel_count <= 500 THEN "Tier 4 (301-500)"
                    ELSE "Tier 5 (500+)"
                END as tier'),
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(parcel_count) as total_parcels'),
                DB::raw('SUM(commission_amount) as total_commission')
            )
            ->whereBetween('delivery_date', [$startDate, $endDate])
            ->when($warehouseCode, function ($q) use ($warehouseCode) {
                $q->join('users', 'delivery_records.user_id', '=', 'users.id')
                  ->where('users.warehouse_code', $warehouseCode);
            })
            ->when($vehicleType, function ($q) use ($vehicleType) {
                $q->join('users', 'delivery_records.user_id', '=', 'users.id')
                  ->where('users.role', $vehicleType);
            })
            ->groupBy('tier')
            ->get();
        
        // Get top earners
        $topEarners = (clone $query)
            ->select('user_id')
            ->selectRaw('SUM(parcel_count) as total_parcels')
            ->selectRaw('SUM(commission_amount) as total_commission')
            ->selectRaw('COUNT(*) as delivery_count')
            ->with(['user', 'user.warehouse'])
            ->groupBy('user_id')
            ->orderByDesc('total_commission')
            ->limit(20)
            ->get();
        
        // Get commission by warehouse
        $warehouseCommission = DB::table('delivery_records')
            ->join('users', 'delivery_records.user_id', '=', 'users.id')
            ->join('warehouses', 'users.warehouse_code', '=', 'warehouses.code')
            ->select(
                'warehouses.code',
                'warehouses.name',
                DB::raw('COUNT(DISTINCT users.id) as user_count'),
                DB::raw('SUM(delivery_records.parcel_count) as total_parcels'),
                DB::raw('SUM(delivery_records.commission_amount) as total_commission')
            )
            ->whereBetween('delivery_date', [$startDate, $endDate])
            ->when($vehicleType, function ($q) use ($vehicleType) {
                $q->where('users.role', $vehicleType);
            })
            ->groupBy('warehouses.code', 'warehouses.name')
            ->orderByDesc('total_commission')
            ->get();
        
        // Get filter options
        $warehouses = Warehouse::active()->orderBy('code')->get();
        
        return view('admin.reports.commission', compact(
            'stats',
            'monthlyTrend',
            'tierAnalysis',
            'topEarners',
            'warehouseCommission',
            'warehouses',
            'startDate',
            'endDate',
            'warehouseCode',
            'vehicleType'
        ));
    }
    
    /**
     * Warehouse Report
     */
    public function warehouse(Request $request)
    {
        // Get filter parameters
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        $warehouseCode = $request->input('warehouse');
        
        // Get all warehouses with metrics
        $warehousesQuery = Warehouse::with(['users' => function ($query) {
            $query->whereIn('role', ['2wheel', '4wheel']);
        }]);
        
        if ($warehouseCode) {
            $warehousesQuery->where('code', $warehouseCode);
        }
        
        $warehouses = $warehousesQuery->get()->map(function ($warehouse) use ($startDate, $endDate) {
            // Get user statistics
            $userStats = [
                'total_users' => $warehouse->users->count(),
                'active_users' => $warehouse->users->where('is_active', true)->count(),
                'vehicle_2wheel' => $warehouse->users->where('role', '2wheel')->count(),
                'vehicle_4wheel' => $warehouse->users->where('role', '4wheel')->count(),
            ];
            
            // Get delivery statistics
            $deliveryStats = DeliveryRecord::whereHas('user', function ($q) use ($warehouse) {
                    $q->where('warehouse_code', $warehouse->code);
                })
                ->whereBetween('delivery_date', [$startDate, $endDate])
                ->selectRaw('COUNT(*) as total_deliveries')
                ->selectRaw('COUNT(DISTINCT user_id) as active_employees')
                ->selectRaw('SUM(parcel_count) as total_parcels')
                ->selectRaw('SUM(commission_amount) as total_commission')
                ->first();
            
            // Calculate efficiency metrics
            $workingDays = Carbon::parse($startDate)->diffInDays(Carbon::parse($endDate)) + 1;
            $avgParcelsPerDay = 0;
            $avgParcelsPerUser = 0;
            $efficiency = 0;
            
            if ($workingDays > 0 && $deliveryStats->total_parcels > 0) {
                $avgParcelsPerDay = $deliveryStats->total_parcels / $workingDays;
                
                if ($deliveryStats->active_employees > 0) {
                    $avgParcelsPerUser = $deliveryStats->total_parcels / $deliveryStats->active_employees;
                    $efficiency = min(($avgParcelsPerUser / 100) * 100, 100); // Example efficiency calculation
                }
            }
            
            $warehouse->userStats = $userStats;
            $warehouse->deliveryStats = $deliveryStats;
            $warehouse->avgParcelsPerDay = $avgParcelsPerDay;
            $warehouse->avgParcelsPerUser = $avgParcelsPerUser;
            $warehouse->efficiency = $efficiency;
            
            return $warehouse;
        });
        
        // Calculate overall statistics
        $overallStats = [
            'total_warehouses' => $warehouses->count(),
            'total_users' => $warehouses->sum('userStats.total_users'),
            'total_deliveries' => $warehouses->sum('deliveryStats.total_deliveries'),
            'total_parcels' => $warehouses->sum('deliveryStats.total_parcels'),
            'total_commission' => $warehouses->sum('deliveryStats.total_commission'),
        ];
        
        // Get 6-month trend data
        $trendData = [];
        $trendLabels = [];
        
        for ($i = 5; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $trendLabels[] = $date->format('M Y');
            
            foreach ($warehouses as $warehouse) {
                $monthData = DeliveryRecord::whereHas('user', function ($q) use ($warehouse) {
                        $q->where('warehouse_code', $warehouse->code);
                    })
                    ->whereMonth('delivery_date', $date->month)
                    ->whereYear('delivery_date', $date->year)
                    ->sum('parcel_count');
                
                $trendData[$warehouse->name][] = $monthData;
            }
        }
        
        // Performance ranking
        $performanceRanking = $warehouses->sortByDesc('deliveryStats.total_parcels')->values();
        
        // Get filter options
        $allWarehouses = Warehouse::orderBy('code')->get();
        
        return view('admin.reports.warehouse', compact(
            'warehouses',
            'overallStats',
            'trendData',
            'trendLabels',
            'performanceRanking',
            'allWarehouses',
            'startDate',
            'endDate',
            'warehouseCode'
        ));
    }
    
    /**
     * Export delivery report
     */
    public function exportDeliveryReport(Request $request)
    {
        // Get the same data as delivery report
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        $warehouseCode = $request->input('warehouse');
        $vehicleType = $request->input('vehicle_type');
        $userId = $request->input('user_id');
        
        $query = DeliveryRecord::with(['user', 'user.warehouse'])
            ->whereBetween('delivery_date', [$startDate, $endDate]);
        
        if ($warehouseCode) {
            $query->whereHas('user', function ($q) use ($warehouseCode) {
                $q->where('warehouse_code', $warehouseCode);
            });
        }
        
        if ($vehicleType) {
            $query->whereHas('user', function ($q) use ($vehicleType) {
                $q->where('role', $vehicleType);
            });
        }

        if ($userId) {
            $query->where('user_id', $userId);
        }
        
        $deliveries = $query->orderBy('delivery_date', 'desc')->get();
        
        $filename = 'delivery_report_' . date('Y-m-d_H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function() use ($deliveries) {
            $file = fopen('php://output', 'w');
            
            // UTF-8 BOM for proper Thai character display in Excel
            fwrite($file, "\xEF\xBB\xBF");
            
            // Headers
            fputcsv($file, [
                'วันที่',
                'ชื่อผู้ส่ง',
                'อีเมล',
                'ประเภทรถ',
                'คลังสินค้า',
                'จำนวนพัสดุ',
                'ค่าคอมมิชชั่น',
            ]);

            // Data rows
            foreach ($deliveries as $delivery) {
                fputcsv($file, [
                    $delivery->delivery_date->format('d/m/Y'),
                    $delivery->user->name ?? '',
                    $delivery->user->email ?? '',
                    $delivery->user->role === '2wheel' ? 'รถ 2 ล้อ' : 'รถ 4 ล้อ',
                    $delivery->user->warehouse_code ?? '',
                    number_format($delivery->parcel_count),
                    number_format($delivery->commission_amount, 2),
                ]);
            }

            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
    
    /**
     * Export commission report
     */
    public function exportCommissionReport(Request $request)
    {
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        $warehouseCode = $request->input('warehouse');
        $vehicleType = $request->input('vehicle_type');
        
        // Get aggregated commission data by user
        $query = DB::table('delivery_records')
            ->join('users', 'delivery_records.user_id', '=', 'users.id')
            ->leftJoin('warehouses', 'users.warehouse_code', '=', 'warehouses.code')
            ->select(
                'users.id',
                'users.first_name',
                'users.last_name',
                'users.email',
                'users.role',
                'users.warehouse_code',
                'warehouses.name as warehouse_name',
                DB::raw('COUNT(delivery_records.id) as delivery_count'),
                DB::raw('SUM(delivery_records.parcel_count) as total_parcels'),
                DB::raw('SUM(delivery_records.commission_amount) as total_commission')
            )
            ->whereBetween('delivery_date', [$startDate, $endDate])
            ->groupBy('users.id', 'users.first_name', 'users.last_name', 'users.email', 
                     'users.role', 'users.warehouse_code', 'warehouses.name');
        
        if ($warehouseCode) {
            $query->where('users.warehouse_code', $warehouseCode);
        }
        
        if ($vehicleType) {
            $query->where('users.role', $vehicleType);
        }
        
        $commissions = $query->orderByDesc('total_commission')->get();
        
        $filename = 'commission_report_' . date('Y-m-d_H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function() use ($commissions, $startDate, $endDate) {
            $file = fopen('php://output', 'w');
            
            // UTF-8 BOM
            fwrite($file, "\xEF\xBB\xBF");
            
            // Report header
            fputcsv($file, ['รายงานค่าคอมมิชชั่น']);
            fputcsv($file, ['ระหว่างวันที่', date('d/m/Y', strtotime($startDate)), 'ถึง', date('d/m/Y', strtotime($endDate))]);
            fputcsv($file, []); // Empty line
            
            // Table headers
            fputcsv($file, [
                'ชื่อ-นามสกุล',
                'อีเมล',
                'ประเภทรถ',
                'คลังสินค้า',
                'จำนวนครั้งที่ส่ง',
                'จำนวนพัสดุทั้งหมด',
                'ค่าคอมมิชชั่นรวม (บาท)',
            ]);

            // Data rows
            foreach ($commissions as $commission) {
                fputcsv($file, [
                    $commission->first_name . ' ' . $commission->last_name,
                    $commission->email,
                    $commission->role === '2wheel' ? 'รถ 2 ล้อ' : 'รถ 4 ล้อ',
                    $commission->warehouse_code . ' - ' . $commission->warehouse_name,
                    number_format($commission->delivery_count),
                    number_format($commission->total_parcels),
                    number_format($commission->total_commission, 2),
                ]);
            }
            
            // Summary
            fputcsv($file, []); // Empty line
            fputcsv($file, [
                'รวมทั้งหมด',
                '',
                '',
                '',
                number_format($commissions->sum('delivery_count')),
                number_format($commissions->sum('total_parcels')),
                number_format($commissions->sum('total_commission'), 2),
            ]);

            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
    
    /**
     * Export warehouse report
     */
    public function exportWarehouseReport(Request $request)
    {
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth()->format('Y-m-d'));
        
        // Get warehouse data
        $warehouses = DB::table('warehouses')
            ->leftJoin('users', 'warehouses.code', '=', 'users.warehouse_code')
            ->leftJoin('delivery_records', function ($join) use ($startDate, $endDate) {
                $join->on('users.id', '=', 'delivery_records.user_id')
                     ->whereBetween('delivery_records.delivery_date', [$startDate, $endDate]);
            })
            ->select(
                'warehouses.code',
                'warehouses.name',
                'warehouses.location',
                DB::raw('COUNT(DISTINCT users.id) as total_users'),
                DB::raw('COUNT(DISTINCT CASE WHEN users.role = "2wheel" THEN users.id END) as users_2wheel'),
                DB::raw('COUNT(DISTINCT CASE WHEN users.role = "4wheel" THEN users.id END) as users_4wheel'),
                DB::raw('COUNT(delivery_records.id) as total_deliveries'),
                DB::raw('SUM(delivery_records.parcel_count) as total_parcels'),
                DB::raw('SUM(delivery_records.commission_amount) as total_commission')
            )
            ->groupBy('warehouses.code', 'warehouses.name', 'warehouses.location')
            ->orderBy('warehouses.code')
            ->get();
        
        $filename = 'warehouse_report_' . date('Y-m-d_H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function() use ($warehouses, $startDate, $endDate) {
            $file = fopen('php://output', 'w');
            
            // UTF-8 BOM
            fwrite($file, "\xEF\xBB\xBF");
            
            // Report header
            fputcsv($file, ['รายงานประสิทธิภาพคลังสินค้า']);
            fputcsv($file, ['ระหว่างวันที่', date('d/m/Y', strtotime($startDate)), 'ถึง', date('d/m/Y', strtotime($endDate))]);
            fputcsv($file, []); // Empty line
            
            // Table headers
            fputcsv($file, [
                'รหัสคลัง',
                'ชื่อคลัง',
                'ที่อยู่',
                'จำนวนพนักงานทั้งหมด',
                'รถ 2 ล้อ',
                'รถ 4 ล้อ',
                'จำนวนครั้งที่ส่ง',
                'จำนวนพัสดุ',
                'ค่าคอมมิชชั่นรวม (บาท)',
            ]);

            // Data rows
            foreach ($warehouses as $warehouse) {
                fputcsv($file, [
                    $warehouse->code,
                    $warehouse->name,
                    $warehouse->location ?? '-',
                    number_format($warehouse->total_users),
                    number_format($warehouse->users_2wheel),
                    number_format($warehouse->users_4wheel),
                    number_format($warehouse->total_deliveries ?? 0),
                    number_format($warehouse->total_parcels ?? 0),
                    number_format($warehouse->total_commission ?? 0, 2),
                ]);
            }
            
            // Summary
            fputcsv($file, []); // Empty line
            fputcsv($file, [
                'รวมทั้งหมด',
                '',
                '',
                number_format($warehouses->sum('total_users')),
                number_format($warehouses->sum('users_2wheel')),
                number_format($warehouses->sum('users_4wheel')),
                number_format($warehouses->sum('total_deliveries')),
                number_format($warehouses->sum('total_parcels')),
                number_format($warehouses->sum('total_commission'), 2),
            ]);

            fclose($file);
        };

        return Response::stream($callback, 200, $headers);
    }
}