<?php

namespace Modules\Notification\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Support\Str;
use Jason\Api\Api;
use Modules\Notification\Http\Resources\NotificationCollection;
use Modules\Notification\Http\Resources\NotificationResource;
use Modules\User\Models\User;

class IndexController extends Controller
{

    /**
     * Notes   : 分类消息数量
     *
     * @Date   : 2021/6/21 9:30 上午
     * @Author : <Jason.C>
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        $user = Api::user();

        $result = [];
        foreach (config('notification.types') as $type => $name) {
            $result[] = [
                'type'  => Str::remove('App\\Notifications\\', $type),
                'icon'  => $name['icon'],
                'name'  => $name['name'],
                'count' => $user->unreadNotifications()->where('type', $type)->count(),
                'title' => data_get($user->unreadNotifications()->where('type', $type)->latest()->value('data'),
                        'title') ?? '',
            ];
        }

        return $this->success($result);
    }

    /**
     * Notes   : 未读消息数量
     *
     * @Date   : 2021/5/20 12:10 下午
     * @Author : <Jason.C>
     */
    public function counts(): JsonResponse
    {
        $user = Api::user();

        if ($user) {
            $count = $user->unreadNotifications()->count();
        } else {
            $count = 0;
        }

        return $this->success($count);
    }

    /**
     * Notes   : 分类读取消息
     *
     * @Date   : 2021/5/18 3:12 下午
     * @Author : <Jason.C>
     * @param  string  $type
     * @return JsonResponse
     */
    public function type(string $type): JsonResponse
    {
        $list = DatabaseNotification::query()
            ->whereHasMorph(
                'notifiable',
                User::class,
                function (Builder $query) {
                    $query->where('id', Api::userId());
                }
            )
            ->where('type', 'like', "%$type")
            ->orderBy('read_at')
            ->orderByDesc('created_at')->paginate();

        return $this->success(new NotificationCollection($list));
    }

    /**
     * Notes   : 消息详情，自动标记已读
     *
     * @Date   : 2021/5/18 3:17 下午
     * @Author : <Jason.C>
     * @param  string  $id
     * @return JsonResponse
     */
    public function show(string $id): JsonResponse
    {
        $notification = DatabaseNotification::findOrFail($id);

        $notification->markAsRead();

        return $this->success(new NotificationResource($notification));
    }

    /**
     * Notes   : 全部标记已读
     *
     * @Date   : 2021/5/18 3:22 下午
     * @Author : <Jason.C>
     */
    public function markAsRead(string $type = null): JsonResponse
    {
        $user = Api::user();

        $user->unreadNotifications()->when($type, function ($query) use ($type) {
            $query->where('type', 'like', "%$type");
        })->update(['read_at' => now()]);

        return $this->success('');
    }

    /**
     * Notes   : 清空消息
     *
     * @Date   : 2021/5/18 5:49 下午
     * @Author : <Jason.C>
     * @param  string|null  $type
     * @return JsonResponse
     */
    public function clean(string $type = null): JsonResponse
    {
        $user = Api::user();

        $user->notifications()->when($type, function ($query) use ($type) {
            $query->where('type', 'like', "%$type");
        })->delete();

        return $this->success('');
    }

}
