<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Contact;
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 ContactController extends Controller
{

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

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

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

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

        if ($request->date_to) {
            $query->whereDate('contacts.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->email) {
            $query->where('email', 'LIKE', '%'.$request->email.'%');
        }
        if ($request->phone) {
            $query->where('phone', 'LIKE', '%'.$request->phone.'%');
        }
         if ($request->subject) {
            $query->where('subject', 'LIKE', '%'.$request->subject.'%');
        }

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

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

    /**
     * Show the form for creating a new About.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('contacts.store');
        $head= __('contacts.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 = Contact::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(Contact $contact) :View
    {
        $action= route('contacts.update', $contact->id);
        $head = __('contacts.head');
       

        return view( $this->viewDirectory.'form', compact('contact', '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= Contact::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 contacts by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

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

    }

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