<?php

namespace App\Http\Controllers;

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

class PriceController extends Controller
{
    public function index()
    {
        $prices = Price::with('product')
            ->orderBy('date_price', 'desc')
            ->get()
            ->groupBy('date_price');

        return view('prices.index', compact('prices'));
    }

    public function create()
    {
        $products = Product::all();
        return view('prices.create', compact('products'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'date_price' => 'required'
        ]);

        foreach ($request->prices as $productId => $price) {

            if ($price != null && $price > 0) {

                Price::create([
                    'product_id' => $productId,
                    'date_price' => $request->date_price,
                    'price' => $price
                ]);
            }
        }

        return redirect('/prices')
            ->with('success', 'Harga berhasil disimpan');
    }

    public function destroy(Price $price)
    {
        $price->delete();
        return redirect('/prices');
    }

    public function editDaily($date)
    {
        $prices = Price::with('product')
            ->whereDate('date_price', $date)
            ->get();

        return view(
            'prices.edit-daily',
            compact('prices', 'date')
        );
    }
    public function updateDaily(Request $request)
    {
        foreach ($request->ids as $index => $id) {

            Price::where('id', $id)
                ->update([

                    'price' => $request->prices[$index]

                ]);
        }

        return redirect('/prices')
            ->with(
                'success',
                'Harga harian berhasil diperbarui'
            );
    }
}
