<?php

namespace App\Http\Controllers\ticket;

use App\Helpers\Helper;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class NotificationController extends Controller
{
    use Helper;

    public function index()
    {
        try {


            $keyword = request()->input('keyword');
            $date_from = request()->input('date_from');
            $date_to = request()->input('date_to');

            $notification = Notification::when($keyword, function ($query) use ($keyword) {
                $query->where('title', 'Like', "%$keyword%");
            })
                ->when($date_from, function ($query) use ($date_from){
                    $query->whereDate('created_at','>=',$date_from);
                })
                ->when($date_to, function ($query) use ($date_to){
                    $query->whereDate('created_at','<=',$date_to);
                })
                ->where('send_to', auth()->user()->id)
                ->orderBy('id', 'DESC')
                ->paginate(request()->input('perPage'));


                return returnData(2000, $notification);
        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), $exception->getMessage());
        }
    }


    public function store(Request $request)
    {


        try {
            DB::beginTransaction();

            $pageNo = $request->page && (int)$request->page > 0 ? $request->page : 1;
            $take = 5;
            $skip = ($pageNo - 1) * $take;

            $data['notification'] = Notification::orderBy('id', 'DESC')
                ->where('status', 1)
                ->where('is_notified', 0)
                ->where('send_to', auth()->user()->id)
                ->take(5)->skip($skip)->get()->keyBy('id');
            DB::commit();

                return returnData(2000, $data);

        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), $exception->getMessage());
        }

    }

    public function update(Request $request)
    {
        try {
            DB::beginTransaction();

            if ($request->input('type') === 'update') {
                Notification::whereIn('id', $request->input('desktop_notifyeds'))->update([
                    'status' => 0,
                    'is_notified' => 1,
                ]);

                DB::commit();

                return returnData(2000, null,'Notificationsviewed');
            }
        } catch (\Exception $exception) {
            DB::rollBack();
            return response()->json(['message' => 'Error: ' . $exception->getMessage()], 500);
        }
    }





}
