<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Sale;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SaleController extends Controller
{
    public function index()
    {
        $sales = Sale::with('product')->latest()->get();

        return Inertia::render('Admin/Pages/Sales/Index', [
            'sales' => $sales,
        ]);
    }

    public function create()
    {
        $products = Product::where('quantity', '>', 0)->get();

        return Inertia::render('Admin/Pages/Sales/Create', [
            'products' => $products,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $product = Product::find($request->product_id);

        if ($product->quantity < $request->quantity) {
            return back()->withErrors(['quantity' => 'Not enough stock']);
        }

        $total = $product->selling_price * $request->quantity;

        Sale::create([
            'product_id' => $request->product_id,
            'quantity' => $request->quantity,
            'total' => $total,
            'date' => today(),
        ]);

        // Reduce stock
        $product->decrement('quantity', $request->quantity);

        return redirect()->route('admin.sales.index');
    }
}