<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DeliveryNote;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class DeliveryNoteController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            // Créer la colonne status si elle n'existe pas
            $this->ensureStatusColumn();
            
            $query = DeliveryNote::query();
            
            // Ajouter les relations seulement si les tables existent
            try {
                $query->with(['items']);
                if (\Schema::hasTable('clients')) {
                    $query->with(['client']);
                }
                if (\Schema::hasTable('users')) {
                    $query->with(['user']);
                }
            } catch (\Exception $e) {
                // Ignorer les erreurs de relations
            }

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

            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function($q) use ($search) {
                    $q->where('number', 'like', "%{$search}%")
                      ->orWhereHas('client', function($clientQuery) use ($search) {
                          $clientQuery->where('name', 'like', "%{$search}%");
                      });
                });
            }

            $deliveryNotes = $query->orderBy('created_at', 'desc')
                                 ->paginate($request->get('per_page', 15));
            
            \Log::info('Delivery notes query result: ' . $deliveryNotes->count() . ' items');
            return response()->json($deliveryNotes);
        } catch (\Exception $e) {
            \Log::error('Erreur chargement bons de livraison: ' . $e->getMessage());
            return response()->json(['error' => 'Erreur lors du chargement des bons de livraison'], 500);
        }
    }
    
    private function ensureStatusColumn()
    {
        try {
            // Table delivery_notes
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS number VARCHAR(255)");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS status VARCHAR(50) DEFAULT 'draft'");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS client_id INTEGER REFERENCES clients(id)");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS user_id INTEGER REFERENCES users(id)");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS date DATE DEFAULT CURRENT_DATE");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS subtotal_ht DECIMAL(10,2) DEFAULT 0");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS total_vat DECIMAL(10,2) DEFAULT 0");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS total_ttc DECIMAL(10,2) DEFAULT 0");
            \DB::statement("ALTER TABLE delivery_notes ADD COLUMN IF NOT EXISTS notes TEXT");
            
            // Créer la table delivery_note_items si elle n'existe pas
            \DB::statement("
                CREATE TABLE IF NOT EXISTS delivery_note_items (
                    id SERIAL PRIMARY KEY,
                    delivery_note_id INTEGER REFERENCES delivery_notes(id) ON DELETE CASCADE,
                    product_id INTEGER REFERENCES products(id),
                    product_name VARCHAR(255),
                    quantity DECIMAL(10,3),
                    unit VARCHAR(50),
                    unit_price DECIMAL(10,2),
                    vat_rate DECIMAL(5,2),
                    total_ht DECIMAL(10,2),
                    total_vat DECIMAL(10,2),
                    total_ttc DECIMAL(10,2),
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ");
        } catch (\Exception $e) {
            // Ignorer les erreurs si les tables/colonnes existent déjà
        }
    }

    public function store(Request $request): JsonResponse
    {
        try {
            // Créer les tables/colonnes manquantes si nécessaire
            $this->ensureStatusColumn();
            
            $validated = $request->validate([
            'client_id' => 'required|exists:clients,id',
            'date' => 'required|date',
            'notes' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|numeric|min:0.01',
            'items.*.unit_price' => 'required|numeric|min:0',
        ]);

        $deliveryNote = DeliveryNote::create([
            'number' => 'BL-' . date('Y') . '-' . str_pad(DeliveryNote::count() + 1, 4, '0', STR_PAD_LEFT),
            'client_id' => $validated['client_id'],
            'user_id' => auth()->id(),
            'date' => $validated['date'],
            'status' => 'draft',
            'notes' => $validated['notes'] ?? null,
        ]);

        $subtotal = 0;
        $totalVat = 0;

        foreach ($validated['items'] as $item) {
            $product = \App\Models\Product::find($item['product_id']);
            
            $totalHt = $item['quantity'] * $item['unit_price'];
            $vat = $totalHt * ($product->vat_rate / 100);
            $totalTtc = $totalHt + $vat;

            $deliveryNote->items()->create([
                'product_id' => $item['product_id'],
                'product_name' => $product->name,
                'quantity' => $item['quantity'],
                'unit' => $product->unit,
                'unit_price' => $item['unit_price'],
                'vat_rate' => $product->vat_rate,
                'total_ht' => $totalHt,
                'total_vat' => $vat,
                'total_ttc' => $totalTtc,
            ]);

            // Créer le mouvement de stock
            StockMovement::create([
                'product_id' => $item['product_id'],
                'user_id' => auth()->id(),
                'type' => 'out',
                'reason' => 'sale',
                'quantity' => $item['quantity'],
                'previous_stock' => $product->current_stock,
                'new_stock' => $product->current_stock - $item['quantity'],
                'reference' => $deliveryNote->number,
                'notes' => 'Bon de livraison',
                'movable_type' => 'App\\Models\\DeliveryNote',
                'movable_id' => $deliveryNote->id,
            ]);

            // Mettre à jour le stock
            $product->decrement('current_stock', $item['quantity']);

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

        $deliveryNote->update([
            'subtotal_ht' => $subtotal,
            'total_vat' => $totalVat,
            'total_ttc' => $subtotal + $totalVat,
        ]);

            return response()->json($deliveryNote->load('items.product'), 201);
        } catch (\Exception $e) {
            \Log::error('Erreur sauvegarde bon de livraison: ' . $e->getMessage());
            return response()->json(['error' => 'Erreur lors de la sauvegarde du bon de livraison'], 500);
        }
    }

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

    public function update(Request $request, DeliveryNote $deliveryNote): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'in:draft,sent,delivered,cancelled',
            'notes' => 'nullable|string',
        ]);

        $deliveryNote->update($validated);
        return response()->json($deliveryNote->load(['client', 'items.product']));
    }

    public function destroy(DeliveryNote $deliveryNote): JsonResponse
    {
        // Restaurer le stock si le bon n'est pas encore livré
        if (!isset($deliveryNote->status) || $deliveryNote->status !== 'delivered') {
            foreach ($deliveryNote->items as $item) {
                $product = $item->product;
                if ($product) {
                    $product->increment('current_stock', $item->quantity);
                    
                    // Supprimer le mouvement de stock correspondant
                    StockMovement::where('reference', $deliveryNote->number)
                                ->where('product_id', $item->product_id)
                                ->delete();
                }
            }
        }

        $deliveryNote->delete();
        return response()->json(['message' => 'Bon de livraison supprimé avec succès']);
    }

    public function generatePdf(DeliveryNote $deliveryNote)
    {
        $deliveryNote->load(['client', 'items.product', 'user']);
        $company = \App\Models\Company::first();
        
        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('delivery-notes.pdf', compact('deliveryNote', 'company'));
        
        return $pdf->download('bon-livraison-' . $deliveryNote->number . '.pdf');
    }

    public function updateStatus(Request $request, DeliveryNote $deliveryNote): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|in:draft,sent,delivered,cancelled',
        ]);

        $deliveryNote->update(['status' => $validated['status']]);
        
        $statusMessages = [
            'draft' => 'Bon de livraison remis en brouillon',
            'sent' => 'Bon de livraison marqué comme envoyé',
            'delivered' => 'Bon de livraison marqué comme livré',
            'cancelled' => 'Bon de livraison annulé',
        ];

        return response()->json([
            'message' => $statusMessages[$validated['status']],
            'deliveryNote' => $deliveryNote->load(['client', 'items'])
        ]);
    }
}