<?php

namespace App\Http\Controllers;

use App\Models\PurchaseOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PurchaseOrderController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'supplier_id' => ['required', 'exists:suppliers,id'],
        ]);

        DB::transaction(function () use ($validated, &$purchaseOrder) {
            $purchaseOrder = PurchaseOrder::create([
                'reference' => PurchaseOrder::generateUniqueReference(),
                'supplier_id' => $validated['supplier_id'],
                'user_id' => Auth::id(),
                'status' => PurchaseOrder::STATUS_DRAFT,
                'order_date' => now(),
            ]);
        });

        return redirect()->route('purchase-orders.edit', $purchaseOrder)->with('success', 'Bon de commande créé avec succès.');
    }

    public function update(Request $request, PurchaseOrder $purchaseOrder)
    {
        if ($purchaseOrder->status !== PurchaseOrder::STATUS_DRAFT) {
            return back()->with('error', 'Vous ne pouvez modifier que les commandes en brouillon.');
        }

        $validated = $request->validate([
            'expected_delivery_date' => ['nullable', 'date'],
            'notes' => ['nullable', 'string'],
        ]);

        $purchaseOrder->update($validated);

        return back()->with('success', 'Bon de commande modifié avec succès.');
    }

    public function activate(PurchaseOrder $purchaseOrder)
    {
        if ($purchaseOrder->status !== PurchaseOrder::STATUS_DRAFT) {
            return back()->with('error', 'Seules les commandes en brouillon peuvent être activées.');
        }

        if ($purchaseOrder->items->isEmpty()) {
            return back()->with('error', 'Vous ne pouvez pas activer une commande sans articles.');
        }

        $purchaseOrder->update([
            'status' => PurchaseOrder::STATUS_ACTIVE,
        ]);

        return redirect()->route('purchase-orders.show', $purchaseOrder)->with('success', 'Bon de commande activé avec succès.');
    }

    public function reactivate(PurchaseOrder $purchaseOrder)
    {
        if ($purchaseOrder->status !== PurchaseOrder::STATUS_CANCELLED) {
            return back()->with('error', 'Seules les commandes annulées peuvent être réactivées.');
        }

        $purchaseOrder->update([
            'status' => PurchaseOrder::STATUS_ACTIVE,
        ]);

        return redirect()->route('purchase-orders.show', $purchaseOrder)->with('success', 'Bon de commande réactivé avec succès.');
    }

    public function cancel(PurchaseOrder $purchaseOrder)
    {
        if ($purchaseOrder->status === PurchaseOrder::STATUS_RECEIVED) {
            return back()->with('error', 'Vous ne pouvez pas annuler une commande déjà reçue.');
        }

        $purchaseOrder->update([
            'status' => PurchaseOrder::STATUS_CANCELLED,
        ]);

        return redirect()->route('purchase-orders.show', $purchaseOrder)->with('success', 'Bon de commande annulé avec succès.');
    }

    public function receive(Request $request, PurchaseOrder $purchaseOrder)
    {
        if ($purchaseOrder->status !== PurchaseOrder::STATUS_ACTIVE) {
            return back()->with('error', 'Seules les commandes actives peuvent être reçues.');
        }

        $validated = $request->validate([
            'items' => ['required', 'array'],
            'items.*.id' => ['required', 'exists:purchase_order_items,id'],
            'items.*.received_quantity' => ['required', 'integer', 'min:0'],
        ]);

        DB::transaction(function () use ($purchaseOrder, $validated) {
            foreach ($validated['items'] as $itemData) {
                $item = $purchaseOrder->items()->find($itemData['id']);

                if ($item && $itemData['received_quantity'] > 0) {
                    $item->update(['received_quantity' => $itemData['received_quantity']]);
                    $item->product->increment('current_stock', $itemData['received_quantity']);
                }
            }

            $purchaseOrder->update([
                'status' => PurchaseOrder::STATUS_RECEIVED,
                'received_at' => now(),
                'received_by' => Auth::id(),
            ]);
        });

        return redirect()->route('purchase-orders.show', $purchaseOrder)->with('success', 'Bon de commande reçu avec succès.');
    }

    public function print(PurchaseOrder $purchaseOrder)
    {
        $purchaseOrder->load(['supplier', 'items.product', 'user']);

        return view('livewire.purchase-orders.print', [
            'purchaseOrder' => $purchaseOrder,
        ]);
    }

    public function destroy(PurchaseOrder $purchaseOrder)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas supprimer un bon de commande.');
        }

        if ($purchaseOrder->status === PurchaseOrder::STATUS_RECEIVED) {
            return back()->with('error', 'Vous ne pouvez pas supprimer une commande déjà reçue.');
        }

        $purchaseOrder->delete();

        return redirect()->route('purchase-orders.index')->with('success', 'Bon de commande supprimé avec succès.');
    }
}
