<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


use Illuminate\Support\Facades\Event;
use App\Task;
use App\Notifications;
use App\Tasktag;
use Illuminate\Http\Request;
use App\Http\Controllers\TagController;
use Illuminate\Support\Facades\DB;
use Illuminate\Routing\Router;
use App\Pipeline;
use App\TaskForm;


Route::get('/', function () {
    return redirect('/home/1');
});


// Validar usuarios invitados

Route::get('registerinvited', 'ValidateInvitedController@index');
Route::get('logininvited', 'ValidateInvitedController@index');


Route::get('searchTaskInactive', 'TesterController@testInactive');

// app/Http/routes.php





Auth::routes();


Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'admin']], function () {
    //Pipelines

    Route::get('pipeline', ['uses' => 'Admin\PipelineController@index']);
    Route::get('pipeline/{id}/edit', ['uses' => 'Admin\PipelineController@edit']);
    Route::get('pipeline/create', ['uses' => 'Admin\PipelineController@create']);
    Route::post('pipeline/store', 'Admin\PipelineController@store');
    Route::post('pipeline/update', 'Admin\PipelineController@update');
    Route::get('pipeline/{id}/delete', ['uses' => 'Admin\PipelineController@delete']);

    Route::post('pipeline/order-pipeline-units', 'Admin\PipelineController@orderPipelineUnits');



//Units
    Route::get('unit', ['uses' => 'Admin\UnitController@index', 'as' => 'unit.controller']);
    Route::get('unit/create', ['uses' => 'Admin\UnitController@create']);
    Route::get('unit/{id}/edit', ['uses' => 'Admin\UnitController@edit']);
    Route::post('unit', 'Admin\UnitController@store');
    Route::post('unit/update', 'Admin\UnitController@update');
    Route::post('unit/add-user', 'Admin\UnitController@addUser');
    Route::post('unit/delete-user', 'Admin\UnitController@deleteUser');


    Route::get('unit/unit-role-walker', 'Admin\UnitController@unitUserRoleWalker');
    Route::post('tagPipeline','Admin\UnitController@autoTagPipeline');
    Route::post('untagPipeline','Admin\UnitController@unTagPipeline');


    Route::post('unit/add-profile','Admin\UnitController@addProfile');
    Route::post('untagProfile','Admin\UnitController@unTagProfile');



    //users

    Route::get('view_users', 'Admin\UserController@index');
    Route::post('changeActive', 'Admin\UserController@changeActive');
    Route::get('edit-user/{id}', 'Admin\UserController@edit');
    Route::post('user/update', 'Admin\UserController@update');

});


