<?php

namespace App\Http\Controllers;

use App\Models\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ActionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $filter = json_decode($request->get('filter'));

        $getActions = Action::where('name', 'LIKE', '%' . $filter->name . '%')
            ->orderBy('id', 'DESC')
            ->paginate($request->get('rows'));

        return response()->json($getActions, 200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $newAction = new Action;
            $newAction->id_user = Auth::id();
            $newAction->id_user_update = Auth::id();
            $newAction->name = $request->name;
            $newAction->save();

            DB::commit();
            return response()->json('Acción guardada con éxito', 201);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - ActionController@store]: ' . $th, 500); 
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $getAction = Action::find($id);
        return response()->json($getAction, 200);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();

            $updateAction = Action::find($id);
            $updateAction->id_user_update = Auth::id();
            $updateAction->name = $request->name;
            $updateAction->save();

            DB::commit();
            return response()->json('Acción editada con éxito', 200);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - ActionController@update]: ' . $th, 500); 
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            DB::beginTransaction();

            $updateAction = Action::find($id);
            $updateAction->id_user_update = Auth::id();
            $updateAction->active = $updateAction->active == 1 ? 0 : 1;
            $updateAction->save();

            DB::commit();
            return response()->json('Cambio de estatus con éxito', 200);
        } catch (Exception $th) {
            DB::rollback();
            return response()->json('[Error - ActionController@destroy]: ' . $th, 500); 
        }
    }

    public function listActions() {
        $list = Action::where('active', 1)->get();
        return response()->json($list, 200);
    }
}
