<?php

namespace DMZ\Http\Controllers\Web;

use Illuminate\Http\Request;
use DMZ\Http\Requests\Web\ContenidoStoreRequest;
use DMZ\Http\Requests\Web\ContenidoPutRequest; 
use DMZ\Models\Contents;
use DMZ\Models\Categories;
use DMZ\Models\Files;
use DMZ\Http\Requests;
use DMZ\Http\Controllers\Controller;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
use Auth;
use Authy;
use Alert;
use Illuminate\Pagination\LengthAwarePaginator;

class ContentsController extends Controller
{

//     public function __construct()
//    {
//        $this->middleware('auth');
//    }

  public function blog( $category, $mode) {
    // return "mensaje desde blog con parametro ".$category." en formato de visualización ".$mode;
    $categories = Categories::where('slug', $category)->first();
    $data['category'] = $categories;
    //$data['contents'] = Contents::getContentPublic($categories->id)->paginate(4);
    if (Auth::user()) {
      $data['contents'] = Contents::getContentPublicAll($categories->id)->paginate(9);
    }else{
      $data['contents'] = Contents::getContentPublic($categories->id)->paginate(9);
    }
    if($mode=="blog"){
      return view('web.contentBlog', $data);
    }elseif($mode=="listado") {  return $data;
      return view('web.contentList', $data);
    }

  }

  public function item($category, $mode, $slug) {
      
      //dd(Contents::getContentItem($slug)->first());

    if($mode=='eliminar'){
      Contents::destroy($slug);
      alert()->info('Eliminado correctamente', '');

      return redirect('/')
      ->withSuccess('El contenido fue eliminado correctamente');
    }

    // return "mensaje desde blog con parametro ".$category." en formato de visualización   el item ".$slug;
    //dd($slug);
    $categories = Categories::where('slug', $category)->first();
    $data['category'] = $categories;
    $data['content'] = Contents::getContentItem($slug)->first();
    //$data['content']=null;
    // return $data['content']->id;
    $data['images'] = Files::getImages($data['content']->id)->get();
    $data['files'] = Files::getFiles($data['content']->id)->get();
    // return $data;
    return view('web.item', $data);

  }  

  public function edit($category, $mode, $id) {
    if ($mode=="status") {     
      $content = Contents::getContentItemId($id)->first();
      if ($content->status==1) {
        Contents::where('id', $id)->update(['status' => 0]);
        return redirect($content->category_slug.'/blog/'.$content->slug)
      ->withSuccess('Los datos se actualizaron correctamente');
      }else{
        Contents::where('id', $id)->update(['status' => 1]);
        return redirect($content->category_slug.'/blog/'.$content->slug)
      ->withSuccess('Los datos se actualizaron correctamente');
      }
    }         

    $data['content'] = Contents::where('id',$id)->first();
    $data['categories'] = Categories::getCategories()->toArray();
    $data['YN'] = array('1'=>'SI','0'=>'NO');

    // return $data;
    return view('web.edit', $data);
  }

  public function welcome() {
    //return "msg";
    
      
    $data['news'] = Contents::getContentLast('32')->first();
    $data['activities'] = Contents::getContentLast('34')->first();
    $data['contentAll'] = Contents::getContentFeatured()->limit(6)->get();
    // return $data;
    return view('web.welcome', $data);
  }

  public function store(ContenidoPutRequest $request) {
    $request->all();
    $slug = strtolower(str_slug($request->title));
    if($request->featured=='on'){$featured=1;}else{$featured=0;}
  //  if($request->status=='on'){$status=1;}else{$status=0;}
    if ($request->file('images')=='') {
        
    
      
      Contents::where('id', $request->id)->update(
        ['category_id' => $request->category_id,
          'publish_up' => $request->publish_up,
          'title' => $request->title,
          'slug' => $slug,
          'created_by_alias' => $request->created_by_alias,
          'description' => $request->description, 
          'featured' => $featured,
          'updated_by' => Auth::user()->id ]);
      $content = Contents::getContentItemId($request->id)->first();

      alert()->info('Modificado correctamente', $request->title)->persistent("OK");
        return redirect($content->category_slug.'/blog/'.$content->slug)
            ->withSuccess('Los datos se actualizaron correctamente');
    }

    $file = $request->file('images');
    $fileext = $file->getClientOriginalExtension();
    if($fileext='jpeg'){$fileext='jpg';}
    $creation = str_slug(date('Y-m-d H-i-s'));
    $nombre = $creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
    \Storage::disk('imagesBig')->put($nombre,  \File::get($file));

    $nombreOptimized = 'image-'.$creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
    $resizeOptimized= Image::make($request->file('images'));
    $resizeOptimized->resize(900, 900, function ($constraint) {
        $constraint->aspectRatio();
    })->encode($fileext);
    $path=\Storage::disk('imagesOptimized')->put( $nombreOptimized, (string) $resizeOptimized );

    $nombreThumbnail = 'thumbnail-'.$creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
    $resizeThumbnail= Image::make($request->file('images'));
    $resizeThumbnail->resize(100, 100, function ($constraint) {
        $constraint->aspectRatio();
    })->encode($fileext);
    $path=\Storage::disk('imagesSmall')->put( $nombreThumbnail, (string) $resizeThumbnail );

    Contents::where('id', $request->id)->update(
      ['category_id' => $request->category_id,
        'publish_up' => $request->publish_up,
        'title' => $request->title,
        'created_by_alias' => $request->created_by_alias,
        'description' => $request->description,
        'images' => $nombre, 
        'featured' => $featured,
        'updated_by' => Auth::user()->id 
        ]);

    $content = Contents::getContentItemId($request->id)->first();

      alert()->info('Modificado correctamente', $request->title  )->persistent("OK");
        return redirect($content->category_slug.'/blog/'.$content->slug)
            ->withSuccess('Los datos se actualizaron correctamente');

  }

