<?php

namespace App\Http\Controllers\API\Seller;

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\Listing\Entities\Listing;
use Modules\JobPost\Entities\JobRequest;
use Modules\LiveChat\App\Models\Message;
use App\Http\Requests\PasswordChangeRequest;
use Modules\Listing\Entities\ListingGallery;
use App\Http\Requests\EditBuyerProfileRequest;
use Modules\Listing\App\Models\ListingPackage;
use Modules\Listing\Entities\ListingTranslation;
use Modules\GlobalSetting\App\Models\GlobalSetting;
use Modules\PaymentWithdraw\App\Models\SellerWithdraw;

class ProfileController extends Controller
{
    public function dashboard()
    {

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

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

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

        $cancel_orders = Order::where('seller_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('seller_id', $user->id)->where(['approved_by_seller' => 'rejected'])->where('order_status', '!=', 'cancel_by_buyer')->latest()->count();

        $withdraw_list = SellerWithdraw::where('seller_id', $user->id)->latest()->get();

        $total_income = Order::where('seller_id', $user->id)->where('payment_status', 'success')->where('completed_by_buyer', 'complete')->sum('total_amount');

        $commission_type = GlobalSetting::where('key', 'commission_type')->value('value');
        $commission_per_sale = GlobalSetting::where('key', 'commission_per_sale')->value('value');

        $total_commission = 0.00;
        $net_income = $total_income;
        if ($commission_type == 'commission') {
            $total_commission = ($commission_per_sale / 100) * $total_income;
            $net_income = $total_income - $total_commission;
        }

        $total_withdraw_amount = $withdraw_list->sum('total_amount');

        $current_balance = $net_income - $total_withdraw_amount;

        $pending_withdraw = SellerWithdraw::where('seller_id', $user->id)->where('status', 'pending')->sum('total_amount');

        $withdraw_list = $withdraw_list->take(5);

        $orders = Order::with('listing.category', 'buyer')->where('seller_id', $user->id)->latest()->take(5)->get();

        return response()->json([
            'active_orders' => $active_orders,
            'complete_orders' => $complete_orders,
            'cancel_orders' => $cancel_orders,
            'rejected_orders' => $rejected_orders,
            'total_income' => $total_income,
            'total_commission' => $total_commission,
            'net_income' => $net_income,
            'current_balance' => $current_balance,
            'withdraw_list' => $withdraw_list,
            '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->gender = $request->gender;
        $user->language = $request->language;
        $user->university_name = $request->university_name;
        $user->university_location = $request->university_location;
        $user->university_time_period = $request->university_time_period;
        $user->school_name = $request->school_name;
        $user->school_location = $request->school_location;
        $user->school_time_period = $request->school_time_period;
        $user->about_me = $request->about_me;
        $user->skills = $request->skills;
        $user->hourly_payment = $request->hourly_payment ? $request->hourly_payment : 0.00;
        $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', 'buyer')->where('seller_id', $user->id)->latest()->get();

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

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

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

        $cancel_orders = Order::with('listing.category', 'buyer')->where('seller_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', 'buyer')->where('seller_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('seller_id', $user->id)->where('order_id', $order_id)->first();
        $order = Order::with('listing')->where('seller_id', $user->id)->where('id', $order_id)->first();

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

        $buyer = User::findOrFail($order->buyer_id);

        $buyer_total_rating = 1;

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

        $total_orders = Order::where('buyer_id', $buyer->id)->latest()->count();

        return response()->json([
            'order' => $order,
            'buyer' => $buyer,
            'total_orders' => $total_orders,
            'total_job' => $total_job,

        ]);
    }

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

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

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

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

        $order->approved_by_seller = 'approved';
        $order->order_status = 'approved_by_seller';
        $order->save();

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


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

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

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

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

        if ($order->approved_by_seller != 'pending') {
            $notify_message = trans('Unable to reject the order');
            return response()->json([
                'message' => $notify_message
            ], 403);
        }
        $order->approved_by_seller = 'rejected';
        $order->order_status = 'rejected_by_seller';
        $order->save();

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

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

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

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

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


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

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

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




    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);
        }

        $listings = Listing::where('seller_id', $user->id)->latest()->get();

        foreach ($listings as $listing) {
            $old_image = $listing->thumb_image;

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

            ListingTranslation::where('listing_id', $listing->id)->delete();
            Review::where('listing_id', $listing->id)->delete();
            ListingPackage::where('listing_id', $listing->id)->delete();

            $galleries = ListingGallery::where('listing_id', $listing->id)->get();
            foreach ($galleries as $gallery) {
                $old_image = $gallery->image;

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

                $gallery->delete();
            }

            $listing->delete();
        }

        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();
        }


        $user->delete();

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

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


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

        $request->validate([
            'submit_file' => 'required|file'
        ]);

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

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

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


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

        $order->save();

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

    public function updateStatus(Request $request)
    {
        $user = Auth::guard('api')->user();
        $user->online_status = $user->online_status == 1 ? 0 : 1;
        $user->save();

        return response()->json(['success' => true, 'online_status' => $user->online_status, 'message' => trans('translate.Status Changed Successfully')]);
    }
}
