<?php

namespace App\Http\Controllers\API\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant\Sale;
use App\Models\Tenant\SaleItem;
use App\Models\Tenant\ProductVariant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SaleController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'items' => 'required|array',
            'items.*.variant_id' => 'required|exists:product_variants,id',
            'items.*.quantity' => 'required|numeric|min:0.01',
        ]);

        try {
            DB::beginTransaction();

            // Calculate total
            $total = 0;
            $itemsToCreate = [];

            foreach ($validated['items'] as $item) {
                $variant = ProductVariant::findOrFail($item['variant_id']);
                $price = $variant->price;
                $lineTotal = $price * $item['quantity'];
                $total += $lineTotal;

                $itemsToCreate[] = [
                    'variant_id' => $variant->id,
                    'quantity' => $item['quantity'],
                    'price' => $price,
                    'total' => $lineTotal,
                ];
            }

            $sale = Sale::create([
                'total' => $total,
                'status' => 'completed',
                'payment_status' => 'paid', // Simplification for POS
            ]);

            $sale->items()->createMany($itemsToCreate);

            DB::commit();

            return response()->json($sale->load('items'), 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Sale failed: ' . $e->getMessage()], 500);
        }
    }
}
