<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class CommissionController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('seller');
    }

    /**
     * Display a listing of seller commissions.
     */
    public function index()
    {
        $seller = Auth::user();
        
        // Récupérer les commissions du vendeur
        $commissions = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        // Calculer les montants
        $monthly_commissions = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('amount');
        
        $yearly_commissions = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->whereYear('created_at', now()->year)
            ->sum('amount');
        
        $total_commissions = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->sum('amount');
        
        // Calculer le taux moyen
        $average_rate = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->avg('rate') ?? 0;
        
        return view('seller.commissions', [
            'commissions' => $commissions,
            'monthly_commissions' => $monthly_commissions,
            'yearly_commissions' => $yearly_commissions,
            'total_commissions' => $total_commissions,
            'average_rate' => number_format($average_rate, 2),
        ]);
    }

    /**
     * Export commissions to CSV.
     */
    public function export()
    {
        $seller = Auth::user();
        
        $commissions = DB::table('commissions')
            ->where('seller_id', $seller->id)
            ->orderBy('created_at', 'desc')
            ->get();
        
        $filename = 'commissions_' . date('Y-m-d_H-i-s') . '.csv';
        $handle = fopen('php://memory', 'r+');
        
        // Header
        fputcsv($handle, ['Date', 'Montant', 'Taux', 'Produit', 'Statut']);
        
        foreach ($commissions as $commission) {
            fputcsv($handle, [
                $commission->created_at,
                $commission->amount,
                $commission->rate,
                $commission->product_id ?? 'N/A',
                $commission->status ?? 'paid',
            ]);
        }
        
        rewind($handle);
        $csv = stream_get_contents($handle);
        fclose($handle);
        
        return response($csv, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ]);
    }
}
