<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\User;

use App\Models\Setor;
use App\Http\Requests;
use App\Models\Protocolo;
use Illuminate\Http\Request;
use App\Mail\NotificacaoMail;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\SetorController;
use App\Notifications\TelegramNotification;
use App\Http\Controllers\AcompanhamentoController;
use Illuminate\Support\Facades\Storage;

class ProtocoloController extends Controller
{

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        //Somente o cadastrador pode ver esta tela
        if(Auth::user()->nivel =! 1){
            return redirect()->route('login');
        }

        $keyword = $request->get('search');
        $perPage = 25;

        if (!empty($keyword)) {
            $protocolo = Protocolo::where('codigo', 'LIKE', "%$keyword%")
                ->orWhere('tipo', 'LIKE', "%$keyword%")
                ->orWhere('descricao', 'LIKE', "%$keyword%")
                ->orWhere('status', 'LIKE', "%$keyword%")
                ->orWhere('idUser', 'LIKE', Auth::user()->id)
                ->latest()->paginate($perPage);
        } else {
            $protocolo = Protocolo::latest()->paginate($perPage);
        }

        return view('cadastrador.solicitacoes', compact('protocolo'));
    }

    public function indexMinhasSolicitacoes()
    {
        //Somente o cadastrador pode ver esta tela
        if(Auth::user()->nivel =! 3){
            return view('auth.login');
        }

        $protocolo = Protocolo::all()->where('idUser', '=', Auth::user()->id);

        return view('protocolo.index', compact('protocolo'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('protocolo.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        //Tamanho máximo de upload 20 mil kB (20MB)
        $this->validate($request, [
			'tipo' => 'required',
			'descricao' => 'required',
            'g-recaptcha-response' => 'required|captcha',
            'anexo' => 'mimes:jpeg,jpg,gif,bmp,png,tiff,pdf|max:20000'

		]);
        $requestData = $request->all();
        $requestData['codigo'] = uniqid(8);
        $requestData['idUser'] = Auth::user()->id;
        $requestData['status'] = "aberta";
        $requestData['idSetor'] = 1;

        //$arrayExtensoes = ["jpeg", "jpg", "gif", "png", "bmp", "tiff", "pdf"];

        if(isset($requestData['anexo'])){
            //if(in_array($request->file('anexo')->extension(), $arrayExtensoes)){
                $caminho = Storage::put('public\\protocolos\\'.Auth::user()->ids, $request->file('anexo'));
                $requestData['anexo'] = $caminho;
            /*}else{
                $error = [];
                $error['anexo'] = 'Só são permitidos arquivos com as extensões: "jpeg", "jpg", "gif","png", "bmp","tiff","pdf"';
                return view('protocolo\create', compact('error'));
            }*/
        }

        $user = Auth::user()->name;
        $codigo = $requestData['codigo'];

        Protocolo::create($requestData);
        //envia e-mail
        $users = User::all()->where('nivel', '=', 1);

        foreach($users as $user){
            if ($user->notificarEmail) {
                //Mail::send(new NotificacaoMail($user, 'novaSolicitacao'));
            }
        }

        if (Auth::user()->notificarEmail) {
            //Mail::send(new NotificacaoMail(Auth::user(), 'recebemosSolicitacao'));
        }

        $cadastradores = User::all()->where("nivel","=",1)->where("notificarTelegram","=", true);

        foreach($cadastradores as $cadastrador){
            $cadastrador->notify(new TelegramNotification(TelegramNotification::NOVA_SOLICITACAO_CADASTRADOR));
        }

        return view('solicitante.sucesso',compact('user','codigo'));
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $protocolo = Protocolo::findOrFail($id);
        $protocolo->idSetor = Setor::findOrFail($protocolo->idSetor)->nome;
        $usuario = User::findOrFail($protocolo->idUser);
        $aC = new AcompanhamentoController();
        $resposta = $aC->listarAcompanhamentos($id);
        $acompanhamentos = $resposta["acompanhamentos"];
        $nivel = $resposta["nivel"];
        $sC = new SetorController();
        $setores = $sC->imprimeArvoreWrapper();

        return view('protocolo.show', compact('protocolo', 'acompanhamentos', 'nivel', 'setores', 'usuario'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $protocolo = Protocolo::findOrFail($id);

        return view('protocolo.edit', compact('protocolo'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
			'tipo' => 'required',
			'descricao' => 'required',

		]);
        $requestData = $request->all();

        $protocolo = Protocolo::findOrFail($id);
        $protocolo->update($requestData);

        return redirect('protocolo')->with('flash_message', 'Protocolo updated!');
    }

    public function updateSetor(Request $request){
        $protocolo = Protocolo::findOrFail($request->id);
        $protocolo->idSetor = $request->idSetor;
        $protocolo->status = 'encaminhada';
        $protocolo->update();

        $protocolo = Protocolo::all();

        $users = DB::table('users')
        ->select('users.id', 'users.notificarEmail', 'users.notificarTelegram', 'users_funcionarios.idSetor')
        ->join("users_funcionarios", "users_funcionarios.idUser", "=", "users.id")
        ->where("users_funcionarios.idSetor", "=", $request->idSetor)
        ->get();

        foreach($users as $user){
            if($user->notificarEmail){
                //Mail::send(new NotificacaoMail(User::findOrFail($user->id), 'novaSolicitacaoFuncionario'));
            }
            if($user->notificarTelegram){
                User::findOrFail($user->id)->notify(new TelegramNotification(TelegramNotification::NOVA_SOLICITACAO_FUNCIONARIO));
            }
        }

        return view('cadastrador.solicitacoes', compact('protocolo'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        Protocolo::destroy($id);

        return redirect('protocolo')->with('flash_message', 'Protocolo deleted!');
    }

    public function index2(){

        return view("solicitante.index");

    }

    public function verificaProtcolosConcluidosEAtrasados(){
        //var_dump("Passou!");
        //Marca como "atrasado" as solicitações a mais de 15 dias sem resposta
        /*DB::table('protocolos')
        ->whereRaw("DATEDIFF('".Carbon::now()."', `created_at`) > 15
        AND (`status` LIKE 'aberta'
        OR `status` LIKE 'encaminhada')")
        ->update(["status" => 'atrasada', "updated_at" => Carbon::now()]);*/

        DB::table('protocolos')
        ->whereRaw("DATEDIFF('".Carbon::now()."', created_at) > 15
        AND (status LIKE 'aberta'
        OR status LIKE 'encaminhada')")
        ->update(['status' => 'atrasada', 'updated_at' => Carbon::now()]);

        /*$teste[0] = DB::raw("UPDATE `protocolos` SET `status` = 'atrasada', `updated_at` = NOW()
        WHERE DATEDIFF('".Carbon::now()."', `created_at`) > 15
        AND (`status` LIKE 'aberta'
        OR `status` LIKE 'encaminhada')");*/

        DB::table('protocolos')
        ->whereRaw("DATEDIFF('".Carbon::now()."', updated_at) > 10
        AND (status LIKE 'respondida')")
        ->update(['status' => 'fechada', 'updated_at' => Carbon::now()]);

        /*$teste[1] = DB::raw("UPDATE `protocolos` SET `status` = 'fechada', `updated_at` = NOW()
        WHERE DATEDIFF('".Carbon::now()."', `updated_at`) > 10
        AND (`status` LIKE 'respondida')");*/

        DB::table('protocolos')
        ->whereRaw("DATEDIFF('".Carbon::now()."', updated_at) > 15
        AND (status LIKE 'atrasada')")
        ->update(['status' => 'fechada', 'updated_at' => Carbon::now()]);

        /*$teste[2] = DB::raw("UPDATE `protocolos` SET `status` = 'fechada', `updated_at` = NOW()
        WHERE DATEDIFF('".Carbon::now()."', `updated_at`) > 15
        AND (`status` LIKE 'atrasada')");*/

    }
}
