<?php

namespace Modules\Notification\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Notification\Interfaces\ManagementNotificationRepositoryInterface;
use Modules\Notification\Interfaces\NotificationRepositoryInterface;
use Modules\Notification\Models\ManagementNotification;
use Modules\Notification\Models\ManagementNotificationDescription;
use Modules\Notification\Models\Notification;
use Modules\Notification\Models\NotificationDescription;

class ManagementNotificationRepository implements ManagementNotificationRepositoryInterface
{
    public function get(Request $request)
    {
        $query = ManagementNotification::orderBy('id', 'DESC')
            ->join('management_notification_descriptions AS sd', 'management_notifications.id', 'sd.management_notification_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title','sd.description', 'management_notifications.*']);

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

        if ($request->date_to) {
            $query->whereDate('management_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->cursor();
        }

        return $notifications;
    }


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

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

            ManagementNotificationDescription::create($data);
        }
    }

}
