<?php

namespace App\Http\Controllers;

use App\Models\MasterUnit;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MasterUnitController extends Controller
{
    public function index(): view
    {
        $masterUnit       = MasterUnit::latest()->paginate(5);

        return view('unit/unit_list',[
            'masterUnit'  => $masterUnit
        ]);
    }

    public function create(): view
    {
        $projects       = Project::where('status', 1)->get();
        return view('unit/unit_form', [
            'projects'  => $projects
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'unit_code'     => 'required',
            'unit_name'     => 'required',
            'project_code'  => 'required',
            'status'        => 'required'
        ]);

        $unit_code      = $request->unit_code;
        $unit_name      = $request->unit_name;
        $project_code   = $request->project_code;
        $status         = $request->status;
        $description    = $request->description;

        MasterUnit::create([
            'unit_code'     => $unit_code,
            'unit_name'     => $unit_name,
            'project_code'  => $project_code,
            'status'        => $status,
            'description'   => $description
        ]);

        return redirect('/unit/master_unit');
    }

    public function show($unit_code): view
    {
        $unitData   = MasterUnit::where('unit_code', $unit_code)->firstOrFail();
        $projects   = Project::where('status', 1)->get();
        
        return view('unit/unit_detail', [
            'unitData'  => $unitData,
            'projects'  => $projects,
        ]);
    }

    public function update($unit_code, Request $request)
    {
        $request->validate([
            'unit_code'     => 'required',
            'unit_name'     => 'required',
            'project_code'  => 'required',
            'status'        => 'required'
        ]);

        $unit_code      = $request->unit_code;
        $unit_name      = $request->unit_name;
        $project_code   = $request->project_code;
        $status         = $request->status;
        $description    = $request->description;

        MasterUnit::where('unit_code', $unit_code)->update([
            'unit_name'     => $unit_name,
            'project_code'  => $project_code,
            'status'        => $status,
            'description'   => $description,
        ]);

        return redirect('/unit/master_unit');
    }

    public function destroy($unit_code)
    {
        MasterUnit::where('unit_code', $unit_code)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Project berhasil dihapus'
        ]);
    }
}
