<?php

namespace Modules\Notification\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Notification\Interfaces\NotificationRepositoryInterface;
use Modules\Notification\Models\Alert;
use Modules\Notification\Models\AlertDescription;
use Modules\Notification\Models\Notification;
use Modules\Notification\Models\NotificationDescription;
use Carbon\Carbon;

class NotificationRepository implements NotificationRepositoryInterface
{
    
    public function getNotifications(Request $request)
    {
        $query = Notification::orderBy('id', 'DESC')
            ->join('notification_descriptions AS sd', 'notifications.id', 'sd.notification_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title','sd.description', 'notifications.*']);
        if ($request->user_id)
        {
            $query->where('notifications.user_id',$request->user_id);
        }

        if ($request->title) {
            $query->where('sd.title', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->date_from) {
            $query->whereDate('notifications.created_at', '>=', $request->date_from);
        }

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


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

        if ($request->paginate ?? null) {
            $notifications= $query->paginate(50);
        }else{
            $notifications=$query->get();
        }

        return $notifications;
    }
    public function get(Request $request)
    {
        $query = Alert::orderBy('id', 'DESC')
            ->join('alert_descriptions AS sd', 'alerts.id', 'sd.alert_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title','sd.description', 'alerts.*']);
        if ($request->user_id)
        {
            $query->where('alerts.user_id',$request->user_id);
        }

        if ($request->title) {
            $query->where('sd.title', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->date_from) {
            $query->whereDate('alerts.created_at', '>=', $request->date_from);
        }

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


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

        if ($request->paginate ?? null) {
            $alerts= $query->paginate(50);
        }else{
            $alerts=$query->cursor();
        }

        return $alerts;
    }

    public function getItem(Notification $notification)
    {
        $query = NotificationDescription::where('notification_id', $notification->id)
            ->join('languages', 'languages.id', 'notification_descriptions.language_id')
            ->select(['notification_descriptions.*', 'languages.local']);

        $notificationDescription= $query->get();
        // dd($notificationDescription->toArray());
        foreach ($notificationDescription as $row) {
            $notification[$row->local]= $row;
        }
        return $notification ;
    }

    //
    public function save(Request $request, ?Notification $notification): void
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$notification) {
            $notification = Notification::create($data);
        } else {
            $notification->update($data);
            NotificationDescription::where('notification_id', $notification->id)->delete();
        }
        $this->saveData( $request, $notification->id );
    }

    private function saveData(Request $request, int $notification_id ) :void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'notification_id'=> $notification_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];

            NotificationDescription::create($data);
        }
    }
    public function saveAlert(Request $request, ?Alert $notification): void
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$notification) {
            $notification = Alert::create($data);
        } else {
            $notification->update($data);
            AlertDescription::where('alert_id', $notification->id)->delete();
        }
        $this->saveAlertSaveData( $request, $notification->id );
    }

    private function saveAlertSaveData(Request $request, int $notification_id ) :void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'alert_id'=> $notification_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];

            AlertDescription::create($data);
        }
    }
    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $notification= Notification::withTrashed()->find($id);
        if ($notification) {
            if ($notification->deleted_at) {
                $notification->forceDelete();
            } else {
                $notification->delete();
            }
            return [ ['message'=> __('dashboard.deletedDone')]];
        } else{
            return [ ['message'=> __('dashboard.noResult')], 400];
        }
    }

    /**
     * Remove several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        $ids= $request->ids;
        $query= Notification::whereIn('id', $ids);
        if ($request->force) {
            $deleted= $query->onlyTrashed()->forceDelete();
        } else {
            $deleted= $query->delete();
        }
        if($deleted){
            return [['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

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

    }

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

    public function deleteAllUser(Request $request):void
    {
        Notification::where('user_id',$request->user_id)->delete();
    }
    public function readNotification(Request $request):void
    {
        Notification::where('user_id', $request->user_id)
        ->update(['read_at' => Carbon::now()]);
    }
    
}
