<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\RawMaterial;

class RawMaterialController extends Controller
{
    public function index()
    {
        // Redirect to produk page with bahan-baku tab
        return redirect('/produk?tab=bahan-baku');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'unit' => 'required|string|max:50',
        ]);

        $branch = auth()->user()->branch ?? 'Cabang 1';

        RawMaterial::create([
            'name' => $request->name,
            'unit' => $request->unit,
            'stock_quantity' => 0,
            'branch' => $branch
        ]);

        return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'unit' => 'required|string|max:50',
        ]);

        $rawMaterial = RawMaterial::findOrFail($id);
        $branch = auth()->user()->branch ?? 'Cabang 1';

        // Only allow update if raw material belongs to user's branch
        if ($rawMaterial->branch !== $branch) {
            return back()->with('error', 'Anda tidak memiliki akses untuk mengubah bahan baku dari cabang lain.');
        }

        $rawMaterial->update([
            'name' => $request->name,
            'unit' => $request->unit,
        ]);

        return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $rawMaterial = RawMaterial::findOrFail($id);
        $branch = auth()->user()->branch ?? 'Cabang 1';

        // Only allow deletion if raw material belongs to user's branch
        if ($rawMaterial->branch !== $branch) {
            return back()->with('error', 'Anda tidak memiliki akses untuk menghapus bahan baku dari cabang lain.');
        }

        $rawMaterial->delete();

        return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil dihapus.');
    }
}
