<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UnitType;
use Alert;
use Illuminate\Support\Facades\Auth;

class UnitTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $unitTypes = UnitType::with(['organizationalUnits', 'creator'])->get();
        return view('unit-types.index', compact('unitTypes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('unit-types.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $rules = [
            'type_name' => 'required|string|max:255|unique:unit_types',
            'level' => 'required|integer|min:1',
            'description' => 'nullable|string',
        ];

        $validatedData = $request->validate($rules);
        $validatedData['created_by'] = Auth::id();

        UnitType::create($validatedData);

        Alert::success('نجاح', 'تمت إضافة نوع الوحدة بنجاح!');
        return redirect()->route('unit-types.index');
    }

    /**
     * Display the specified resource.
     */
    public function show(UnitType $unitType)
    {
        $unitType->load(['organizationalUnits', 'creator']);
        return view('unit-types.show', compact('unitType'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(UnitType $unitType)
    {
        return view('unit-types.edit', compact('unitType'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, UnitType $unitType)
    {
        $rules = [
            'type_name' => 'required|string|max:255|unique:unit_types,type_name,' . $unitType->id,
            'level' => 'required|integer|min:1',
            'description' => 'nullable|string',
        ];

        $validatedData = $request->validate($rules);

        $unitType->update($validatedData);

        Alert::success('نجاح', 'تم تحديث نوع الوحدة بنجاح!');
        return redirect()->route('unit-types.index');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(UnitType $unitType)
    {
        $unitType->delete();

        Alert::success('نجاح', 'تم حذف نوع الوحدة بنجاح!');
        return redirect()->route('unit-types.index');
    }
}
