<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\TaskRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;

use App\User;
use App\Task;
use App\TaskFile;
use App\NotificationForward;
use App\Notification;
class TaskController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/tasks';
    /** View folder */
    private $viewDirectory= 'admin.tasks.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('tasks.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the tasks.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Task::orderBy('id', 'DESC');

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('name', 'LIKE', '%'.$request->name.'%');
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $tasks= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('tasks'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('tasks.store');
        $head = metaFields('tasks', 'add_new', getCurrentLocale()) ?? __('tasks.new');
        $users = User::whereNotIn('role_id',['5','6','4',])->get();

        return view( $this->viewDirectory.'form', compact('action', 'head','users') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param TaskRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(TaskRequest $request) :RedirectResponse
    { 
     
        $task= Task::create($request->except('user_id'));
        
       $noti =  Notification::create(['title'=>'رسالة من مدير النظام','description'=>$task->id,'type'=>'1']);
        $this->saveData($request, $task->id);
       foreach($request->user_id as $user){
           NotificationForward::create([
               'forward_id'=>$user,
               'notification_id'=>$noti->id,
               ]);
       }
       
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  Task  $task
     * @return View
     */
    public function edit(Task $task): View
    {
        $action= route('tasks.update', $task->id);
        $head = metaFields('tasks', 'edit', getCurrentLocale()) ?? __('tasks.edit');
        $users = User::whereNotIn('role_id',['5','6','4',])->get();
        $task_photos = TaskFile::where('task_id',$task->id)->where('type','0')->get();
        $task_files = TaskFile::where('task_id',$task->id)->where('type','1')->get();


        return view( $this->viewDirectory.'form', compact('task', 'action', 'head','users','task_photos','task_files') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  TaskRequest  $request
     * @param  Task  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(TaskRequest $request, Task $task) :RedirectResponse
    {
     
       
        $task->update($request->except('user_id'));
        TaskFile::where('task_id',$task->id)->where('type','0')->delete();
        $this->saveData($request, $task->id);
        

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }
    private function saveData(TaskRequest $request, int $task_id ):void
    {
        
        if ($request->has('images')){

            foreach ($request->images as $image) {
                $data=[
                    'file'=> $image,
                    'type'=>'0',
                    'task_id'=> $task_id,
                ];

                TaskFile::create($data);

            }
        }
      
       
            foreach($request->files as $row){
                foreach($row as $file){
               $file = $file['file'];
        $name=mt_rand(1000000, 9999999).time().'file-'.$task_id.'.'.$file->getClientOriginalExtension();
        $file->move(public_path('/uploads/files/'),$name);
        TaskFile::create([
            'file'=> '/uploads/files/'.$name,
            'type'=>'1',
            'task_id'=> $task_id,
            ]);
                }    
                }
        

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $user = Task::withTrashed()->find($id);
        if ($user) {
            if ($user->deleted_at) {
                $user->forceDelete();
            } else {
                $user->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Task::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Task::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $user = Task::withTrashed()->find($id);

        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $user = Task::whereIn('id', $request->ids)->onlyTrashed();
        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
