<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiReport;
use App\Models\User;
use App\Models\Order;
use App\Models\Commission;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ReportController extends Controller
{
    /**
     * Afficher la liste des rapports
     */
    public function index()
    {
        $reports = AiReport::orderBy('created_at', 'desc')->paginate(20);
        return view('admin.reports.index', compact('reports'));
    }

    /**
     * Afficher le formulaire de génération
     */
    public function create()
    {
        return view('admin.reports.create');
    }

    /**
     * Générer un nouveau rapport
     */
    public function store(Request $request)
    {
        $type = $request->input('type', 'monthly');
        $startDate = $request->input('start_date', now()->startOfMonth());
        $endDate = $request->input('end_date', now()->endOfMonth());

        // Générer les données du rapport
        $data = $this->generateReportData($type, $startDate, $endDate);

        $report = AiReport::create([
            'type' => $type,
            'title' => 'Rapport ' . ucfirst($type) . ' - ' . now()->format('d/m/Y'),
            'data' => $data,
            'status' => 'completed',
            'generated_at' => now(),
        ]);

        return redirect()->route('admin.reports.show', $report)
            ->with('success', 'Rapport généré avec succès.');
    }

    /**
     * Afficher un rapport
     */
    public function show($id)
    {
        $report = AiReport::findOrFail($id);
        return view('admin.reports.show', compact('report'));
    }

    /**
     * Télécharger un rapport
     */
    public function download($id)
    {
        $report = AiReport::findOrFail($id);
        
        $content = json_encode($report->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        $filename = 'rapport_' . $report->type . '_' . $report->created_at->format('Y-m-d') . '.json';

        return response($content)
            ->header('Content-Type', 'application/json')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }

    /**
     * Supprimer un rapport
     */
    public function destroy($id)
    {
        $report = AiReport::findOrFail($id);
        $report->delete();

        return back()->with('success', 'Rapport supprimé.');
    }

    /**
     * Générer les données du rapport
     */
    private function generateReportData(string $type, $startDate, $endDate): array
    {
        $start = Carbon::parse($startDate);
        $end = Carbon::parse($endDate);

        return [
            'period' => [
                'start' => $start->format('Y-m-d'),
                'end' => $end->format('Y-m-d'),
            ],
            'summary' => [
                'total_members' => User::where('role', 'member')->whereBetween('created_at', [$start, $end])->count(),
                'total_orders' => Order::whereBetween('created_at', [$start, $end])->count(),
                'total_sales' => Order::where('status', 'delivered')->whereBetween('created_at', [$start, $end])->sum('total'),
                'total_commissions' => Commission::whereBetween('created_at', [$start, $end])->sum('amount'),
            ],
            'top_products' => Product::withCount(['orderItems' => function($q) use ($start, $end) {
                    $q->whereBetween('created_at', [$start, $end]);
                }])
                ->orderBy('order_items_count', 'desc')
                ->limit(10)
                ->get()
                ->map(fn($p) => ['name' => $p->name, 'sales' => $p->order_items_count])
                ->toArray(),
            'top_members' => User::where('role', 'member')
                ->withCount(['orders' => function($q) use ($start, $end) {
                    $q->whereBetween('created_at', [$start, $end]);
                }])
                ->orderBy('orders_count', 'desc')
                ->limit(10)
                ->get()
                ->map(fn($u) => ['name' => $u->name, 'orders' => $u->orders_count])
                ->toArray(),
            'daily_sales' => Order::where('status', 'delivered')
                ->whereBetween('created_at', [$start, $end])
                ->select(
                    DB::raw('DATE(created_at) as date'),
                    DB::raw('SUM(total) as total'),
                    DB::raw('COUNT(*) as count')
                )
                ->groupBy('date')
                ->orderBy('date')
                ->get()
                ->toArray(),
        ];
    }
}
