<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Price;
use App\Models\Sale;
use App\Models\SaleItem;
use Illuminate\Http\Request;

class SaleController extends Controller
{
    public function index()
    {
        $sales = Sale::latest()->get();
        return view('sales.index', compact('sales'));
    }

    public function create()
    {
        $products = \App\Models\Product::all();

        foreach ($products as $p) {
            $price = \App\Models\Price::where('product_id', $p->id)
                // ->whereDate('date_price', today())
                ->latest()
                ->first();

            $p->sell_price = $price ? $price->price : 0;
        }

        return view('sales.create', compact('products'));
    }

    public function store(Request $request)
    {
        $cart = $request->cart;

        $diskon = (int)$request->diskon;
        $bayar = (int)$request->bayar;

        $subtotal = 0;

        foreach ($cart as $id => $item) {

            $subtotal += $item['qty'] * $item['harga'];
        }

        $grandTotal = $subtotal - $diskon;

        $kembali = $bayar - $grandTotal;

        $sale = Sale::create([
            'date_sale' => now(),
            'subtotal' => $subtotal,
            'discount' => $diskon,
            'pay' => $bayar,
            'change' => $kembali,
            'total' => $grandTotal
        ]);

        foreach ($cart as $id => $item) {

            $product = Product::find($id);

            $sub = $item['qty'] * $item['harga'];

            SaleItem::create([
                'sale_id' => $sale->id,
                'product_id' => $id,
                'qty' => $item['qty'],
                'price' => $item['harga'],
                'subtotal' => $sub
            ]);

            // Kurangi stok
            $product->stock -= $item['qty'];
            $product->save();
        }

        return response()->json([
            'status' => 'success',
            'sale_id' => $sale->id
        ]);
    }

    public function receipt($id)
    {
        $sale = \App\Models\Sale::with('items.product')->findOrFail($id);

        return view('sales.receipt', compact('sale'));
    }
}
