<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Material;
use Illuminate\Http\Request;

class MaterialController extends Controller
{
    /**
     * Display a listing of materials with optional category filter
     */
    public function index(Request $request)
    {
        $query = Material::query();
        
        // Filter by category if provided
        if ($request->has('category') && $request->category != '') {
            $query->where('category', $request->category);
        }
        
        $materials = $query->latest()->paginate(12);
        
        return view('superadmin.materials.index', compact('materials'));
    }

    /**
     * Show the form for creating a new material
     */
    public function create()
    {
        return view('superadmin.materials.create');
    }

    /**
     * Store a newly created material in storage
     */
    public function store(Request $request)
    {
        $request->validate([
            'category' => 'required|in:panel,solid,veneer,mdf,other',
            'name' => 'required|string|max:255',
            'thickness' => 'required|numeric|min:0',
            'price_per_m2' => 'nullable|numeric|min:0',
            'price_per_unit' => 'nullable|numeric|min:0',
            'unit' => 'required|string|max:20',
        ]);

        Material::create($request->all());

        return redirect()->route('superadmin.materials.index')->with('success', 'Material berhasil ditambahkan!');
    }

    /**
     * Show the form for editing the specified material
     */
    public function edit(Material $material)
    {
        return view('superadmin.materials.edit', compact('material'));
    }

    /**
     * Update the specified material in storage
     */
    public function update(Request $request, Material $material)
    {
        $request->validate([
            'category' => 'required|in:panel,solid,veneer,mdf,other',
            'name' => 'required|string|max:255',
            'thickness' => 'required|numeric|min:0',
            'price_per_m2' => 'nullable|numeric|min:0',
            'price_per_unit' => 'nullable|numeric|min:0',
            'unit' => 'required|string|max:20',
        ]);

        $material->update($request->all());

        return redirect()->route('superadmin.materials.index')->with('success', 'Material berhasil diupdate!');
    }

    /**
     * Remove the specified material from storage
     */
    public function destroy(Material $material)
    {
        $material->delete();
        
        return redirect()->route('superadmin.materials.index')->with('success', 'Material berhasil dihapus!');
    }
}