<?php

namespace App\Http\Controllers;

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

class DepartmentsController extends Controller
{
    public function index(Request $request)
    {
        $rows = Department::query()
            ->when($request->get('q'), function ($query, $keyword) {
                $query->search($keyword, ['departments.name']);
            })
            ->orderBy('id', 'DESC')
            ->with('creator')
            ->get();

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

    public function store(Request $request)
    {
        if ($request->has('id')) {
            $row = Department::find($request->input('id'));
        } else {
            $row = new Department();
        }
        $row->fill($request->input());
        $row->save();

        $result = $row->load('creator');

        return response()->json([
            'status' => 1,
            'row' => $result
        ]);
    }

    public function destroy($rowId)
    {
        $row = Department::findOrFail($rowId);
        if (!empty($row)) {
            $row->delete();
        }

        return response()->json([
            'status'  => 1
        ]);
    }


    public function show($reference)
    {
        return response()->json([
            'row' => Department::where('reference', $reference)->with('creator')->first()
        ]);
    }
}
