<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Contact;
use Illuminate\View\View;
use App\ContactDescription;
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\ContactRequest; // 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= moduleName('contacts', getCurrentLocale()) ?? __('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()
        ->join('contact_descriptions AS cd', 'contacts.id', 'cd.contact_id')
        ->join('languages', 'languages.id', 'cd.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['cd.title', 'contacts.*']);

        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->title) {
            $query->where('cd.title', 'LIKE', '%'.$request->title.'%');
        }

        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 contact.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('contacts.store');
        $head = metaFields('contacts', 'add_new', getCurrentLocale()) ?? __('contacts.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * Store a newly created contact in storage.
     * @param ContactRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ContactRequest $request) :RedirectResponse
    {
        $contact = Contact::create();

        // Insert Description
        $this->saveData( $request, $contact->id );

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

    /**
     * Show the form for editing the specified contact.
     *
     * @param  Contact  $contact
     * @return View
     */
    public function edit(Contact $contact) :View
    {
        $action= route('contacts.update', $contact->id);
        $head = metaFields('contacts', 'edit', getCurrentLocale()) ?? __('contacts.edit');

        $query = ContactDescription::where('contact_id', $contact->id)
        ->join('languages', 'languages.id', 'contact_descriptions.language_id')
        ->select(['contact_descriptions.*', 'languages.local']);

        $contactDescription= $query->get();

        foreach ($contactDescription as $row) {
            $contact[$row->local]= $row;
        }

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

    /**
     * Update the specified contact in storage.
     * @param ContactRequest $request
     * @param Contact $contact
     * @return RedirectResponse
     */
    public function update(ContactRequest $request, Contact $contact) :RedirectResponse
    {
        // Update the "updated_at" column only
        $contact->touch();

        // Delete old description
        ContactDescription::where('contact_id', $contact->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param ContactRequest $request
     * @param int $contactId
     * @return void
     */

     private function saveData(ContactRequest $request, int $contactId ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'contact_id'=> $contactId,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            ContactDescription::create($data);
        }
     }

    /**
     * Remove the specified contact from storage.
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $contact= Contact::withTrashed()->find($id);
        if ($contact) {
            if ($contact->deleted_at) {
                $contact->forceDelete();
            } else {
                $contact->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 contact from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $contact= Contact::withTrashed()->find($id);
        if ($contact) {
            $contact->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')]);
    }
}
