<?php

namespace App\Http\Controllers;

use App\Domain\Comments\Models\Comment;
use App\Domain\Complaints\Models\CommentComplaint;
use Inertia\Inertia;
use Illuminate\Http\Request;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Complaints\Models\Reason;
use Illuminate\Support\Facades\Redirect;
use App\Domain\Complaints\Models\Complaint;
use App\Domain\Feeds\Queries\FeedQueryBuilder;

class ComplaintController extends Controller
{

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

    public function index($feed_id)
    {
        $feed = Feed::findOrFail($feed_id);
        if ($feed->user()->is(auth()->user())) {
            return Redirect::back();
        }

        $reasons = Reason::all();
        $feed = new FeedQueryBuilder();
        $feed = $feed->selectByIds($feed_id)->disablePaginate()->transformGet()->first();

        return Inertia::render('Complaint/Index', [
            'user' => $feed['user'],
            'feed' =>  $feed,
            'reasons' => $reasons,
        ]);
    }

    public function store(Request $request)
    {

        $feed_id = $request->get('feed');
        $feed = Feed::findOrFail($feed_id);

        if(empty($request->get('reason'))){
            return Redirect::back()->with('error', 'Выберите тип жалобы!');
        }
        $reason_id = $request->get('reason');
        $reason = Reason::findOrFail($reason_id);

        $complaint = new Complaint;
        $complaint->user_id = auth()->user()->id;
        $complaint->reason_id = $reason->id;
        $complaint->feed_id = $feed->id;
        $complaint->save();

        // return Redirect::route('feeds.layoutsidebar')->with('success', 'Жалоба успешно отправлена');
        return Redirect::back()->with('success', 'Жалоба успешно отправлена');
    }


    public function commentIndex($comment_id)
    {
        $comment = Comment::findOrFail($comment_id);
        if ($comment->user()->is(auth()->user())) {
            return Redirect::back();
        }

        $reasons = Reason::all();
        $user = $comment->user;
        $user->name = $user->name;
        return Inertia::render('Complaint/IndexComment', [
            'user' => $comment->user,
            'comment' =>  $comment,
            'reasons' => $reasons,
        ]);
    }

    public function commentStore(Request $request)
    {
        $comment_id = $request->get('comment');
        $comment = Comment::findOrFail($comment_id);

        if(empty($request->get('reason'))){
            return Redirect::back()->with('error', 'Выберите тип жалобы!');
        }
        $reason_id = $request->get('reason');
        $reason = Reason::findOrFail($reason_id);

        $complaint = new CommentComplaint;
        $complaint->user_id = auth()->user()->id;
        $complaint->reason_id = $reason->id;
        $complaint->comment_id = $comment->id;
        $complaint->save();

        return Redirect::back()->with('success', 'Жалоба успешно отправлена');
    }

}
