<?php

namespace DMZ\Http\Controllers\Web;

use Illuminate\Http\Request;
use DMZ\Models\Documentos;
use DMZ\Http\Requests;
use DMZ\Http\Requests\Web\DocumentoStoreRequest;
use DMZ\Http\Requests\Web\DocumentoPutRequest;
use DMZ\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
use Auth; 

class DocumentosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {         
        if (Auth::user()) {
            $data['documentos'] = Documentos::getDocumentos()->paginate(5);
        }else{
            $data['documentos'] = Documentos::getDocumentos()->where('status',true)->paginate(5); 
        }       
        $data['category'] = 'Documentos';
        return view('web.documentos.index', $data);
    }

    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        //return "formulario de creacion de autoridad";
        return view('web.documentos.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response AuthoritiesStoreRequest Request
     */ 
    public function store(DocumentoStoreRequest $request)
    {        
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        //return $request->all();
        $data = new Documentos;
        $data->title  = $request->title;    
        $data->description  = $request->description;  
        $data->publish_up  = $request->publish_up;


            $file = $request->file('file');
            $fileext = $file->getClientOriginalExtension(); 
        $data->type = $fileext;
        $data->size = ($file->getSize()/1024)/1024;
            $creation = str_slug(date('Y-m-d H-i-s'));
            $nombre = $creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
            \Storage::disk('documentsWeb')->put($nombre,  \File::get($file));
        $data->file = $nombre;
        $data->save();

        alert()->info('Registrado correctamente', $request->title );
             
        return redirect('documentos');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return "documentos-".$id;
        
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    { 
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        $data['documento'] = Documentos::find($id);
        if (!Documentos::find($id)) {
           alert()->error('No se ha encontrado el registro', 'ERROR');
           return redirect('documentos');
        }
        
        return view('web.documentos.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(DocumentoPutRequest $request, $id)
    { 
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        $data = Documentos::find($id);
        $data->title  = $request->title;    
        $data->description  = $request->description;  
        $data->publish_up  = $request->publish_up;

        if ($request->file('file')) {
                $file = $request->file('file');
                $fileext = $file->getClientOriginalExtension(); 
            $data->type = $fileext;
            $data->size = ($file->getSize()/1024)/1024;
                $creation = str_slug(date('Y-m-d H-i-s'));
                $nombre = $creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
                \Storage::disk('documentsWeb')->put($nombre,  \File::get($file));
            $data->file = $nombre;   
        }


        $data->save();

        alert()->success('Registro actualizado correctamente', $request->title);
 
             
        return redirect('documentos');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        if(\Request::ajax()) {
            Documentos::destroy($id);
            return response()->json(['element' => $id, 'message' => 'delete'], 202);
        }
        //Authorities::destroy($id);

        Documentos::find($id)->delete();
    }

    public function download($id)
    {
        if(\Request::ajax()) {
            Documentos::find($id)->increment('hits',1);
            return response()->json(['element' => $id, 'message' => '+1 download'], 202);
        } 
    }

    public function statusChange($id,$status)
    {
        if (!Auth::user()) {
            alert()->error($_SERVER ['HTTP_USER_AGENT'], 'Usted no tiene permisos para realizar ésta actividad, se notificará al administrador')->persistent('Cerrar');
            return redirect('/'); 
        }
        if(\Request::ajax()) {
            if ($status) {
                Documentos::where('id', $id)->update(['status' => false]);
                return response()->json(['element' => $id, 'message' => 'to False', 'now' => false, 'previous' => $status], 202);
            }else{
                Documentos::where('id', $id)->update(['status' => true]);
                return response()->json(['element' => $id, 'message' => 'to False', 'now' => true, 'previous' => $status], 202);
            }
        }
        return response()->json(['element' => $id, 'message' => 'error'], 404);
    }

}
