<?php

namespace App\Http\Controllers\API\Buyer;

use App\Models\User;
use App\Models\Order;
use App\Models\Review;
use Illuminate\Http\Request;
use Auth, File, Image, Str, Hash;
use App\Http\Controllers\Controller;
use Modules\JobPost\Entities\JobPost;
use Modules\JobPost\Entities\JobRequest;
use Modules\LiveChat\App\Models\Message;
use App\Http\Requests\PasswordChangeRequest;
use Modules\Refund\App\Models\RefundRequest;
use App\Http\Requests\EditBuyerProfileRequest;
use Modules\JobPost\Entities\JobPostTranslation;

class ProfileController extends Controller
{
    public function dashboard()
    {

        $user = Auth::guard('api')->user();

        $orders = Order::with('listing', 'seller')->where('buyer_id', $user->id)->latest()->take(10)->get();

        $active_orders = Order::with('listing', 'seller')->where('buyer_id', $user->id)->where(['approved_by_seller' => 'approved', 'order_status' => 'approved_by_seller'])->latest()->count();

        $complete_orders = Order::where('buyer_id', $user->id)->where(function ($query) {
            $query->where('order_status', 'complete_by_buyer')
                ->orWhere('completed_by_buyer', 'complete');
        })->latest()->count();

        $cancel_orders = Order::where('buyer_id', $user->id)->where(function ($query) {
            $query->where('order_status', 'cancel_by_seller')
                ->orWhere('order_status', 'cancel_by_buyer');
        })->latest()->count();

        $rejected_orders = Order::where('buyer_id', $user->id)->where(['approved_by_seller' => 'rejected'])->where('order_status', '!=', 'cancel_by_buyer')->latest()->count();



        return response()->json([
            'active_orders' => $active_orders,
            'complete_orders' => $complete_orders,
            'cancel_orders' => $cancel_orders,
            'rejected_orders' => $rejected_orders,
            'orders' => $orders,
        ]);
    }

    public function edit_profile()
    {
        $user = Auth::guard('api')->user();

        return response()->json(['user' => $user]);
    }

    public function update_profile(EditBuyerProfileRequest $request)
    {

        $user = Auth::guard('api')->user();
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->designation = $request->designation;
        $user->address = $request->address;
        $user->about_me = $request->about_me;
        $user->language = $request->language;
        $user->gender = $request->gender;
        $user->save();

        if ($request->hasFile('image')) {
            $file_path = uploadPublicFile($request->image, 'uploads/custom-images', $user->image);
            $user->image = $file_path;
            $user->save();
        }

        $notify_message = trans('translate.Updated successfully');
        return response()->json([
            'message' => $notify_message
        ]);
    }

    public function update_avatar(Request $request)
    {

        $request->validate([
            'image' => 'required'
        ]);

        $user = Auth::guard('api')->user();

        if ($request->hasFile('image')) {
            $file_path = uploadPublicFile($request->image, 'uploads/custom-images', $user->image);
            $user->image = $file_path;
            $user->save();
        }

        $notify_message = trans('translate.Updated successfully');
        return response()->json([
            'message' => $notify_message
        ]);
    }

    public function update_password(PasswordChangeRequest $request)
    {

        $user = Auth::guard('api')->user();

        if (Hash::check($request->current_password, $user->password)) {
            $user->password = Hash::make($request->password);
            $user->save();

            $notify_message = trans('translate.Password changed successfully');
            return response()->json([
                'message' => $notify_message
            ]);
        } else {
            $notify_message = trans('translate.Current password does not match');
            return response()->json([
                'message' => $notify_message
            ], 403);
        }
    }


    public function orders()
    {
        $user = Auth::guard('api')->user();

        $orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->latest()->get();

        $active_orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->where(['approved_by_seller' => 'approved', 'order_status' => 'approved_by_seller'])->latest()->get();

        $awaiting_orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->where(['approved_by_seller' => 'pending'])->where('order_status', '!=', 'cancel_by_buyer')->latest()->get();

        $rejected_orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->where(['approved_by_seller' => 'rejected'])->where('order_status', '!=', 'cancel_by_buyer')->latest()->get();

        $cancel_orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->where(function ($query) {
            $query->where('order_status', 'cancel_by_seller')
                ->orWhere('order_status', 'cancel_by_buyer');
        })->latest()->get();

        $complete_orders = Order::with('listing.category', 'seller')->where('buyer_id', $user->id)->where(function ($query) {
            $query->where('order_status', 'complete_by_buyer')
                ->orWhere('completed_by_buyer', 'complete');
        })->latest()->get();

        return response()->json([
            'orders' => $orders,
            'active_orders' => $active_orders,
            'awaiting_orders' => $awaiting_orders,
            'rejected_orders' => $rejected_orders,
            'cancel_orders' => $cancel_orders,
            'complete_orders' => $complete_orders,
        ]);
    }

