<?php

namespace App\Http\Controllers\API;

use App\Evaluate;
use App\UmrahTrip;
use Illuminate\Http\Request;
use App\UmrahTripReservation;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\UmrahTripResource;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\UmrahTripReservationResource;
use App\Http\Requests\API\AddUmrahReservationRequest;

class UmrahTripController extends Controller
{

    /**
     * Get all umrah trips or by id
     * @param null $umrah_trip_id
     * @return JsonResponse
     */
    public function umrahTrips($umrah_trip_id = null) :JsonResponse
    {
        $umrahTrips =  UmrahTrip::withDescription($umrah_trip_id);
        $umrahTrips = $umrah_trip_id ? UmrahTripResource::make($umrahTrips) : UmrahTripResource::collection($umrahTrips);
        return response()->json(['message' => 'success', 'data' => $umrahTrips], 200);
    }


    /**
     * Add umrah reservation foreach auth user and guest
     * @param AddUmrahReservationRequest $request
     * @param $umrah_trip_id
     * @return JsonResponse
     */
    public function addReservationForUserAndGuest(AddUmrahReservationRequest $request, $umrah_trip_id) :JsonResponse
    {

//        return response()->json(['message' => 'success', 'data' => $umrah_trip_id], 200);

        $data = $request->all();
        $umrah = UmrahTrip::find($umrah_trip_id);
        $userLogged = Auth::check() ? Auth::user() : null;
        $data['name'] = $userLogged ? $userLogged->name : $request->name;
        $data['email'] = $userLogged ? $userLogged->email : $request->email;
        $code = $userLogged ? $userLogged->code : $request->code;
        $phone = $userLogged ? $userLogged->phone : $request->phone;
        $data['phone'] = $code.$phone;
        $data['user_id'] = $userLogged ? $userLogged->id : null;
        $data['umrah_trip_id'] = $umrah_trip_id;
        $data['departure_city'] = $umrah->departure_city;
        $data['arrival_city'] = $umrah->arrival_city;
        $data['price_per_person'] = $umrah->price_per_person;
        $data['person_count'] = $request->person_count ? $request->person_count : 0;
        $data['rally_point_info'] = [$request->rally_point_info => $umrah->rally_point_info[$request->rally_point_info]];
        $escorts = [];
        if ($userLogged && $request->escorts && count($request->escorts)){
            foreach ($request->escorts as $escortName) {
                if (isset($userLogged->escorts[$escortName])){
                    $escorts[$escortName] = $userLogged->escorts[$escortName];
                }
            }
        }

        $data['escorts'] = $escorts;
        $total = $umrah->price_per_person;

        if ($data['person_count']){
            $total = $data['person_count']*$umrah->price_per_person;
        }
        if ($request->escorts && count($request->escorts)){
            $total = count($escorts)*$umrah->price_per_person;
        }
        $data['total'] = $total;
        $data['status'] = 'current';
        $umrahReservation = UmrahTripReservation::create($data);
        return response()->json(['message' => 'success', 'data' => UmrahTripReservationResource::make($umrahReservation)], 200);

    }

    /**
     * Get all reservation by umrah id or umrah id and reservation status [current-finished]
     * @param $umrah_trip_id
     * @param null $status
     * @return JsonResponse
     */
    public function getReservations($umrah_trip_id, $status = null) :JsonResponse
    {
        $reservations = UmrahTripReservation::where('umrah_trip_id', $umrah_trip_id);
        if ($status){
            $reservations->where('status', $status);
        }
        $reservations = $reservations->cursor();
        return response()->json(['message' => 'success', 'data' => UmrahTripReservationResource::collection($reservations)], 200);

    }

    /**
     * Umrah trip evaluate
     * @param Request $request
     * @param $umrah_trip_id
     * @return JsonResponse
     */
    public function evaluate(Request $request, $umrah_trip_id) :JsonResponse
    {
        $validation = Validator::make($request->all(),
            [
                'evaluate_average' => 'required|in:1,2,3,4,5',
                'comment' => 'required|min:3|max:400',
            ],[],[
                'comment' => __('evaluates.comment'),
                'evaluate_average' => __('evaluates.evaluate_average')
            ]);

        if ($validation->fails()){
            return response()->json(['message' => $validation->errors()->first()], 400);
        }

        $userId = Auth::id();

        $umrahTripReservation = UmrahTripReservation::where('umrah_trip_id', $umrah_trip_id)->where('user_id', $userId)->first();

        if (!$umrahTripReservation){
            return response()->json(['message' => __('umrahTrips.reservation_not_found')], 400);
        }

        if ($umrahTripReservation->umrah_trip_date > date('Y-m-d') || $umrahTripReservation->status != 'finished'){
            return response()->json(['message' => __('umrahTrips.reservation_not_finished')], 400);
        }

        $isEvaluateBefore = Evaluate::where('user_id', $userId)->where('umrah_trip_id', $umrah_trip_id)->first();

        if ($isEvaluateBefore){
            return response()->json(['message' => __('umrahTrips.evaluate_before')], 400);
        }

        Evaluate::create([
            'user_id' => $userId,
            'umrah_trip_id' => $umrah_trip_id,
            'comment' => $request->comment,
            'evaluate_average' => $request->evaluate_average,
        ]);
        $rate = DB::table('evaluates')
            ->selectSub("SELECT SUM(evaluate_average) FROM evaluates WHERE umrah_trip_id=$umrah_trip_id LIMIT 1", 'evaluate_sum')
            ->selectSub("SELECT COUNT(evaluate_average) FROM evaluates WHERE umrah_trip_id=$umrah_trip_id LIMIT 1", 'evaluate_count')->first();
        $rate = $rate->evaluate_sum/$rate->evaluate_count;

        UmrahTrip::find($umrah_trip_id)->update(['rate' => $rate]);

        return response()->json(['message' => __('hotels.evaluate_successfully')], 200);

    }

    /**
     * Add or remove hotel to favorite
     * @param $umrah_trip_id
     * @return JsonResponse
     */
    public function addToFavorite($umrah_trip_id) :JsonResponse
    {
        $user = Auth::user();
        $favoriteUmrah = $user->umrahFavorites()->pluck('umrah_trip_id')->toArray();
        $message = __('umrahTrips.favorite_successfully');
        if (in_array($umrah_trip_id, $favoriteUmrah)){
            $message = __('umrahTrips.remove_favorite_successfully');
        }
        $user->umrahFavorites()->toggle($umrah_trip_id);
        return response()->json(['message' => $message], 200);
    }

    /**
     * Get flights reservation requires like escorts and rally point info
     * @return JsonResponse
     */
    public function requires() :JsonResponse
    {
        $user = Auth::check() ? Auth::user() : null;
        $escorts = [];
        $rallyPoints = [];
        $umrahTripDates = [];
        if ($user){
            if ($user->escorts && is_array($user->escorts)){
                $escorts = is_string($user->escorts) ? json_decode($user->escorts, true) : $user->escorts;
            }
        }

        $umrahTrip = UmrahTrip::first();

        if ($umrahTrip) {
            $rallyPoints = is_string($umrahTrip->rally_point_info) ? json_decode($umrahTrip->rally_point_info, true) : $umrahTrip->rally_point_info;
            $umrahTripDates = is_string($umrahTrip->umrah_trip_date) ? json_decode($umrahTrip->umrah_trip_date, true) : $umrahTrip->umrah_trip_date;
        }

        return response()->json(['message' => 'success', 'data' => [
            'escorts' =>  $escorts,
            'rally_point' => $rallyPoints,
            'umrah_trip_dates' => $umrahTripDates,
        ]], 200);

    }


}
