<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Routing\Controllers\HasMiddleware;

use Illuminate\Http\Request;
use App\Models\User;
use App\DataTables\UserDataTableEditor;
use App\DataTables\UserDataTable;
use Illuminate\Support\Facades\Auth;
use Notification;
use Session;
use PDF;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Mail\InvitoFamiglia;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller implements HasMiddleware
{
  public static $permission_group = "Utenti";
  public static $permissions = [
    'view-user' => 'Vedi',
    'create-user' => 'Crea',
    'edit-user' => 'Modifica',
    'remove-user' => 'Rimuovi'
  ];

  public $messages = [
    'nome.required' => 'Devi indicare il nome',
    'cognome.required' => 'Devi indicare il cognome',
    // 'telefono.required' => 'Devi indicare il telefono',
    'email.required' => 'Devi indicare l\'indirizzo email',
    'email.email' => 'L\'indirizzo email indicato non è valido',
    'email.unique' => 'L\'indirizzo email indicato non è valido',
    'password.required' => 'Devi indicare la password',
    'password.confirmed' => 'La password non corriponde a quella di conferma',
    'password.min' => 'La password deve essere composta da almeno 8 caratteri',
  ];

  public static function middleware(): array
  {
    return [
      new Middleware('permission:view-user', only: ['index']),
      new Middleware('permission:create-user|edit-user|remove-user', only: ['store', 'admin_aggiorna']),
    ];
  }

  public function index(UserDataTable $dataTable)
  {
    return $dataTable->render('user.index');
  }

  public function store(UserDataTableEditor $editor)
  {
    $request = request();
    $input = $request->all();

    if($request->has('action')){
      switch($input['action']){
        case 'create':
          if(!Auth::user()->can('create-user')) return;
          break;

          case 'edit':
            if(!Auth::user()->can('edit-user')) return;
            break;

            case 'remove':
              if(!Auth::user()->can('remove-user')) return;
              break;
            }
          }
          if($request->action == 'remove' && (array_key_first($request->data) == Auth::user()->id) && Auth::user()->hasRole('superadmin')){
            // dd('ok');
            return response()->json(['error' => 'Non puoi eliminare te stesso se sei superadmin!' , 'success' => false , 'class' => 'alert-danger'], 400);
          }
          return $editor->process($request);
        }


        //////


        public function upload_foto_profilo(Request $request){
          $original_name = $request->file->getClientOriginalName();
          $extension = pathinfo($original_name, PATHINFO_EXTENSION);

          $filename = pathinfo(Str::camel($original_name), PATHINFO_FILENAME)."_".time().".".$extension;

          //store file into temp folder
          $file = $request->file->storeAs('', $filename , 'temp');
          // $evento->path_img = $file;
          // $evento->save();

          return response()->json(['url' => Storage::disk('temp')->url($file), 'filename' => $file]);
        }

        public function showCropImage(Request $request){
          return view('profile.cropImage', ['filename' => $request->filename]);
        }

        public function cropImage(Request $request){
          // $evento = Evento::find($request->evento_id);
          $fileName = explode(".", $request->filename);
          $extension = array_pop($fileName);
          $filename = implode("_", $fileName);

          // create new image instance
          $manager = new ImageManager(new Driver());
          $image = $manager->read(Storage::disk('temp')->path($request->filename));
          $image->crop($request->cropBoxData['width'], $request->cropBoxData['height'], $request->cropBoxData['x'], $request->cropBoxData['y']);
          $newFileName = $filename.'_'.time().'_cropped.'.$extension;
          Storage::disk('temp')->put($filename.'_'.time().'_cropped.'.$extension, $image->encodeByExtension($extension, quality: 100));
          // $evento->path_img = $newFileName;
          // $evento->save();

          return response()->json(['url' => Storage::disk('temp')->url($newFileName), 'filename' => $newFileName]);
        }

        public function admin_list(Request $request){
          $input = $request->all();
          $list = array();

          if($request->has('initialValue') && $input['initialValue'] == "true"){
            $val = trim(str_replace('"', '', $input['value']));
            $entity = User::find($val);
            return response()->json(['id' => $entity->id, 'text' => $entity->full_name]);

          }else{
            $page = $input['page'];
            $resultCount = 25;
            $offset = ($page - 1) * $resultCount;
            $entitys = User::where(function($q)use($input){
              $q->where('nome', 'LIKE', '%'.$input['term'].'%')
              ->orWhere('cognome', 'LIKE', '%'.$input['term'].'%');
            })
            ->orderBy('cognome', 'ASC');


            foreach ($entitys->skip($offset)->take($resultCount)->get() as $e) {
              if(!$e->hasRole('superadmin') || ($e->hasRole('superadmin') && Auth::user()->hasRole('superadmin'))){
                array_push($list, array('id' => $e->id, 'text' => $e->full_name));
              }
            }

            $count = $entitys->count();
            $endCount = $offset + $resultCount;
            $morePages = $count > $endCount;

            $results = array(
              "results" => $list,
              "pagination" => array(
                "more" => $morePages
                )
              );

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


        }