    public function order_show($order_id)
    {
        $user = Auth::guard('api')->user();

        $order = Order::with('listing')->where('buyer_id', $user->id)->where('id', $order_id)->first();

        if (!$order) {
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        $seller = User::select('id', 'username', 'name', 'image', 'status', 'is_banned', 'is_seller', 'is_top_seller', 'designation', 'hourly_payment', 'kyc_status', 'online_status', 'online')->findOrFail($order->seller_id);

        $total_job = JobRequest::where('seller_id', $seller->id)->where('status', 'approved')->count();

        $review_exist = Review::where(['buyer_id' => $user->id, 'order_id' => $order->id])->count();
        $review = Review::where(['buyer_id' => $user->id, 'order_id' => $order->id])->first();

        $able_to_refund = false;
        $refund_available = false;
        $can_send_refund = false;
        $refund = null;

        if ($order->order_status == 'cancel_by_seller' || $order->order_status == 'cancel_by_buyer' || $order->approved_by_seller == 'rejected') {
            if (checkModule('Wallet') && checkModule('Refund')) {
                $able_to_refund = true;
                $can_send_refund = true;

                $refund = RefundRequest::where('order_id', $order->id)->first();
                if ($refund) {
                    $refund_available = true;
                }
            }
        }



        return response()->json([
            'order' => $order,
            'seller' => $seller,
            'total_job' => $total_job,
            'review_exist' => $review_exist,
            'review' => $review,
            'able_to_refund' => $able_to_refund,
            'can_send_refund' => $can_send_refund,
            'refund_available' => $refund_available,
            'refund' => $refund,
        ]);
    }


    public function order_complete(Request $request, $id)
    {

        $user = Auth::guard('api')->user();

        $order = Order::where('buyer_id', $user->id)->where('id', $id)->first();

        if (!$order) {
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        if ($order->approved_by_seller == 'approved' && $order->order_status == 'approved_by_seller') {
            $order->completed_by_buyer = 'complete';
            $order->order_status = 'complete_by_buyer';
            $order->save();

            $notify_message = trans('translate.Order complete successful');
            return response()->json([
                'message' => $notify_message,
            ]);
        } else {
            return response()->json([
                'message' => trans('translate.Not able to complete the order')
            ], 403);
        }
    }

    public function order_cancel(Request $request, $id)
    {

        $user = Auth::guard('api')->user();

        $order = Order::where('buyer_id', $user->id)->where('id', $id)->first();

        if (!$order) {
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        $able_to_cancel = false;
        if ($order->approved_by_seller == 'approved' && $order->order_status == 'approved_by_seller') {
            $able_to_cancel = true;
        } elseif ($order->approved_by_seller == 'pending') {
            $able_to_cancel = true;
        }

        if (!$able_to_cancel) {
            return response()->json([
                'message' => trans('translate.Not able to cancel the order')
            ], 403);
        }

        if ($order->order_status == 'cancel_by_buyer') {
            return response()->json([
                'message' => trans('translate.Not able to cancel the order')
            ], 403);
        }

        $order->order_status = 'cancel_by_buyer';
        $order->save();

        $notify_message = trans('translate.Order cancel successful');

        return response()->json([
            'message' => $notify_message,
        ]);
    }

    public function store_review(Request $request, $order_id)
    {
        $request->validate([
            'rating' => 'required',
            'review' => 'required'
        ], [
            'rating.required' => trans('translate.Rating is required'),
            'review.required' => trans('translate.Review is required'),
        ]);


        $user = Auth::guard('web')->user();
        $order = Order::where('buyer_id', $user->id)->where('id', $order_id)->first();

        $exist = Review::where(['buyer_id' => $user->id, 'order_id' => $order_id])->count();
        if ($exist) {
            $notify_message = trans('translate.Review already submited');
            $notify_message = array('message' => $notify_message, 'alert-type' => 'error');
            return redirect()->back()->with($notify_message);
        }

        $review = new Review();
        $review->order_id = $order_id;
        $review->listing_id = $order->listing_id;
        $review->buyer_id = $order->buyer_id;
        $review->seller_id = $order->seller_id;
        $review->rating = $request->rating;
        $review->review = $request->review;
        $review->status = 'disable';
        $review->save();

        $notify_message = trans('translate.Review submited successful, please wait for admin approval');
        $notify_message = array('message' => $notify_message, 'alert-type' => 'success');
        return redirect()->back()->with($notify_message);
    }

    public function account_delete(Request $request)
    {

        $request->validate([
            'current_password' => 'required'
        ]);

        $user = Auth::guard('api')->user();

        if (!Hash::check($request->current_password, $user->password)) {
            $notify_message = trans('translate.Current password does not match');
            return response()->json([
                'message' => $notify_message
            ], 403);
        }

        $user_image = $user->image;

        if ($user_image) {
            deleteFile($user_image);
        }

        Review::where('buyer_id', $user->id)->delete();
        Review::where('seller_id', $user->id)->delete();

        JobRequest::where('user_id', $user->id)->delete();
        JobRequest::where('seller_id', $user->id)->delete();

        Order::where('seller_id', $user->id)->delete();
        Order::where('buyer_id', $user->id)->delete();


        $json_module_data = file_get_contents(base_path('modules_statuses.json'));
        $module_status = json_decode($json_module_data);

        if (isset($module_status->LiveChat) && $module_status->LiveChat) {
            Message::where('seller_id', $user->id)->delete();
            Message::where('buyer_id', $user->id)->delete();
        }

        $job_posts = JobPost::with('translate', 'category')->where('user_id', $user->id)->latest()->get();

        foreach ($job_posts as $job_post) {
            $old_image = $job_post->thumb_image;

            if ($old_image) {
                deleteFile($old_image);
            }

            JobPostTranslation::where('job_post_id', $job_post->id)->delete();
            JobRequest::where('job_post_id', $job_post->id)->delete();

            $job_post->delete();
        }

        $user->delete();

        Auth::guard('api')->logout();

        $notify_message = trans('translate.Your account deleted successful');
        return response()->json([
            'message' => $notify_message
        ]);
    }
}