  public function status($category, $status, $id)  { 
    return $id;
  }

  public function create() {
    $data['categories'] = Categories::getCategories()->toArray();
    $data['adicional']  = "diego";
    return view('web.create', $data);
  }

  public function storeNew(ContenidoStoreRequest $request)
  {
//return $request->all();

    if(Auth::user())
      {
//          return $request->all();

        $data = new Contents;

        $data->category_id = $request->category_id;
        $data->publish_up = $request->publish_up;
        $data->created_by_alias = $request->created_by_alias;
        $data->title = $request->title;
        $data->description = $request->description;
        $data->created_by = Auth::user()->id;
        $data->slug = strtolower(str_slug($request->title));
        $data->hits = 1;
        $data->featured = 1;

        if ($request->file('images')=='') {
          $data->save();
            $caQtegory = categories::where('id',$request->category_id)->first();

            return redirect($category->slug.'/blog')
                ->withSuccess('Los datos se actualizaron correctamente');
        }  

        $file = $request->file('images');
        $fileext = $file->getClientOriginalExtension();
        if($fileext='jpeg'){$fileext='jpg';}
        $creation = str_slug(date('Y-m-d H-i-s'));
        $nombre = $creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
        \Storage::disk('imagesBig')->put($nombre,  \File::get($file));

        $nombreOptimized = 'image-'.$creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
        $resizeOptimized= Image::make($request->file('images'));
        $resizeOptimized->resize(900, 900, function ($constraint) {
          $constraint->aspectRatio();
        })->encode($fileext);
        $path=\Storage::disk('imagesOptimized')->put( $nombreOptimized, (string) $resizeOptimized );

        $nombreThumbnail = 'thumbnail-'.$creation.'-'.strtolower(str_slug($request->title)).'.'.$fileext;
        $resizeThumbnail= Image::make($request->file('images'));
        $resizeThumbnail->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->encode($fileext);
        $path=\Storage::disk('imagesSmall')->put( $nombreThumbnail, (string) $resizeThumbnail );
          $data->images = $nombre;
          $data->featured = 1;
          $data->save();
          
          $category = categories::where('id',$request->category_id)->first();

        alert()->info('Registrado correctamente', $request->title)->persistent("OK");

          return redirect($category->slug.'/blog')
            ->withSuccess('Los datos se actualizaron correctamente');

      }
      return "no tiene autorización";
  }

  public function delete($id)
  {

    Contents::destroy($id);
      return response()->json(['element' => $id, 'message' => 'delete Content'], 202);


    if(\Request::ajax()) {
        Contents::destroy($id);
        return response()->json(['element' => $id, 'message' => 'delete Content'], 202);
      } 
  }
  
  public function uploadImage(Request $request) {
    //return $request->all();
    // return $request->file('image');
      
    $file = $request->file('image');
    $fileext = $file->getClientOriginalExtension(); 
    // return $fileext;
    if($fileext='jpeg'){$fileext='jpg';}
    $creation = str_slug(date('Y-m-d H-i-s'));
    $nombre = 'upload-'.rand(10000,99999).'-'.$creation.'.'.$fileext;
    // \Storage::disk('imagesBig')->put($nombre,  \File::get($file));

    $nombreOptimized = $nombre;
    $resizeOptimized= Image::make($request->file('image'));
    
    $resizeOptimized->resize(900, 900, function ($constraint) {
        $constraint->aspectRatio();
    })->encode($fileext);
    
    $path=\Storage::disk('imagesOptimized')->put( $nombreOptimized, (string) $resizeOptimized );
        
    return 'http://machareti-ivo.org/assets/img/optimized/'.$nombre;
    /*
    return "http://www.machareti-ivo.org/assets/img/optimized/image-2019-08-19-16-26-52-carlos-cuellar-virtudes-de-medico-naturista-y-una-historia-de-lucha.jpg";
    return response()->json(['image' => 'asdas', 'message' => 'image uploaded'], 202);*/
  }

}
