<?php

namespace App\Http\Controllers;

use App\Models\ProductsWholesale;
use Illuminate\Http\Request;

class ProductsWholesaleController extends Controller
{
    // GET data berdasarkan product_id
    public function index($product_id)
    {
        $data = ProductsWholesale::with('product.unit', 'multiunit.multi_unit')->where('product_id', $product_id)->get();

        $response = [
            'status' => true,
            'data' => $data
        ];

        return response($response, 200);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id'     => 'required|integer',
            'multi_unit_id'  => 'required|array',
            'multi_unit_id.*' => 'nullable|integer',
            'min_qty'        => 'required|array',
            'min_qty.*'      => 'required|numeric|min:1',
            'max_qty'        => 'required|array',
            'max_qty.*'      => 'nullable|numeric|min:1',
            'price'          => 'required|array',
            'price.*'        => 'required|numeric|min:0'
        ]);

        try {
            $data = $request->multi_unit_id;
            $wholesales = [];

            foreach ($data as $key => $value) {
                // Validasi tambahan untuk setiap item
                if (
                    isset($request->max_qty[$key]) &&
                    $request->max_qty[$key] !== null &&
                    $request->max_qty[$key] < $request->min_qty[$key]
                ) {
                    throw new \Exception("Max qty tidak boleh kurang dari min qty pada baris " . ($key + 1));
                }

                // Cek duplikasi
                $existing = ProductsWholesale::where('product_id', $request->product_id)
                    ->where('multi_unit_id', $request->multi_unit_id[$key])
                    ->where('min_qty', $request->min_qty[$key])
                    ->first();

                if ($existing) {
                    throw new \Exception("Kombinasi unit dan min qty sudah ada pada baris " . ($key + 1));
                }

                $wholesale = new ProductsWholesale();
                $wholesale->product_id = $request->product_id;
                $wholesale->multi_unit_id = $request->multi_unit_id[$key];
                $wholesale->min_qty = $request->min_qty[$key];
                $wholesale->max_qty = $request->max_qty[$key];
                $wholesale->price = $request->price[$key];

                $wholesale->save();
                $wholesales[] = $wholesale;
            }

            $response = [
                'status' => true,
                'message' => 'Harga grosir berhasil dibuat',
                'data' => $wholesales
            ];

            return response($response, 201);
        } catch (\Exception $e) {
            return response([
                'status' => false,
                'message' => $e->getMessage()
            ], 422);
        }
    }

    public function update(Request $request)
    {
        $request->validate([
            'product_id'     => 'required|integer',
            'multi_unit_id'  => 'required|array',
            'multi_unit_id.*' => 'nullable|integer',
            'min_qty'        => 'required|array',
            'min_qty.*'      => 'required|numeric|min:1',
            'max_qty'        => 'required|array',
            'max_qty.*'      => 'nullable|numeric|min:1',
            'price'          => 'required|array',
            'price.*'        => 'required|numeric|min:0'
        ]);

        try {
            // Hapus semua wholesale data lama untuk produk ini
            ProductsWholesale::where('product_id', $request->product_id)->delete();

            $data = $request->multi_unit_id;
            $wholesales = [];

            foreach ($data as $key => $value) {
                // Validasi tambahan untuk setiap item
                if (
                    isset($request->max_qty[$key]) &&
                    $request->max_qty[$key] !== null &&
                    $request->max_qty[$key] < $request->min_qty[$key]
                ) {
                    throw new \Exception("Max qty tidak boleh kurang dari min qty pada baris " . ($key + 1));
                }

                $wholesale = new ProductsWholesale();
                $wholesale->product_id = $request->product_id;
                $wholesale->multi_unit_id = $request->multi_unit_id[$key] ?? null;
                $wholesale->min_qty = $request->min_qty[$key];
                $wholesale->max_qty = $request->max_qty[$key];
                $wholesale->price = $request->price[$key];

                $wholesale->save();
                $wholesales[] = $wholesale;
            }

            $response = [
                'status' => true,
                'message' => 'Harga grosir berhasil diupdate',
                'data' => $wholesales
            ];

            return response($response, 200);
        } catch (\Exception $e) {
            return response([
                'status' => false,
                'message' => $e->getMessage()
            ], 422);
        }
    }

    public function show($productId)
    {
        try {
            $wholesales = ProductsWholesale::with(['product.unit', 'multiunit'])
                ->where('product_id', $productId)
                ->orderBy('min_qty', 'asc')
                ->get();

            $response = [
                'status' => true,
                'data' => $wholesales
            ];

            return response($response, 200);
        } catch (\Exception $e) {
            return response([
                'status' => false,
                'message' => 'Gagal mengambil data wholesale'
            ], 500);
        }
    }

    public function destroy($id)
    {
        $wholesale = ProductsWholesale::find($id);

        if (!$wholesale) {
            return response()->json([
                'status' => false,
                'message' => 'Data not found.'
            ], 404);
        }

        $wholesale->delete();

        $response = [
            'status' => true,
            'message' => 'Wholesale product deleted successfully.'
        ];

        return response($response, 200);
    }
}
