<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\SupplierPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PurchaseController extends Controller
{
    public function index()
    {
        $purchases = Purchase::with('supplier')->latest()->paginate(20);
        return view('purchases.index', compact('purchases'));
    }

    public function create()
    {
        $suppliers = Supplier::orderBy('name')->get();
        $categories = \App\Models\Category::orderBy('name')->get();
        $products = Product::with('weight')->orderBy('category_id')->orderBy('weight_id')->get();
        return view('purchases.form', compact('suppliers', 'categories', 'products'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'date' => 'required|date',
            'paid_amount' => 'nullable|numeric|min:0',
            'notes' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.bags' => 'required|integer|min:1',
            'items.*.price_per_bag' => 'required|numeric|min:0',
        ]);

        DB::transaction(function () use ($validated) {
            $totalAmount = 0;
            $items = [];

            foreach ($validated['items'] as $item) {
                $subtotal = $item['bags'] * $item['price_per_bag'];
                $totalAmount += $subtotal;
                $items[] = array_merge($item, ['subtotal' => $subtotal]);
            }

            $paidAmount = $validated['paid_amount'] ?? 0;

            $purchase = Purchase::create([
                'supplier_id' => $validated['supplier_id'],
                'date' => $validated['date'],
                'total_amount' => $totalAmount,
                'paid_amount' => $paidAmount,
                'notes' => $validated['notes'] ?? null,
            ]);

            foreach ($items as $item) {
                $purchase->items()->create($item);
                // Add stock
                Product::where('id', $item['product_id'])->increment('stock', $item['bags']);
            }

            // Record payment if paid
            if ($paidAmount > 0) {
                SupplierPayment::create([
                    'supplier_id' => $validated['supplier_id'],
                    'purchase_id' => $purchase->id,
                    'amount' => $paidAmount,
                    'date' => $validated['date'],
                    'notes' => 'Payment with purchase #' . $purchase->id,
                ]);
            }

            // Recalculate supplier balance
            $supplier = Supplier::find($validated['supplier_id']);
            $supplier->recalculateBalance();
        });

        return redirect()->route('purchases.index')->with('success', 'Purchase recorded.');
    }

    public function show(Purchase $purchase)
    {
        $purchase->load(['supplier', 'items.product.category', 'items.product.weight', 'payments']);
        return view('purchases.show', compact('purchase'));
    }
}
