<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Load;
use App\Models\Bill;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\FinancialReportExport;
use App\Exports\LoadReportExport;
use App\Exports\DriverReportExport;

class ReportController extends Controller
{
    /**
     * Display report dashboard
     */
    public function index(Request $request)
    {
        try {
            $today = Carbon::today();
            $thisMonth = Carbon::now()->startOfMonth();
            $lastMonth = Carbon::now()->subMonth()->startOfMonth();

            // Quick statistics
            $stats = [
                'today' => [
                    'loads' => Load::whereDate('created_at', $today)->count(),
                    'revenue' => Load::whereDate('created_at', $today)
                        ->where('status', 'delivered')
                        ->sum('price'),
                ],
                'this_month' => [
                    'loads' => Load::whereDate('created_at', '>=', $thisMonth)->count(),
                    'revenue' => Load::whereDate('created_at', '>=', $thisMonth)
                        ->where('status', 'delivered')
                        ->sum('price'),
                ],
                'last_month' => [
                    'loads' => Load::whereBetween('created_at', [
                        $lastMonth,
                        $lastMonth->copy()->endOfMonth()
                    ])->count(),
                    'revenue' => Load::whereBetween('created_at', [
                        $lastMonth,
                        $lastMonth->copy()->endOfMonth()
                    ])->where('status', 'delivered')->sum('price'),
                ],
            ];

            return response()->json([
                'success' => true,
                'message' => 'آمار گزارشات با موفقیت دریافت شد',
                'data' => $stats,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت آمار',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Generate financial report
     */
    public function financial(Request $request)
    {
        try {
            $query = Load::with(['requester:id,name', 'driver:id,name', 'bill']);

            // Date range filter
            if ($request->has('start_date') && $request->start_date) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if ($request->has('end_date') && $request->end_date) {
                $query->whereDate('created_at', '<=', $request->end_date);
            } else {
                // Default to current month
                $query->whereDate('created_at', '>=', Carbon::now()->startOfMonth());
            }

            // Status filter
            if ($request->has('status') && $request->status) {
                $query->where('status', $request->status);
            }

            // Get data
            $loads = $query->orderBy('created_at', 'desc')->get();

            // Calculate totals
            $totalRevenue = $loads->where('status', 'delivered')->sum('price');
            $pendingRevenue = $loads->whereIn('status', ['approved', 'in_transit'])->sum('price');
            $totalLoads = $loads->count();
            $deliveredLoads = $loads->where('status', 'delivered')->count();

            // Group by status
            $byStatus = $loads->groupBy('status')->map(function($items, $status) {
                return [
                    'count' => $items->count(),
                    'total_price' => $items->sum('price'),
                ];
            });

            // Daily revenue (for chart)
            $dailyRevenue = [];
            $startDate = $request->start_date ? Carbon::parse($request->start_date) : Carbon::now()->startOfMonth();
            $endDate = $request->end_date ? Carbon::parse($request->end_date) : Carbon::now();

            $currentDate = $startDate->copy();
            while ($currentDate <= $endDate) {
                $dayRevenue = $loads->where('status', 'delivered')
                    ->filter(function($load) use ($currentDate) {
                        return Carbon::parse($load->created_at)->isSameDay($currentDate);
                    })
                    ->sum('price');

                $dailyRevenue[] = [
                    'date' => $currentDate->format('Y-m-d'),
                    'date_name' => $currentDate->locale('fa')->isoFormat('D MMMM'),
                    'revenue' => (float) $dayRevenue,
                ];

                $currentDate->addDay();
            }

            // Top requesters
            $topRequesters = $loads->groupBy('requester_id')
                ->map(function($items) {
                    return [
                        'requester' => $items->first()->requester,
                        'total_loads' => $items->count(),
                        'total_spent' => $items->where('status', 'delivered')->sum('price'),
                    ];
                })
                ->sortByDesc('total_spent')
                ->values()
                ->take(10);

            // Top drivers
            $topDrivers = $loads->where('driver_id', '!=', null)
                ->groupBy('driver_id')
                ->map(function($items) {
                    return [
                        'driver' => $items->first()->driver,
                        'total_loads' => $items->count(),
                        'completed_loads' => $items->where('status', 'delivered')->count(),
                        'total_revenue' => $items->where('status', 'delivered')->sum('price'),
                    ];
                })
                ->sortByDesc('total_revenue')
                ->values()
                ->take(10);

            return response()->json([
                'success' => true,
                'message' => 'گزارش مالی با موفقیت ایجاد شد',
                'data' => [
                    'summary' => [
                        'total_revenue' => (float) $totalRevenue,
                        'pending_revenue' => (float) $pendingRevenue,
                        'total_loads' => $totalLoads,
                        'delivered_loads' => $deliveredLoads,
                        'delivery_rate' => $totalLoads > 0 ? round(($deliveredLoads / $totalLoads) * 100, 2) : 0,
                    ],
                    'by_status' => $byStatus,
                    'daily_revenue' => $dailyRevenue,
                    'top_requesters' => $topRequesters,
                    'top_drivers' => $topDrivers,
                    'loads' => $loads,
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد گزارش مالی',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Generate loads report
     */
    public function loads(Request $request)
    {
        try {
            $query = Load::with(['requester:id,name,phone', 'driver:id,name,phone', 'bill']);

            // Date range filter
            if ($request->has('start_date') && $request->start_date) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if ($request->has('end_date') && $request->end_date) {
                $query->whereDate('created_at', '<=', $request->end_date);
            }

            // Status filter
            if ($request->has('status') && $request->status) {
                $query->where('status', $request->status);
            }

            // Requester filter
            if ($request->has('requester_id') && $request->requester_id) {
                $query->where('requester_id', $request->requester_id);
            }

            // Driver filter
            if ($request->has('driver_id') && $request->driver_id) {
                $query->where('driver_id', $request->driver_id);
            }

            $loads = $query->orderBy('created_at', 'desc')->get();

            // Statistics
            $stats = [
                'total' => $loads->count(),
                'by_status' => $loads->groupBy('status')->map->count(),
                'total_weight' => $loads->sum('weight'),
                'total_value' => $loads->sum('price'),
                'avg_price' => $loads->avg('price'),
                'avg_weight' => $loads->avg('weight'),
            ];

            return response()->json([
                'success' => true,
                'message' => 'گزارش بارها با موفقیت ایجاد شد',
                'data' => [
                    'statistics' => $stats,
                    'loads' => $loads,
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد گزارش بارها',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Generate driver performance report
     */
    public function drivers(Request $request)
    {
        try {
            $query = User::where('role', 'driver')
                ->with(['driverLoads' => function($q) use ($request) {
                    if ($request->has('start_date') && $request->start_date) {
                        $q->whereDate('created_at', '>=', $request->start_date);
                    }
                    if ($request->has('end_date') && $request->end_date) {
                        $q->whereDate('created_at', '<=', $request->end_date);
                    }
                }])
                ->withCount([
                    'driverLoads as total_loads' => function($q) use ($request) {
                        if ($request->has('start_date') && $request->start_date) {
                            $q->whereDate('created_at', '>=', $request->start_date);
                        }
                        if ($request->has('end_date') && $request->end_date) {
                            $q->whereDate('created_at', '<=', $request->end_date);
                        }
                    },
                    'driverLoads as completed_loads' => function($q) use ($request) {
                        $q->where('status', 'delivered');
                        if ($request->has('start_date') && $request->start_date) {
                            $q->whereDate('created_at', '>=', $request->start_date);
                        }
                        if ($request->has('end_date') && $request->end_date) {
                            $q->whereDate('created_at', '<=', $request->end_date);
                        }
                    },
                    'driverLoads as cancelled_loads' => function($q) use ($request) {
                        $q->where('status', 'cancelled');
                        if ($request->has('start_date') && $request->start_date) {
                            $q->whereDate('created_at', '>=', $request->start_date);
                        }
                        if ($request->has('end_date') && $request->end_date) {
                            $q->whereDate('created_at', '<=', $request->end_date);
                        }
                    },
                ]);

            $drivers = $query->get()->map(function($driver) {
                $revenue = $driver->driverLoads->where('status', 'delivered')->sum('price');
                $totalLoads = $driver->total_loads;
                $completedLoads = $driver->completed_loads;

                return [
                    'id' => $driver->id,
                    'name' => $driver->name,
                    'phone' => $driver->phone,
                    'is_active' => $driver->is_active,
                    'total_loads' => $totalLoads,
                    'completed_loads' => $completedLoads,
                    'cancelled_loads' => $driver->cancelled_loads,
                    'in_progress_loads' => $totalLoads - $completedLoads - $driver->cancelled_loads,
                    'completion_rate' => $totalLoads > 0 ? round(($completedLoads / $totalLoads) * 100, 2) : 0,
                    'total_revenue' => (float) $revenue,
                ];
            });

            // Sort by total revenue
            $drivers = $drivers->sortByDesc('total_revenue')->values();

            return response()->json([
                'success' => true,
                'message' => 'گزارش عملکرد رانندگان با موفقیت ایجاد شد',
                'data' => [
                    'drivers' => $drivers,
                    'summary' => [
                        'total_drivers' => $drivers->count(),
                        'active_drivers' => $drivers->where('is_active', true)->count(),
                        'total_revenue' => $drivers->sum('total_revenue'),
                        'total_loads' => $drivers->sum('total_loads'),
                        'completed_loads' => $drivers->sum('completed_loads'),
                    ],
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد گزارش رانندگان',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Export financial report to Excel
     */
    public function exportExcel(Request $request)
    {
        try {
            $reportType = $request->get('type', 'financial');

            switch ($reportType) {
                case 'financial':
                    return $this->exportFinancialReport($request);
                case 'loads':
                    return $this->exportLoadsReport($request);
                case 'drivers':
                    return $this->exportDriversReport($request);
                default:
                    return response()->json([
                        'success' => false,
                        'message' => 'نوع گزارش نامعتبر است',
                    ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در خروجی اکسل',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Export financial report
     */
    private function exportFinancialReport(Request $request)
    {
        $query = Load::with(['requester:id,name', 'driver:id,name', 'bill']);

        if ($request->has('start_date') && $request->start_date) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }

        if ($request->has('end_date') && $request->end_date) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        $loads = $query->orderBy('created_at', 'desc')->get();

        $filename = 'financial_report_' . date('Y-m-d_His') . '.xlsx';

        // Note: You need to create these Export classes
        // return Excel::download(new FinancialReportExport($loads), $filename);

        // For now, return JSON response with download instructions
        return response()->json([
            'success' => true,
            'message' => 'برای دانلود فایل اکسل، باید کلاس Export ایجاد شود',
            'data' => [
                'filename' => $filename,
                'records' => $loads->count(),
                'instructions' => 'لطفا کلاس FinancialReportExport را در app/Exports ایجاد کنید',
            ],
        ], 200);
    }

    /**
     * Export loads report
     */
    private function exportLoadsReport(Request $request)
    {
        // Similar implementation
        return response()->json([
            'success' => true,
            'message' => 'برای دانلود فایل اکسل، باید کلاس Export ایجاد شود',
        ], 200);
    }

    /**
     * Export drivers report
     */
    private function exportDriversReport(Request $request)
    {
        // Similar implementation
        return response()->json([
            'success' => true,
            'message' => 'برای دانلود فایل اکسل، باید کلاس Export ایجاد شود',
        ], 200);
    }
}
