<?php

namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\Request;

class DocumentController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    public function index(Request $request){
       
        try{
          
            if ((isset($request['search'])) || (isset($request['orderby'])) || (isset($request['orderdir'])) || (isset($request['start'])) || (isset($request['length']))) {
                $orderBy = $request['orderby'];
                $orderDir = $request['orderdir'];
                $start = $request['start'];
                $length = $request['length'];
                $query= $documents = Document::orderBy($orderBy, $orderDir);
                if (isset($request['search'])) {
                    $search = $request['search'];
                    $query=$query->where('description', 'like', '%'.$search.'%')
                    ->skip($start)
                    ->take($length);
                } 
                $doc_count=$query->count();
                $documents=$query->skip($start)->take($length);
                $documents=$documents->get();          
            } else {
                $do = Document::query();
                $doc_count=$do->count();
                $documents = $do->get(); 
            } 
            $respuesta['total']=$doc_count;
            $respuesta['list']=$documents;
             if( count($documents) > 0){
                 return $this->successResponse($respuesta, "", 201);
             } else {
                 return $this->successResponse($respuesta,"No hay Documentos cargados en el sistema.", 201);
             }

         } catch(\Exception $ex){
             return $this->messageError("Ocurrió un error al buscar los Documentos.", 201);
         }
    }

    public function show(int $id){
       try{
           if($id != ""){
                $document= Document::find($id);
           }else{
                $document=null;
           }
            
            if( $document === null){
                return $this->messageError("No hay datos para el Documento buscado.", 201);
            } else {
                return $this->successResponse($document, "", 201);
            }
        } catch(\Exception $ex){
            return $this->messageError("Ocurrió un error al buscar los Documentos en el sistema.", 201);
        }
    }

    public function store(Request $request)
    {
        // return response($request->all(),201);
    }

    public function update(){
        // return  response(null, 204);
    }
    
    public function destroy(){
        // return  response(null, 204);
    }

}
