<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Models\CorporateDivision;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class CorporateDivisionController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        $division = CorporateDivision::query()
            ->where('corporate_id', $corporate_id)
            ->get(['id', 'name']);

        return response()->json($division);
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('internal::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request, $corporate_id)
    {
        $request->validate([
            'code' => [
                'required',
            ],
            'name' => 'required'
        ]);

        $newCorporatePlan = CorporateDivision::create([
            'corporate_id' => $corporate_id,
            'code' => $request->code,
            'name' => $request->name,
        ]);

        return $newCorporatePlan;
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('internal::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($corporate_id, $id)
    {
        $corporatePlan = CorporateDivision::findOrFail($id);

        return $corporatePlan;
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $corporate_id, $id)
    {
        $corporatePlan = CorporateDivision::findOrFail($id);
        $request->validate([
            'code' => [
                'required',
                Rule::unique('corporate_plans')->where('corporate_id', $corporate_id)->ignore($corporatePlan->id)
            ],
            'name' => 'required'
        ]);

        $corporatePlan->fill([
            'code' => $request->code,
            'name' => $request->name,
            'active' => $request->active,
        ])->save();

        return $corporatePlan;
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }
}
