<?php

namespace App\Http\Controllers;

use App\Attachment;
use App\Subtask;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Events\CreateAttach;
use App\Task;

class UploadController extends Controller
{
    /**
     * Handles the file upload
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws UploadMissingFileException
     */
    public function upload(Request $request)
    {

        // create the file receiver
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
        // check if the upload is success
        if ($receiver->isUploaded()) {
            // receive the file
            $save = $receiver->receive();
            // check if the upload has finished (in chunk mode it will send smaller files)
            if ($save->isFinished()) {
                // save the file and return any response you need
                return $this->saveFile($save->getFile());
            } else {
                // we are in chunk mode, lets send the current progress
                /** @var AbstractHandler $handler */
                $handler = $save->handler();
                return response()->json([
                    "done" => $handler->getPercentageDone(),
                ]);
            }
        } else {
            throw new UploadMissingFileException();
        }
    }

    /**
     * Saves the file
     *
     * @param UploadedFile $file
     * @return \Illuminate\Http\JsonResponse
     */
    protected function saveFile(UploadedFile $file, $typeTask = null)
    {

        $fileName = $this->createFilename($file);
        $mime = str_replace('/', '-', $file->getMimeType());
        $filePath = "upload/";
        $file->move(public_path("/uploads"), $fileName);
        $fileOriginalName = $file->getClientOriginalName();


        if (!empty($typeTask->all())) {

            /**
             * Save attachment in DB
             */

            $attachments = new Attachment();
            $attachments->filename = $fileName;
            $attachments->path = $filePath;
            $attachments->original_name = $fileOriginalName;
            $attachments->user_id = Auth::user()->id;
            $attachments->mimetype = $mime;

            $attachments->subtask_id = null;

            $arrayTypeTask = array("id_subtask" => $typeTask->id_subtask, "id_task" => $typeTask->id_task);

            if ($typeTask->is_subtask == "true") {

                $attachments->task_id = null;
                $attachments->save();

                event(new CreateAttach($attachments, $arrayTypeTask));//crea un evento cuando se sube un archivo


            } elseif ($typeTask->id_task != "undefined") {
                $task = Task::find($typeTask->id_task);

                if ($task->unit_id) {
                    $attachments->task_id = null;  //   tarea creada
                    $attachments->save();
                    event(new CreateAttach($attachments, $arrayTypeTask));//crea un evento cuando se sube un archivo
                } else {  // Este caso es cuando es borrador (edicion)

                    $attachments->save();

                }

            } else {  // Este caso es cuando se crea una tarea nueva  (nuevo)

                $attachments->save();

            }

            /*
                            var_dump($typeTask);
                            exit;
            */

            // Nuevo actualiza tarea task


            if (($typeTask->is_subtask != "true") && ($typeTask->id_task != "undefined")) {

                $query = DB::table('attach_task')->insert(
                    ['attachment_id' => $attachments->id, 'task_id' => $typeTask->id_task, 'delivered_final' => 0]);


            }

            // Nuevo

            if ((!empty($typeTask->id_subtask)) && ($typeTask->id_subtask != "undefined")) {  // Subtarea creada

                $query = DB::table('attach_subtask')->insert(
                    ['attachment_id' => $attachments->id, 'subtask_id' => $typeTask->id_subtask]);


            }


            return response()->json([
                'path' => $filePath,
                'name' => $fileOriginalName,
                'mime_type' => $mime,
                'id' => $attachments->id,
                'filename' => $attachments->filename,
                'created_at' => date('d/m/Y')
            ]);
        }

    }

    public function alternativeUpload(Request $request)
    {


        if ($request->uploadfile) {


            $file = $request->uploadfile;
            $original_name = $file->getClientOriginalName();
            $extension = $file->extension();
            $filename = md5(rand()) . '.' . $extension;
            $mime = str_replace('/', '-', $file->getMimeType());
            $filePath = "upload/";


            $attachments = new Attachment();
            $attachments->filename = $filename;
            $attachments->path = $filePath;
            $attachments->original_name = $original_name;
            $attachments->user_id = Auth::user()->id;
            $attachments->mimetype = $mime;
            $attachments->save();


            // la siguente linea viene heredada de @saveFile, me parece mas fácil pasar el tipo por POST desde
            // la vista, y hacer el switch mas abajo


            $arrayTypeTask = array(
                "id_subtask" => $request->subtask_id ? $request->subtask_id : 'undefined',
                "id_task" => $request->task_id ? $request->task_id : 'undefined',);

            //crea un evento cuando se sube un archivo
            event(new CreateAttach($attachments, $arrayTypeTask));


            switch ($request->type) {
                case 'task':
                    $query = DB::table('attach_task')->insert(
                        ['attachment_id' => $attachments->id, 'task_id' => $request->task_id, 'delivered_final' => 0]);
                    break;
                case 'subtask':
                    $query = DB::table('attach_subtask')->insert(
                        ['attachment_id' => $attachments->id, 'task_id' => $request->subtask_id]);
                    break;
                default:
                    return;
            }


        }

//        var_dump($filename);
        \Storage::disk('uploads')->put( $filename ,\File::get($file));

        return redirect()->back()->with('message','success');





    }
    public function slugify($text)

    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);
        // trim
        $text = trim($text, '-');
        // remove duplicate -
        $text = preg_replace('~-+~', '-', $text);
        // lowercase
        $text = strtolower($text);
        if (empty($text)) {
            return 'n-a';
        }
        return $text;

    }


    /**
     * Create unique filename for uploaded file
     * @param UploadedFile $file
     * @return string
     */
    protected function createFilename(UploadedFile $file)
    {

        $slugFilename = $this->slugify($file->getClientOriginalName());
        $extension = $file->getClientOriginalExtension();
        //$filename = str_replace(".".$extension, "", $file->getClientOriginalName()); // Filename without extension
        //$filename .= "_" . md5(time()) . "." . $extension;
        $filename = $slugFilename . '-' . md5(time()) . "." . $extension;
        return $filename;
    }
}




