<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\InvoiceExport;

class InvoiceController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Invoice::with(['client', 'supplier', 'user', 'items.product']);

        if ($request->has('type')) {
            $query->where('type', $request->get('type'));
        }

        if ($request->has('status')) {
            $query->where('status', $request->get('status'));
        }

        $invoices = $query->orderBy('created_at', 'desc')
                         ->paginate($request->get('per_page', 15));
        
        return response()->json($invoices);
    }

    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'type' => 'required|in:sale,purchase',
                'client_id' => 'nullable|exists:clients,id',
                'supplier_id' => 'nullable|exists:suppliers,id',
                'date' => 'required|date',
                'due_date' => 'required|date',
                'notes' => 'nullable|string',
                'terms' => 'nullable|string',
                'items' => 'required|array|min:1',
                'items.*.product_name' => 'required|string|max:255',
                'items.*.quantity' => 'required|numeric|min:0.01',
                'items.*.unit_price' => 'required|numeric|min:0',
            ]);

        // Générer un numéro simple
        $invoiceNumber = ($validated['type'] === 'sale' ? 'FAC-' : 'ACH-') . time();

        $invoice = Invoice::create([
            'number' => $invoiceNumber,
            'type' => $validated['type'],
            'client_id' => $validated['client_id'] ?? null,
            'supplier_id' => $validated['supplier_id'] ?? null,
            'user_id' => auth()->id(),
            'date' => $validated['date'],
            'due_date' => $validated['due_date'],
            'notes' => $validated['notes'] ?? null,
            'terms' => $validated['terms'] ?? null,
        ]);

        $subtotal = 0;
        $totalVat = 0;

        foreach ($validated['items'] as $item) {
            $quantity = (float) $item['quantity'];
            $unitPrice = (float) $item['unit_price'];
            $vatRate = 20.0;
            
            $totalHt = $quantity * $unitPrice;
            $vat = $totalHt * 0.2;
            $totalTtc = $totalHt + $vat;

            $invoice->items()->create([
                'product_name' => $item['product_name'],
                'description' => $item['description'] ?? '',
                'quantity' => $quantity,
                'unit' => 'Unité',
                'unit_price' => $unitPrice,
                'vat_rate' => $vatRate,
                'total_ht' => $totalHt,
                'total_vat' => $vat,
                'total_ttc' => $totalTtc,
            ]);

            $subtotal += $totalHt;
            $totalVat += $vat;

            // Pas de gestion de stock pour le moment
        }

        // Calculer les totaux finaux
        $finalTotalTtc = $subtotal + $totalVat;
        
        $invoice->update([
            'subtotal_ht' => round($subtotal, 2),
            'total_vat' => round($totalVat, 2),
            'total_ttc' => round($finalTotalTtc, 2),
            'remaining_amount' => round($finalTotalTtc, 2),
        ]);

        return response()->json($invoice->load('items.product'), 201);
        
        } catch (\Exception $e) {
            \Log::error('Erreur création facture: ' . $e->getMessage());
            return response()->json([
                'error' => 'Erreur lors de la création de la facture',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function show(Invoice $invoice): JsonResponse
    {
        return response()->json($invoice->load(['client', 'supplier', 'user', 'items.product']));
    }

    public function update(Request $request, Invoice $invoice): JsonResponse
    {
        try {
            $validated = $request->validate([
                'client_id' => 'nullable|exists:clients,id',
                'supplier_id' => 'nullable|exists:suppliers,id',
                'date' => 'required|date',
                'due_date' => 'required|date',
                'status' => 'nullable|in:draft,sent,paid,partially_paid,overdue,cancelled',
                'notes' => 'nullable|string',
                'terms' => 'nullable|string',
                'items' => 'required|array|min:1',
                'items.*.product_name' => 'required|string|max:255',
                'items.*.quantity' => 'required|numeric|min:0.01',
                'items.*.unit_price' => 'required|numeric|min:0',
            ]);

            // Mettre à jour les informations de base
            $invoice->update([
                'client_id' => $validated['client_id'] ?? null,
                'supplier_id' => $validated['supplier_id'] ?? null,
                'date' => $validated['date'],
                'due_date' => $validated['due_date'],
                'status' => $validated['status'] ?? $invoice->status,
                'notes' => $validated['notes'] ?? null,
                'terms' => $validated['terms'] ?? null,
            ]);

            // Supprimer les anciens items
            $invoice->items()->delete();

            // Recréer les items
            $subtotal = 0;
            $totalVat = 0;

            foreach ($validated['items'] as $item) {
                $quantity = (float) $item['quantity'];
                $unitPrice = (float) $item['unit_price'];
                $vatRate = 20.0;
                
                $totalHt = $quantity * $unitPrice;
                $vat = $totalHt * 0.2;
                $totalTtc = $totalHt + $vat;

                $invoice->items()->create([
                    'product_name' => $item['product_name'],
                    'description' => $item['description'] ?? '',
                    'quantity' => $quantity,
                    'unit' => 'Unité',
                    'unit_price' => $unitPrice,
                    'vat_rate' => $vatRate,
                    'total_ht' => $totalHt,
                    'total_vat' => $vat,
                    'total_ttc' => $totalTtc,
                ]);

                $subtotal += $totalHt;
                $totalVat += $vat;
            }

            // Recalculer les totaux
            $finalTotalTtc = $subtotal + $totalVat;
            
            $invoice->update([
                'subtotal_ht' => round($subtotal, 2),
                'total_vat' => round($totalVat, 2),
                'total_ttc' => round($finalTotalTtc, 2),
                'remaining_amount' => round($finalTotalTtc - $invoice->paid_amount, 2),
            ]);

            return response()->json($invoice->load(['client', 'supplier', 'items.product']));
            
        } catch (\Exception $e) {
            \Log::error('Erreur modification facture: ' . $e->getMessage());
            return response()->json([
                'error' => 'Erreur lors de la modification de la facture',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy(Invoice $invoice): JsonResponse
    {
        $invoice->delete();
        return response()->json(['message' => 'Facture supprimée avec succès']);
    }

    public function generatePdf(Invoice $invoice)
    {
        $invoice->load(['client', 'supplier', 'items.product', 'user']);
        $company = \App\Models\Company::first();
        
        $pdf = Pdf::loadView('invoices.pdf', compact('invoice', 'company'));
        
        return $pdf->download('facture-' . $invoice->number . '.pdf');
    }

    public function generateExcel(Invoice $invoice)
    {
        return Excel::download(new InvoiceExport($invoice), 'facture-' . $invoice->number . '.xlsx');
    }

    public function recalculateTotals(Invoice $invoice): JsonResponse
    {
        $subtotal = 0;
        $totalVat = 0;

        foreach ($invoice->items as $item) {
            $subtotal += $item->total_ht;
            $totalVat += $item->total_vat;
        }

        $finalTotalTtc = $subtotal + $totalVat;

        $invoice->update([
            'subtotal_ht' => round($subtotal, 2),
            'total_vat' => round($totalVat, 2),
            'total_ttc' => round($finalTotalTtc, 2),
            'remaining_amount' => round($finalTotalTtc - $invoice->paid_amount, 2),
        ]);

        return response()->json([
            'message' => 'Totaux recalculés avec succès',
            'invoice' => $invoice->fresh()->load(['client', 'supplier', 'items.product'])
        ]);
    }

    public function updateStatus(Request $request, Invoice $invoice): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|in:draft,sent,paid,partially_paid,overdue,cancelled',
        ]);

        $invoice->update(['status' => $validated['status']]);
        
        $statusMessages = [
            'draft' => 'Facture remise en brouillon',
            'sent' => 'Facture marquée comme envoyée',
            'paid' => 'Facture marquée comme payée',
            'partially_paid' => 'Facture marquée comme partiellement payée',
            'overdue' => 'Facture marquée en retard',
            'cancelled' => 'Facture annulée',
        ];

        return response()->json([
            'message' => $statusMessages[$validated['status']],
            'invoice' => $invoice->fresh()->load(['client', 'supplier', 'items.product'])
        ]);
    }
}