<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BulkPricing;
use App\Models\Product;
use Illuminate\Http\Request;

class BulkPricingController extends Controller
{
    public function index()
    {
        $bulkPricings = BulkPricing::with('product')->latest()->paginate(10);
        return view('admin.bulk-pricing.index', compact('bulkPricings'));
    }

    public function create()
    {
        $products = Product::where('is_active', true)->get();
        return view('admin.bulk-pricing.create', compact('products'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'min_quantity' => 'required|integer|min:1',
            'max_quantity' => 'nullable|integer|min:1|gte:min_quantity',
            'price' => 'nullable|numeric|min:0',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
            'is_active' => 'nullable|boolean',
        ]);

        $validated['is_active'] = $request->boolean('is_active');

        BulkPricing::create($validated);

        return redirect()->route('admin.bulk-pricing.index')
            ->with('success', 'Bulk pricing rule created successfully');
    }

    public function edit(BulkPricing $bulkPricing)
    {
        $products = Product::where('is_active', true)->get();
        return view('admin.bulk-pricing.edit', compact('bulkPricing', 'products'));
    }

    public function update(Request $request, BulkPricing $bulkPricing)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'min_quantity' => 'required|integer|min:1',
            'max_quantity' => 'nullable|integer|min:1|gte:min_quantity',
            'price' => 'nullable|numeric|min:0',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
            'is_active' => 'nullable|boolean',
        ]);

        $validated['is_active'] = $request->boolean('is_active');

        $bulkPricing->update($validated);

        return redirect()->route('admin.bulk-pricing.index')
            ->with('success', 'Bulk pricing rule updated successfully');
    }

    public function destroy(BulkPricing $bulkPricing)
    {
        $bulkPricing->delete();
        return redirect()->route('admin.bulk-pricing.index')
            ->with('success', 'Bulk pricing rule deleted successfully');
    }
}
