<?php

namespace Inside\DESK\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inside\Authentication\Models\User;
use Inside\Content\Models\Contents\Alerts;
use Inside\Reaction\Facades\Reactions;
use Laravel\Lumen\Routing\Controller;

class PopinController extends Controller
{
    public function popin(Request $request): array
    {
        /** @var User $user */
        $user = Auth::user();

        $alert = Alerts::query()->where('status', 1)->where('langcode', $user->langcode)->orderBy('created_at', 'DESC')->first();

        if (empty($alert)) {
            return [
                'popin' => false,
            ];
        }

        $reaction = DB::table('inside_reactions')
            ->where('type', 'alert')
            ->where('user_uuid', $user->uuid)
            ->where('reactionable_uuid', $alert->uuid)
            ->where('created_at', 'LIKE', date('Y-m-d', time()) . ' %')
            ->orderBy('created_at', 'DESC')->get();

        $count = $reaction->count();

        return [
            'popin' => !(bool)$count,
            'reaction_date' => $count === 0 ? null : $reaction->pluck('created_at')->first()
        ];
    }

    public function reaction(Request $request): array
    {
        /** @var User $user */
        $user = Auth::user();

        DB::table('inside_reactions')
            ->where('type', 'alert')
            ->where('user_uuid', $user->uuid)
            ->delete();

        $data_uuid = $request->get('uuid');

        /** @var Alerts $data */
        $data = DB::table('inside_content_alerts')->where('uuid', $data_uuid)->first();

        Reactions::create([
            'user_uuid' => $user->uuid,
            'reactionable_uuid' => $data_uuid,
            'reactionable_type' => "Inside\Content\Models\Contents\Alerts",
            'type' => 'alert',
            'langcode' => $data->langcode
        ], ['uuid']);

        return [
            'success' => true,
        ];
    }
}
