<?php

namespace App\Http\Controllers\Admin;

use App\Article;
use App\Category;
use App\CategoryDescription;
use Exception;
use App\MailList;
use App\Newsletter;
use Illuminate\Contracts\View\Factory;
use Illuminate\View\View;
use App\Jobs\NewsletterJob;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\NewsletterRequest;

class NewsletterController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/newsletters';
    /** View folder */
    private $viewDirectory = 'admin.newsletters.';


    private $mailListViewDirectory = 'admin.newsletters.mail_lists.';

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

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

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

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

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

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

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

        $newsletters= $query->paginate(10);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('newsletters.store');
        $head = metaFields('newsletters', 'new', getCurrentLocale()) ?? __('newsletters.new');
        $title = $head;
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param NewsletterRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(NewsletterRequest $request) :RedirectResponse
    {
        $this->saveData($request);
        return redirect($this->redirectSuccessPath)->with('message', __('newsletters.email_success'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Newsletter $newsletter
     * @return View
     */
    public function edit(Newsletter $newsletter) :View
    {
        $action= route('newsletters.update', $newsletter->id);
        return view( $this->viewDirectory.'form', compact('newsletter', 'action') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param NewsletterRequest $request
     * @return RedirectResponse|Redirector
     */
    public function update(NewsletterRequest $request) :RedirectResponse
    {
        $this->saveData( $request);
        return redirect($this->redirectSuccessPath)->with('message', __('newsletters.email_success'));
    }

    /**
     * Handle Save form data
     *
     * @param NewsletterRequest $request
     * @return void
     */

    private function saveData(NewsletterRequest $request ):void
    {
        $data = [];
        $categories = [];

        if($request->categories != null){
            $articles = Article::join('article_descriptions', 'article_descriptions.article_id', 'articles.id')
                ->select(['article_descriptions.title', 'article_descriptions.description'])
                ->whereIn('category_id', $request->categories)
                ->where('language_id', currentLanguage()->id)
                ->orderByDesc('articles.id')
                ->take(20)
                ->cursor()->toArray();
            $data['articles'] = $articles;

            $categories = CategoryDescription::whereIn('category_id', $request->categories)
                ->where('language_id', currentLanguage()->id)->pluck('name')->toArray();

            $categories = json_encode($categories);

        }

        // Create mail list
        MailList::create([
            'send_to' => $request->email,
            'subject' => $request->subject,
            'message' => $request->message,
            'categories' => $categories ? $categories : null
        ]);

        if ($request->email == 'all') {
            $email = Newsletter::pluck('email')->toArray();
            $request['email'] = $email;
        }

        $data['msg'] = $request->message;

        $data = array_merge($data, $request->all(['email', 'subject']));


        if (is_array($data['email'])){
            foreach ($data['email'] as $email) {
                $this->dispatch(new NewsletterJob($data, $this->viewDirectory.'email'));
            }

        } else {
            $this->dispatch(new NewsletterJob($data, $this->viewDirectory.'email'));

        }

    }

    /**
     * return data of the newsletters mail list.
     *
     * @param Request $request
     * @return View
     */
    public function mailsListGrid(Request $request) :View
    {
        $query = MailList::latest();

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

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

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

        $mailLists= $query->paginate(10);

        return view($this->mailListViewDirectory.'grid',compact('mailLists'));
    }


    /**
     * Display a listing of the mail list.
     * @return View
     */
    public function mailsList() :View
    {
        $title= __('newsletters.mail_list');
        $mailList = MailList::cursor();
        return view($this->mailListViewDirectory.'index', compact('title'));
    }

    /**
     * Display mail list information by id
     * @param $id
     * @return Factory|View
     */
    public function mailsListMore($id) :View
    {
        $mailList = MailList::findOrFail($id);
        $categories = json_decode($mailList->categories);
        $head = __('newsletters.mail_list_more');
        return view($this->mailListViewDirectory.'more', compact(['head', 'mailList', 'categories']));
    }


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

        if ($newsletter){
            $newsletter->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
    {
        $newsletters = Newsletter::whereIn('id', $request->ids)->onlyTrashed();
        if ($newsletters){
            $newsletters->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
