<?php

namespace DMZ\Http\Controllers\Web;

use Illuminate\Http\Request;
use DMZ\Models\Fotos;
use DMZ\Models\Albums;
use DMZ\Http\Requests;
use DMZ\Http\Requests\Web\FotoStoreRequest;
use DMZ\Http\Requests\Web\FotoPutRequest;
use DMZ\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
use Auth; 

class FotosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $filter)
    {         
       //($filter);
       //return Input::get('filter');
        if (Auth::user()) {
            $data['fotos'] = Fotos::getFotos()->where('album_id',Input::get('filter'))->paginate(8);
        }else{
            $data['fotos'] = Fotos::getFotos()->where('album_id',Input::get('filter'))->where('status',true)->paginate(8); 
        }       
        return view('web.fotos.index', $data);
    }

    public function fotosAlbum(){
        return "album";
    }
    
    /**
     * 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";
        $data['albums'] = Albums::getSelectAlbums()->toArray();
        return view('web.fotos.create',$data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response AuthoritiesStoreRequest Request
     */  
     // FotoStoreRequest
    public function store(FotoStoreRequest $request)
    {        
        //return $request->all();
        //return $request->file; 
    /*
        foreach ($request->file as $file) {
            echo $file->getClientOriginalName();
        }*/ 
        
        
        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('/'); 
        }
        
        foreach ($request->file as $file) {
        
            //return $request->all();
            $data = new Fotos;
            $data->title  = $request->title;  
            $data->album_id  = $request->album_id;  
            $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'));
                $hash =md5(microtime());
                $nombre = $hash.'.'.$fileext;
                
                \Storage::disk('fotosWeb')->put($nombre,  \File::get($file));
    /*
                $nombreOptimized = 'image-'.$creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
                $resizeOptimized= Image::make($request->file('file'));
                $resizeOptimized->resize(900, 900, function ($constraint) {
                    $constraint->aspectRatio();
                })->encode($fileext);
                $path=\Storage::disk('fotosWeb')->put( $nombreOptimized, (string) $resizeOptimized );
    */
            $data->file = $nombre;
            $data->save();
            
        }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //return "fotos-".$id;
        $data['foto'] = Fotos::find($id);
        return view('web.fotos.show',$data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    { 
      //  return $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'] = Fotos::find($id);
        $data['albums'] = Albums::getSelectAlbums()->toArray();
        //return $data;
        if (!Fotos::find($id)) {
           alert()->error('No se ha encontrado el registro', 'ERROR');
           return redirect('albums');
        }
        
        return view('web.fotos.edit',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(FotoPutRequest $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 = Fotos::find($id);
        $data->album_id  = $request->album_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('fotosWeb')->put($nombre,  \File::get($file));
            $data->file = $nombre;   
        }


        $data->save();

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

    /**
     * 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()) {
            Fotos::destroy($id);
            return response()->json(['element' => $id, 'message' => 'delete'], 202);
        }
        //Authorities::destroy($id);

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

    public function download($id)
    {
        if(\Request::ajax()) {
            Fotos::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) {
                Fotos::where('id', $id)->update(['status' => false]);
                return response()->json(['element' => $id, 'message' => 'to False', 'now' => false, 'previous' => $status], 202);
            }else{
                Fotos::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);
    }
    
    public function scopeSetAlbum(){
        
    }

}
