<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Mail\FeedbackToAdmin;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Request;
use Illuminate\Http\Request as HttpRequest;
use App\Domain\Feeds\Queries\FeedQueryBuilder;

class DashboardController extends Controller
{

    public function __construct()
    {
        // $this->middleware('subs.paid');
    }

    public function index()
    {

        $filter = Request::get('filter');
        $feeds = (new FeedQueryBuilder())->filter()->search(Request::only('search'))->build();

        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if($filter === 'hot'){
            $feeds = $feeds->sortByDesc('entity.likes')->values();
        }

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        return Inertia::render('Dashboard/Index', [
            'searchFilters' => Request::all('search'),
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'active_filter' => $filter ?? 'new'
        ]);

    }

    public function commonSendWriteToUs()
    {
        return Inertia::render('Auth/Feedback', []);
    }

    public function sendWriteToUs(HttpRequest $request)
    {
        $user = auth()->user();

        if($user){
            $request->validate([
                'title' => ['required'],
                'body' => ['required'],
            ]);

            $userInfo = (object)[
                'userFullName' => $user->name,
                'userPhone' => $user->phone,
                'userEmail' => $user->email,
                'profileUrl' => env('APP_URL') . '/profile/' . $user->username,
                'guest' => false
            ];
        }else{
            $request->validate([
                'title' => ['required'],
                'body' => ['required'],
                'email' => ['required'],
            ]);

            $userInfo = (object)[
                'userEmail' => request()->post('email'),
                'guest' => true
            ];
        }

        $data = (object) [
            'title' => request()->post('title'),
            'body' => request()->post('body'),
            'userInfo' => $userInfo
        ];

        Mail::to(env('MAIL_ADMIN_EMAIL'))->send(new FeedbackToAdmin($data));

        return back()->with('success', 'Сообщение успешно отправлено')->with('status', 'Сообщение успешно отправлено');
    }

}
