<?php

namespace App\Http\Controllers;

use App\Enum\OfferStatus;
use App\Enum\UserType;
use App\Http\Controllers\Utils\UtilController;
use App\Models\Artist;
use App\Models\Event;
use App\Models\Offer;
use App\Models\OfferComment;
use App\Models\Organizer;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Exception;

class OfferController extends Controller
{
    //
    public function __construct()
    {
        $this->middleware(['auth', 'verified', 'onboarding']);
        $this->middleware(['role:artist,organizer,manager'])->only(['show', 'writeComment', 'declineOffer']);
        $this->middleware(['role:artist,manager'])->only(['setPrice']);
        $this->middleware(['role:artist,organizer'])->only('index');
        $this->middleware(['role:organizer'])->only(['create', 'store']);
    }

    public function index()
    {
        $offers = Offer::select('offers.*')
            ->join('events', 'events.id', '=', 'offers.event_id')
            ->when(Auth::user()->type === UserType::ORGANIZER->value, function ($query) {
                return $query->where('events.organizer_id', '=', Auth::id());
            })
            ->when(Auth::user()->type === UserType::ARTIST->value, function ($query) {
                return $query->where('offers.artist_id', '=', Auth::id());
            })
            ->orderBy('offers.status', 'asc')
            ->orderBy('events.event_date', 'desc')
            ->paginate(15);

        return view('web.offer.offers')
            ->with('offers', $offers);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function create($username)
    {
        $organizer = Organizer::findOrFail(Auth::id());
        $user_artist = User::where('username', $username)->firstOrFail();
        $artist = Artist::where('user_id', $user_artist->id)->firstOrFail();

        return view('web.offer.create')
            ->with('events', $organizer->events)
            ->with('artist', $artist);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response|\Illuminate\Contracts\Foundation\Application|RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        $artist = Artist::where('user_id', $request->artist_id)->firstOrFail();
        $event = Event::where('id', $request->event_id)->firstOrFail();

        $checkIfOffersExists = Offer::where(function ($query) use ($event, $artist) {
            $query->where('event_id', $event->id);
            $query->where('artist_id', $artist->user_id);
            $query->where('status', OfferStatus::DECLINED->value);
            $query->where('created_at', '>', Carbon::now()->subDays(7)->endOfDay());
        })->orWhere(function ($query) use ($event, $artist) {
            $query->where('event_id', $event->id);
            $query->where('artist_id', $artist->user_id);
            $query->where('status', '!=', OfferStatus::DECLINED->value);
        })->exists();

        if ($checkIfOffersExists) {
            return redirect()->back()
                ->with('warning', 'You cannot send request to the artist for the selected event');
        }

        $offer = new Offer();
        $offer->slug = UtilController::generateSlugFromString('offer' . '-' . $event->title . Str::random(10));
        $offer->status = OfferStatus::IN_PROGRESS->value;
        $offer->payment_type = 1;

        $artist_id = Artist::find($request->artist_id);
        $offer->artist()->associate($artist_id);

        $event_id = Event::find($request->event_id);
        $offer->event()->associate($event_id);

        try {
            $offer->save();
        } catch (Exception $e) {
            return redirect()->back()
                ->with('error', $e->getMessage());
        }

        return redirect('/offers/' . $offer->slug)
            ->with('success', 'Request created and sent!');
    }

    /**
     * Display the specified resource.
     *
     * @param $slug
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\never
     */
    public function show($slug)
    {
        $offer = Offer::where('slug', $slug)->firstOrFail();
        $logged_user = User::where('id', Auth::id())->firstOrFail();

        if (
            ($logged_user->type === UserType::ARTIST->value && $offer->artist->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::MANAGER->value && $offer->artist->manager->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::ORGANIZER->value && $logged_user->id == $offer->event->organizer->user_id)
        ) {
            if ($logged_user->type === UserType::ORGANIZER->value) {
                if ($offer->status == OfferStatus::WAITING_FOR_PAYMENT->value) {
                    $intent = Auth::user()->role->createSetupIntent();
                }
            }
            return view('web.offer.offer')
                ->with('offer', $offer)
                ->with('intent', $intent ?? null);
        }

        return abort(404);
    }

    public function writeComment(Request $request)
    {
        $offer = Offer::where('id', $request->offer_id)->firstOrFail();
        $logged_user = User::where('id', Auth::id())->firstOrFail();

        //ORGANIZER, ARTIST, MANAGER
        /*
         * ALLOWED TP REPLY IF:
         * OFFER IS CREATED BY THE SIGNED ORGANIZER
         * OFFER IS SENT TO SIGNED ARTIST
         * OFFER IS SENT TO ARTIST WHO IS MANAGED BY SIGNED MANAGER
         */
        if (
            ($logged_user->type === UserType::ORGANIZER->value && $logged_user->id == $offer->event->organizer->user_id) ||
            ($logged_user->type === UserType::ARTIST->value && $offer->artist->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::MANAGER->value && $offer->artist->manager->user_id == $logged_user->id)
        ) {
            $offerComment = new OfferComment();
            $offerComment->offer()->associate($offer);

            $offerComment->author()->associate($logged_user);

            $offerComment->content = $request->comment;
            $offerComment->updated_at = null;

            try {
                $offerComment->save();
            } catch (\Exception $e) {
                dd($e);
            }

            return redirect()->back();
        }
        return abort(404);
    }

    public function setPrice(Request $request): RedirectResponse
    {
        $offer = Offer::where('id', $request->offer_id)->firstOrFail();
        $logged_user = User::where('id', Auth::id())->firstOrFail();

        if (
            ($offer->status === OfferStatus::IN_PROGRESS->value) &&
            (($logged_user->type === UserType::ARTIST->value && $offer->artist->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::MANAGER->value && $offer->artist->manager->user_id == $logged_user->id))
        ) {
            $offer->price = $request->price;

            try {
                $offer->update();
            } catch (Exception $e) {
                return redirect()->back()
                    ->with('error', $e->getMessage());
            }

            return redirect()->back();
        } else {
            return redirect()->back()
                ->with('warning', 'You are not authorized for that action!');
        }
    }

    public function declineOffer(Request $request): RedirectResponse
    {
        $offer = Offer::where('id', $request->offer_id)->firstOrFail();
        $logged_user = User::where('id', Auth::id())->firstOrFail();

        if (
            ($offer->status === OfferStatus::IN_PROGRESS->value) &&
            (($logged_user->type === UserType::ORGANIZER->value && $logged_user->id == $offer->event->organizer->user_id) ||
            ($logged_user->type === UserType::ARTIST->value && $offer->artist->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::MANAGER->value && $offer->artist->manager->user_id == $logged_user->id))
        ) {
            $offer->status = OfferStatus::DECLINED->value;
            $offer->completed_at = Carbon::now()->toDateTimeString();

            try {
                $offer->update();
            } catch (Exception $e) {
                return redirect()->back()
                    ->with('error', $e->getMessage());
            }

            return redirect()->back();
        } else {
            return redirect()->back()
                ->with('warning', 'You are not authorized for that action!');
        }
    }

    public function acceptOffer(Request $request): RedirectResponse
    {
        $offer = Offer::where('id', $request->offer_id)->firstOrFail();
        $logged_user = User::where('id', Auth::id())->firstOrFail();

        if (
            ($offer->status === OfferStatus::IN_PROGRESS->value) &&
            (($logged_user->type === UserType::ORGANIZER->value && $logged_user->id == $offer->event->organizer->user_id) ||
            ($logged_user->type === UserType::ARTIST->value && $offer->artist->user_id == $logged_user->id) ||
            ($logged_user->type === UserType::MANAGER->value && $offer->artist->manager->user_id == $logged_user->id))
        ) {
            $offer->status = OfferStatus::WAITING_FOR_PAYMENT->value;
            $offer->completed_at = Carbon::now()->toDateTimeString();

            try {
                $offer->update();
            } catch (Exception $e) {
                return redirect()->back()
                    ->with('error', $e->getMessage());
            }

            return redirect()->back();
        } else {
            return redirect()->back()
                ->with('warning', 'You are not authorized for that action!');
        }
    }
}
