<?php

namespace App\Http\Controllers;

use App\Modulos;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ModulosController extends Controller
{
    public function ListarModulos(Request $request)
    {

        $buscar = $request->buscar;

        if ($buscar=='') {
            $modulos = DB::table('modulos as mod') 
                ->select('mod.nombre as nombre','mod.detalle as detalle','mod.estado as estado','mod.id as id')
                ->orderBy('mod.id', 'desc')->paginate(10);
        } else {
            $modulos = DB::table('modulos as mod') 
                ->select('mod.nombre as nombre','mod.detalle as detalle','mod.estado as estado','mod.id as id')
                ->where(function($q) use ($buscar) {
                    $q->where('mod.nombre', 'LIKE', '%'.$buscar.'%')
                    ->orwhere('mod.detalle', 'LIKE', '%'.$buscar.'%');
                })
                ->orderBy('mod.id', 'desc')->paginate(10);
        }

        return [
            'pagination' => [
                'total'          => $modulos->total(),
                'current_page'   => $modulos->currentPage(),
                'per_page'       => $modulos->perPage(),
                'last_page'      => $modulos->lastPage(),
                'from'           => $modulos->firstItem(),
                'to'             => $modulos->lastItem(),
            ],
            'modulos'  => $modulos
        ];
    }

    public function registrarModulo(Request $request)
    {
        if (Modulos::where('nombre',$request->nombre)->first()) {
            return response()->json(['code'=> 400]);
            
        } else {
            $modulo = Modulos::create([
                'nombre' => $request->nombre,
                'detalle' => $request->detalle,
                'estado' => $request->estado,
                'sysuser' => Auth::user()->nick,
            ]);
            return response()->json(['code'=> 200]);
        }
    }

    public function desactivarModulo(Request $request)
    {
        $modulo = Modulos::findOrFail($request->id);
        $modulo->estado = '0';
        $modulo->save();
    }

    public function activarModulo(Request $request)
    {
        $modulo = Modulos::findOrFail($request->id);
        $modulo->estado = '1';
        $modulo->save();
    }

    public function actualizarModulo(Request $request)
    {
        $modulo = Modulos::where('id',$request->id)
            ->first();

        $modulo->update([
        'nombre' => $request->nombre,
        'detalle' => $request->detalle,
        ]);
        return response()->json($modulo);
        
    }

    public function selectModulos()
    {
        $modulos = Modulos::all();

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