<?php

namespace Modules\HospitalPortal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Claim;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\HospitalPortal\Helpers\ApiResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class NotificationController extends Controller
{
    public function getNotifications(Request $request, $user_id)
    {
        $data = [
            'user_id' => $user_id,
        ];
        if (!$user_id)
        {
            return ApiResponse::apiResponse('Not Found', $data, trans('Message.not_found'), 404);
        }
        else
        {
            try {
                $notifications = DB::table('notifications')
                ->join('notification_types', 'notification_types.id', '=', 'notifications.type')
                ->select(
                    'notifications.id',
                    'notifications.title',
                    'notifications.description',
                    'notifications.avatar',
                    'notification_types.type',
                    DB::raw('DATE_FORMAT(notifications.created_at, "%Y-%m-%dT%H:%i:%s.000+07:00") as createdAt'),
                    'notifications.isUnRead',
                )
                ->where('user_id', '=', $user_id)
                ->orderBy('id', 'DESC')
                ->get();
                $res_data['notifications'] = $notifications;
                return ApiResponse::apiResponse("Success", $res_data, trans('Message.success'), 200);
            }
            catch (\Exception $e) {
                return ApiResponse::apiResponse("Error", $data, $e->getMessage(), 500);
            }
        }
    }
    
    public function setReadNotification(Request $request)
    {
        $data = [
            'user_id' => $request->user_id,
            'id' => $request->id,
            'isUnRead'=> 0,
        ];
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'id' => 'required'
        ], [
            'user_id.required' => trans('Validation.required',['attribute' => 'Hospital ID']),
            'id.required' => trans('Validation.required',['attribute' => 'ID']),
        ]);
        if ($validator->fails())
        {
            return ApiResponse::apiResponse('Bad Request', $data, $validator->errors(), 400);
        }
        else
        {
            try {
                DB::beginTransaction();
                DB::table('notifications')
                ->where('notifications.id', '=', $request->id)
                ->update($data);
                DB::commit();
                return ApiResponse::apiResponse("Success", $data, trans('Message.read_notification'), 200);

            }
            catch (\Exception $e) {
                DB::rollback();
                return ApiResponse::apiResponse("Error", $data, $e->getMessage(), 500);
            }
        }
    }

}