<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Channel;
use App\ChannelFile;
use App\User;
use App\Type;
use App\Category;
use Illuminate\View\View;
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 ChannelController extends Controller
{

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

    /**
     * Display a listing of the channels.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $members = User::where('role','member')->get();
        $consults = User::where('role','consult')->get();
        $types = Type::cursor();
        $categories = Category::cursor();
        $title= __('channels.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title','members','consults','types','categories'));
    }

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

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

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

        if ($request->message) {
            $query->where('message', 'LIKE', '%'.$request->message.'%');
        }
        if ($request->name) {
            $query->where('name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->user) {
            $query->where('user_id', $request->user);
        }
        if ($request->target) {
            $query->where('target_id',$request->target);
        }
        if ($request->type_id) {
            $query->where('type_id',$request->type_id);
        }
        
        if ($request->category_id) {
            $query->where('category_id',$request->category_id);
        }
         if ($request->stating) {
            $query->where('status', $request->stating);
        }

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

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

    /**
     * Show the form for creating a new About.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('channels.store');
        $head= __('channels.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 = Channel::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(Channel $channel) :View
    {
        $action= route('channels.update', $channel->id);
        $head = __('channels.head');
        $files = ChannelFile::where('channel_id',$channel->id)->get();
       

        return view( $this->viewDirectory.'form', compact('channel', 'action','head','files') );
    }
    public function show($id)
    {
        $channel = ChannelFile::find($id);
        $arr = explode('.',$channel->file);
        
        if($arr[1] == 'pdf'){
             $file= public_path(). $channel->file;
         $headers = array(
              'Content-Type: application/pdf',
            );
return \Response::download($file, 'File.pdf', $headers);
        }
        else{
          $filepath = public_path('').$channel->file;
return \Response::download($filepath);
        }
           
    }

    /**
     * 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= Channel::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 channels by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Channel::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Channel::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= Channel::withTrashed()->find($id);
        if ($about) {
            $about->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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