<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Report;
use Illuminate\View\View;
use App\Reason;
use App\Channel;
use App\User;
use App\AboutDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\AboutRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ReportController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/reports';
    /** View folder */
    private $viewDirectory= 'admin.reports.';

    /**
     * Display a listing of the reports.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('reports.head');
        $request= $request->toArray();
        $channel_ids = Report::pluck('channel_id');
        $target_ids = Channel::withTrashed()->whereIn('id',$channel_ids)->pluck('target_id');
        $targets = User::find($target_ids);
        $user_ids = Report::pluck('user_id');
       
        $users = User::withTrashed()->get();
        $channels = Channel::withTrashed()->find($channel_ids);
        $targets = Channel::withTrashed()->find($channel_ids);
        return view($this->viewDirectory.'index',compact('title','users','channels','targets'));
    }

    /**
     * return data of the reports.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Report::latest();

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

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

        if ($request->reason_id) {
            $query->where('reason_id', $request->reason_id);
        }
         if ($request->user_id) {
            $query->where('user_id', $request->user_id);
        }
         if ($request->product_id) {
            $query->where('product_id', $request->product_id);
        }
        if ($request->role) {
            $users_ids = User::where('role',$request->role)->pluck('id'); 
            
            $query->whereIn('user_id', $users_ids);
        }
        

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

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

    /**
     * Show the form for creating a new About.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('reports.store');
        $head= __('reports.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * Store a newly created About in storage.
     * @param AboutRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(AboutRequest $request) :RedirectResponse
    {
       

        $about = Report::create();
        $about->update([
                'video' => parseExternalVideoLink($request->video)['url'],
            ]);  
       
        // Insert Description
        $this->saveData( $request, $about->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified About.
     *
     * @param  About  $about
     * @return View
     */
    public function edit(Report $report) :View
    {
        $action= route('reports.show', $report->id);
        $head = __('reports.show');
       

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

    /**
     * Update the specified About in storage.
     * @param AboutRequest $request
     * @param About $about
     * @return RedirectResponse|Redirector
     */
    public function update(AboutRequest $request, About $about) :RedirectResponse
    {
        // Update the "updated_at" column only
       
     	$about->update([
                'video' => parseExternalVideoLink($request->video)['url'],
            ]);  

        // Delete old description
        AboutDescription::where('about_id', $about->id)->delete();

        // Insert new description
        $this->saveData( $request, $about->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param AboutRequest $request
     * @param int $about_id
     * @return void
     */

     private function saveData(AboutRequest $request, int $about_id ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'about_id'=> $about_id,
                'language_id'=> $lang->id,
                'description'=> $requestData['description_'.$lang->local],
                'vission'=> $requestData['vission_'.$lang->local],
                'mission'=> $requestData['mission_'.$lang->local],
                'goal'=> $requestData['goal_'.$lang->local],
                
            ];

            AboutDescription::create($data);
        }

     }

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

    /**
     * Remove several reports by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Report::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Report::whereIn('id', $ids)->delete();
        }

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

    /**
     * Restore the specified About from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $about= Report::withTrashed()->find($id);
        if ($about) {
            $about->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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