Route::group(['middleware' => ['auth']], function () {


    Route::get('filterTask/{unit?}/{status?}', 'FilterTaskController@index');

    Route::get('filterTask_data', 'FilterTaskController@getData');

    Route::post('print', 'FilterTaskController@printResult');




    Route::get('task/create', [
        'uses' => 'TaskController@create',
        'as' => 'task.create'
    ]);

    Route::post('upload', 'DependencyUploadController@uploadFile');


    Route::get('cambiarPass', 'UserController@solicitarcambioPass');
    Route::post('cambiarPass', 'UserController@updatePass');
    Route::get('assign_profile_teamLeader', 'UserController@assignProfileToTeamLeader');

//    panel de usuario rutas
    Route::get('panelDeUsuario', 'UserController@panelUser');
    Route::get('unit-init', 'UserController@controlUnitInit');
    Route::post('unit-init', 'UserController@saveUnit');

    // Tasks

    Route::get('task/create-selector', "TaskController@createSelector");
    Route::get('tasks', 'TaskController@index');
    Route::get('tasks/unit/{unit}/show', 'TaskController@getUnit');
    Route::get('tasks/status/{status}/unit/{unit}/show', 'TaskController@getStatus');
    Route::post('tasks/assign-pipeline','TaskController@assignPipeline');
    Route::get('tasks/uninitiated', 'TaskController@indexUninitiated');
    Route::get('tasks/in-progress', 'TaskController@indexInProgress');

    //tareas por perfil
//    Route::get('tasks/byProfile/{statu}', 'TaskController@viewTaskByProfile');
    Route::get('tasks/selectbyProfile', 'TaskController@selectTaskByProfile');
    Route::post('tasks/selectbyProfile', 'TaskController@selectTaskByProfile');



    //cambiar pipeline de tarea
    Route::post('tasks/update-pipeline',"TaskController@updatePipeline");

    //

    //Cambiar perfil de una tarea
    Route::post('tasks/change-profile-task', 'TaskController@changeProfileTask');

    // Extraigo los Attach de cada tarea (Ajax)

    Route::post('tasks/getAttachTask','TaskController@getAttachTask'); 

    // Comparto un Attach a una tarea 

    Route::post('tasks/{id}/combinateAttachtask', 'TaskController@combinateAttachtask');

    Route::get('mytasks', 'TaskController@getMyTasks');
    Route::get('tasks/{id}/show', 'TaskController@show');
    Route::get('tasks/{id}/unit/{unit}/show', 'TaskController@show');

    // Traigo por Ajax todos los Attach

    Route::post('tasks/getAttachByTask', 'TaskController@getAttachByTask');

    // Route::get('mytasks/task', 'TaskController@getTypeTasks');
    Route::post('mytasks', 'TaskController@getMyTasks');

    Route::post('store/coverage', 'TaskController@storeFormCoverage');

    Route::post('listaDeTareas', 'TaskController@mostrarNotificaciones');
    Route::get('listaDeTareas', 'TaskController@mostrarNotificaciones');//falta terminar

    Route::post('tasks/form_edit_Task', 'TaskController@editTaskTL');

    //notifications
    Route::get('notifications', 'NotificationsController@index');
    Route::get('notifications/read', 'NotificationsController@getNotificationsRead');
    Route::get('notifications/archivadas', 'NotificationsController@getNotificationsArchivadas');
    Route::get('notifications/inactividad', 'NotificationsController@getNotificationsInactivas');
    View::composer('shared.nav', function ($view) {
        $view->with('noti', Notifications::getNotRead());
    });

    //cantidad de notificaciones no leídas en el title
    View::composer('layouts.app', function ($view) {
        $view->with('noti', Notifications::getNotRead());
    });

    Route::post('notificationsArchived', 'NotificationsController@notificationsArchived');
    Route::post('notificationsTodosleidos', 'NotificationsController@marcarLeidos');
    Route::post('marcarLeido','NotificationsController@markRead');

    Route::post('notification/select','NotificationsController@select');
    Route::post('notifications/setRead', 'NotificationsController@setToReadSelect');

    //search
    Route::get('search', 'SearchController@search');
    Route::post('search', 'SearchController@search');
    Route::post('search/notificaciones', 'NotificationsController@search');


    //task Team Leader
    Route::get('tasks/teamLeader/{profile?}/{taskdata?}/{task?}/{unit?}', 'TaskController@createTaskTL');
    Route::post('/tasks/teamLeader/form', 'TaskController@storeFormTeamLeader');
    Route::get('tasks/{id}/createTask', 'TaskController@show');


    //  Download desde Tarea 

    Route::get('tasks/{id}/download', 'TaskController@taskDownload');
    Route::get('subtasks/{id}/download', 'SubtasksController@subtaskDownload');
    Route::get('download/{id}', 'TaskController@downloadFile');


    Route::post('task/publish-draft', 'TaskController@publishDraft');
    Route::post('tasks/move-to-task', 'TaskController@moveTaskToUnit');
    Route::post('tasks/update-status', 'TaskController@updateStatus');



    //  Get Old Attach

    Route::post('tasks/getoldattach', 'TaskController@getOldAttach');


    //tasktags
    Route::post('taskTag', 'TagController@store');
    Route::post('subtaskTag', 'TagController@store');
    Route::post('untag','TagController@unTagUser');


    //subtasks
    Route::get('subtasks', 'SubtasksController@index');
    Route::get('subtasks/{id}/show', 'SubtasksController@show');
    Route::post('subtasks/update-status', 'SubtasksController@updateStatus');
    Route::post('subtasks/store', 'SubtasksController@store');
    //    Route::get('subtasks/{id}/show', 'SubtasksController@etiquetarUsuarios');

    // Vincular archivos de task en subtask
    Route::post('subtasks/{id}/addsubtask', 'SubtasksController@addsubtaskAttach');

    // Eliminar Attach de la subtarea
    Route::post('subtasks/{id}/deleteAttachsubtask', 'SubtasksController@deleteAttachsubtask');

    // Entregar el archivo a la tarea
    Route::post('subtasks/{id}/deliverAttachsubtask', 'SubtasksController@deliverAttachsubtask');




    // Eliminar Attach de la tarea
    Route::post('tasks/{id}/deleteAttachtask', 'TaskController@deleteAttachtask');

    //Entregar Attach de la tarea
    Route::post('tasks/{id}/deliverAttachtask', 'TaskController@deliverAttachtask');

    // Route::get('/home', 'HomeController@index')->name('home');

    View::composer('shared.globalstyles', function ($view) {
        $view->with('units', App\Unit::all());
    });

    //Route::get('home', 'TaskController@clientHome');
    Route::get('home/{status?}', 'TaskController@clientHome');
    Route::get('home/1', ['uses'=>'TaskController@clientHome','as'=>'redirectHome']);

//    Route::get('home/{status?}/{page}', 'TaskController@clientHome')->where(['status' => '[0-9]+', 'page' => '[0-9]+']);
//    Route::get('home/{status?}', function ($status) {
//        return redirect('/home/'.$status.'/1');})->where('status','[0-9]+');

    Route::post('home/select-taskdata', 'TaskController@selectTaskdata');



    //rutas a Profile
    Route::get('profiles', 'ProfileController@index');
    Route::get('profile/create/{dir?}', 'ProfileController@create');
    Route::get('profile/{id}/edit', 'ProfileController@edit');
    Route::post('profile/store', 'ProfileController@store');
    Route::post('profile/update', 'ProfileController@update');
    Route::post('profile/delete', 'ProfileController@delete');
    Route::post('profile/removeinvited','ProfileController@removeinvited');



//    foreach (TaskForm::All() as $form){
//        Route::get('forms/'.$form->slug, 'TaskController@createForm'.ucfirst($form->slug));
//    Route::get('forms/'.$form->slug.'/{id}/edit', 'TaskController@editForm'.ucfirst($form->slug));
//    Route::post('forms/store/'.$form->slug, 'TaskController@storeForm'.ucfirst($form->slug));
//    Route::post('forms/update/'.$form->slug, 'TaskController@updateForm'.ucfirst($form->slug));
//    Route::post('forms/'.$form->slug.'/delete', 'TaskController@deleteForm'.ucfirst($form->slug));
//    }

//    rutas a Form Web
    Route::get('forms/web', 'TaskController@createFormWeb');
    Route::get('forms/web/{id}/edit', 'TaskController@editFormWeb');
    Route::post('forms/store/web', 'TaskController@storeFormWeb');
    Route::post('forms/update/web', 'TaskController@updateFormWeb');
    Route::post('forms/web/delete', 'TaskController@deleteFormWeb');

    //rutas a Form Email
    Route::get('forms/email', 'TaskController@createFormEmail');
    Route::get('forms/email/{id}/edit', 'TaskController@editFormEmail');
    Route::post('forms/store/email', 'TaskController@storeFormEmail');
    Route::post('forms/update/email', 'TaskController@updateFormEmail');
    Route::post('forms/email/delete', 'TaskController@deleteFormEmail');

    //rutas a Form Event
    Route::get('forms/event', 'TaskController@createFormEvent');
    Route::get('forms/event/{id}/edit', 'TaskController@editFormEvent');
    Route::post('forms/store/event', 'TaskController@storeFormEvent');
    Route::post('forms/update/event', 'TaskController@updateFormEvent');
    Route::post('forms/event/delete', 'TaskController@deleteFormEvent');

    //rutas a Form Other
    Route::get('forms/other', 'TaskController@createFormOther');
    Route::get('forms/other/{id}/edit', 'TaskController@editFormOther');
    Route::post('forms/store/other', 'TaskController@storeFormOther');
    Route::post('forms/update/other', 'TaskController@updateFormOther');
    Route::post('forms/other/delete', 'TaskController@deleteFormOther');

    //rutas a Form Evento
    Route::get('forms/evento', 'TaskController@createFormEvento');
    Route::get('forms/evento/{id}/edit', 'TaskController@editFormEvento');
    Route::post('forms/store/evento', 'TaskController@storeFormEvento');
    Route::post('forms/update/evento', 'TaskController@updateFormEvento');
    Route::post('forms/evento/delete', 'TaskController@deleteFormEvento');



    Route::get('otask/{id}/show', 'TaskController@clientShow');

//    Route::get('test', 'TestController@test');
    Route::get('instructive', 'HomeController@instructive');


    Route::get('form', function () {
        return view('form');
    });

    Route::post('deadline','TaskController@changeDeadline');
    /**
     * selecciona los títulos de tareas del perfil seleccionado
     */
    Route::get('taskdata', function (Illuminate\Http\Request $request) {


        if ($request->term){
            $tasks = Task::where('profile_id', '=', $request->profile_id)->where('title','like','%'.$request->term.'%')->get();

        }else{
            $tasks = Task::where('profile_id', '=', $request->profile_id)->get();

        }


        $taskdata = [];
        $taskdata[] = ['id' => 999999, 'text' => "Esta tarea no tiene otra tarea relacionada"];

        if (is_countable($tasks)){
            foreach ($tasks as  $t) {

                $taskdata[] = ['id' => $t->taskdata->id, 'text' => $t->taskdata->title];
            }
        }else {


        }

        $nuevo = array();

        foreach ($taskdata as $key => $value) {

            if(empty($nuevo[$value['id']])){
                $nuevo[$value['id']] = $value;
            }

        }

        return \Response::json(array_values($nuevo));
    });

    /**
     */

    Route::get('put', function () {
        $ble = Storage::cloud()->put('test.txt', 'Hello World');
        var_dump($ble);
        return 'File was saved to Google Drive';
    });

    Route::get('list', function () {
        $dir = '/';
        $recursive = false; // Get subdirectories also?
        $contents = collect(Storage::cloud()->listContents($dir, $recursive));
        //return $contents->where('type', '=', 'dir'); // directories
        return $contents->where('type', '=', 'file'); // files
    });

    Route::get('get-by-name', function () {
        $dir = '/';
        $name = 'test';
        $ext = 'txt';
        $recursive = false; // Get subdirectories also?
        $contents = collect(Storage::cloud()->listContents($dir, $recursive));
        return $contents
            ->where('type', '=', 'file')
            ->where('filename', '=', $name)
            ->where('extension', '=', $ext)
            ->first(); // there can be duplicate file names!
    });

    Route::get('get', function () {
        $filename = 'test.txt';
        $dir = '/';
        $recursive = false; // Get subdirectories also?
        $contents = collect(Storage::cloud()->listContents($dir, $recursive));
        $file = $contents
            ->where('type', '=', 'file')
            ->where('filename', '=', pathinfo($filename, PATHINFO_FILENAME))
            ->where('extension', '=', pathinfo($filename, PATHINFO_EXTENSION))
            ->first(); // there can be duplicate file names!
        //return $file; // array with file info
        $rawData = Storage::cloud()->get($file['path']);
        return response($rawData, 200)
            ->header('ContentType', $file['mimetype'])
            ->header('Content-Disposition', "attachment; filename='$filename'");
    });


    Route::get('create-dir', function () {
        Storage::cloud()->makeDirectory('Test Dir');
        return 'Directory was created in Google Drive';
    });


    Route::get('put-in-dir', function () {
        $dir = '/';
        $recursive = false; // Get subdirectories also?
        $contents = collect(Storage::cloud()->listContents($dir, $recursive));
        $dir = $contents->where('type', '=', 'dir')
            ->where('filename', '=', 'Test Dir')
            ->first(); // There could be duplicate directory names!
        if (!$dir) {
            return 'Directory does not exist!';
        }
        Storage::cloud()->put($dir['path'] . '/test.txt', 'Hello World');
        return 'File was created in the sub directory in Google Drive';
    });


    Route::get('newest', function () {
        $filename = 'test.txt';
        $filename = 'test.txt';
        Storage::cloud()->put($filename, \Carbon\Carbon::now()->toDateTimeString());
        $dir = '/';
        $recursive = false; // Get subdirectories also?
        $file = collect(Storage::cloud()->listContents($dir, $recursive))
            ->where('type', '=', 'file')
            ->where('filename', '=', pathinfo($filename, PATHINFO_FILENAME))
            ->where('extension', '=', pathinfo($filename, PATHINFO_EXTENSION))
            ->sortBy('timestamp')
            ->last();
        return Storage::cloud()->get($file['path']);
    });

    Route::get('phpinfo', function () {
        phpinfo();
    });


    Route::get('unique-revision-pipelines', function () {


        $pipelines = Pipeline::all();

        foreach ($pipelines as $p) {
            $mt = md5(microtime().rand());
            $p->latestRevision = $mt;

            $p->save();

            DB::table('unit_pipeline')->where('pipeline_id', $p->id)->update(['revision' => $mt]);

        }


    });

    Route::get('phpinfo',function(){
        echo phpinfo();
    });

    Route::post('alternative-upload','UploadController@alternativeUpload');

    Route::get('tasks/{id}/download/pdf', function ($id) {
        require(public_path().'/vendor/fpdf/fpdf.php');
        $task = Task::where('id', '=', $id)->first();
        $taskdata = \App\Taskdata::where('id', '=', $task->taskdata_id)->first();

        $pdf = new FPDF();
        header('Content-type: application/pdf');
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',14);
        $pdf->Cell(0,10,utf8_decode('PROTOCOLO DE SOLICITUD PARA EVENTOS ONLINE 2020'),0,1,'C');

        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(0,10,utf8_decode('El presente documento es imprescindible para autorización de cualquier actividad online de la Comunidad'),0,1,'C');
        $pdf->Cell(0,10,utf8_decode('UNTREF y su difusión en los canales oficiales de Comunicación Institucional'),0,1,'C');

        $pdf->SetFont('Arial','',12);
        $pdf->Cell(0,10,utf8_decode('Para la gestión del evento y la transmisión necesitamos saber:'),0,1,'L');

        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(0,10,utf8_decode('SOLICITANTE'),0,1,'L');

        $pdf->SetFont('Arial','',12);
        $pdf->Cell(0,10,utf8_decode('Fecha de la solicitud: '. Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $task->created_at)->format('d-m-Y')),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Área: '.$task->profile->area),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Responsable: '.$task->profile->name.' '.$task->profile->surname),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Nombre del solicitante: '.$task->createdBy->name.' '.$task->createdBy->surname),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Contacto: '.$task->createdBy->email),0,1,'L');

        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(0,10,utf8_decode('ACTIVIDAD'),0,1,'L');

        $pdf->SetFont('Arial','',12);
        $pdf->Cell(0,10,utf8_decode('Nombre de la actividad: '.$taskdata->name_activity),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Tipo de actividad solicitada/Especificar  cual de estas marcado con X: '),0,1,'L');

        $type1 = '';
        $type2 = '';
        $type3 = '';
        $type4 = '';
        if (in_array(1,$taskdata->event_type_activity)){
            $type1 = 'x';
        }
        if (in_array(2,$taskdata->event_type_activity)){
            $type2 = 'x';
        }
        if (in_array(3,$taskdata->event_type_activity)){
            $type3 = 'x';
        }
        if (in_array(4,$taskdata->event_type_activity)){
            $type4 = 'x';
        }

        $pdf->Cell(0,10,utf8_decode('Streaming desde la web de UNTREF ( '.$type1.' )'),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Streaming Canal UNTREF de YouTube ( '.$type2.' )'),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Streaming en canal UNTREF de Youtube desde una cuenta personal ( '.$type3.' ) '),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Sala Zoom UNTREF (Sin Streaming) ( '.$type4.' )'),0,1,'L');

        $pdf->Cell(0,10,utf8_decode('Fecha/s: '.Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $taskdata->event_date_format)->format('d-m-Y')),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Horario/s: '.$taskdata->event_time),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Idioma del evento: Español (indicar si habrá otros idiomas) '.$taskdata->event_language),0,1,'L');

        $pdf->Cell(0,10,utf8_decode('*No podemos realizar transmisión online desde la plataforma de Google Meet'),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('*Si no necesitas ninguna transmisión de la UNTREF pero solo deseas la difusión de tu evento,'),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('aclarar aquí, por favor, para encaminar su pedido a Comunicación Institucional'),0,1,'L');


        $pdf->Cell(0,10,utf8_decode('IMPORTANTE: UNA VEZ CONFIRMADA LA APROBACIÓN DE LA ACTIVIDAD POR PARTE DE LAS '),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('AUTORIDADES SE DARÁ CURSO AL PEDIDO. '),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('NO SE TOMARAN PEDIDOS CON MENOS DE 15 DÍAS HÁBILES DE ANTICIPACIÓN  '),0,1,'L');
        $pdf->Cell(0,10,utf8_decode('Y LA FECHA Y EL HORARIO QUEDA SUJETA A LA DISPOSICIÓN DEL CANAL DE YOUTUBE.'),0,1,'L');


        ob_get_clean();
        $pdf->Output();
        exit;
    });
});

Route::get('notifications/mail', 'NotificationsMailController@sendNotificationMail');
