<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Sale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class BusinessSaleController extends Controller
{
    public function index()
    {
        $sales = Auth::guard('business')->user()->sales()->with('product')->latest('date')->get();

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

    public function create()
    {
        $products = Auth::guard('business')->user()->products()->where('quantity', '>', 0)->get();

        return Inertia::render('Business/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;
        $profit = ($product->selling_price - $product->cost_price) * $request->quantity;

        $sale = Auth::guard('business')->user()->sales()->create([
            'product_id' => $request->product_id,
            'quantity' => $request->quantity,
            'total_amount' => $total,
            'profit' => $profit,
            'date' => today(),
        ]);

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

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