<?php

declare(strict_types=1);

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Http\Requests\Site\Store;
use App\Models\Site;
use App\Models\SocialiteUser;
use App\Notifications\SiteApply;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use Notification;

class SiteController extends Controller
{
    public function index(): View
    {
        $site = Site::select('id', 'name', 'url', 'description')
            ->where('audit', 1)
            ->orderBy('sort')
            ->get();
        $head = [
            'title'       => translate('Recommend Blog'),
            'keywords'    => translate('Recommend Blog'),
            'description' => translate('Recommend Blog'),
        ];
        $assign = [
            'site'        => $site,
            'head'        => $head,
            'category_id' => 'index',
            'tagName'     => '',
        ];

        return view('home.site.index', $assign);
    }

    public function store(Store $request): JsonResponse
    {
        /** @var \App\Models\SocialiteUser $socialiteUser */
        $socialiteUser = auth()->guard('socialite')->user();

        $siteData                      = $request->only('name', 'url', 'description');
        $siteData['socialite_user_id'] = $socialiteUser->id;
        $sort                          = Site::orderBy('sort', 'desc')->value('sort');
        $siteData['sort']              = (int) $sort + 1;
        $newSite                       = Site::create($siteData);

        SocialiteUser::where('id', $socialiteUser->id)->update([
            'email' => $request->input('email'),
        ]);

        Notification::route('mail', config('bjyblog.notification_email'))
            ->notify(new SiteApply());

        return response()->json($newSite);
    }
}
