<?php

namespace Modules\Listing\Http\Controllers\API\Seller;

use App\Models\User;
use App\Models\Order;
use App\Models\Review;
use Auth, Image, File, Str;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Listing\Entities\Listing;
use Modules\Category\Entities\Category;
use Modules\Language\App\Models\Language;
use Modules\Category\Entities\SubCategory;
use Illuminate\Contracts\Support\Renderable;

use Modules\Listing\Entities\ListingGallery;

use Modules\Listing\App\Models\ListingPackage;
use Modules\Listing\Entities\ListingTranslation;
use Modules\Listing\Http\Requests\ListingRequest;
use Modules\GlobalSetting\App\Models\GlobalSetting;
use Modules\Listing\Http\Requests\ListingBasicRequest;
use Modules\Subscription\Entities\SubscriptionHistory;
use Modules\Listing\Http\Requests\ListingPackageRequest;

class ListingController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $user = Auth::guard('api')->user();

        $services = Listing::with('seller')->where('seller_id', $user->id)->latest()->get();
        $active_services = Listing::with('seller')->where('seller_id', $user->id)->where('approved_by_admin', 'approved')->latest()->get();
        $pending_services = Listing::with('seller')->where('seller_id', $user->id)->where('approved_by_admin', 'pending')->latest()->get();

        return response()->json([
            'services' => $services,
            'active_services' => $active_services,
            'pending_services' => $pending_services,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create(Request $request)
    {
        $auth_user = Auth::guard('api')->user();

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

        if ($commission_type == 'subscription') {
            $find_plan = SubscriptionHistory::where('user_id', $auth_user->id)->first();

            if (!$find_plan) {
                $notify_message = trans('translate.You do not have active plan, please renew or purchase');
                return response()->json([
                    'message' => $notify_message,
                ], 403);
            }

            if ($find_plan->expiration_date != 'lifetime' && date('Y-m-d') > $find_plan->expiration_date) {

                $notify_message = trans('translate.You subscription plan has expired, please renew or purchase');
                return response()->json([
                    'message' => $notify_message,
                ], 403);
            }

            $existing_listing = $job_posts = Listing::where('seller_id', $auth_user->id)->count();

            if ($find_plan->max_listing != '-1' && $existing_listing >= $find_plan->max_listing) {
                $notify_message = trans('translate.You subscription plan limit exceeded, please renew or purchase new plan');
                return response()->json([
                    'message' => $notify_message,
                ], 403);
            }
        }

        $categories = Category::where('status', 'enable')->get();

        $sub_categories = SubCategory::where('status', 'enable')->latest()->get();


        return response()->json([
            'categories' => $categories,
            'sub_categories' => $sub_categories,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(ListingBasicRequest $request)
    {

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

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

        // if($commission_type == 'subscription'){
        //     $find_plan = SubscriptionHistory::where('user_id', $auth_user->id)->first();

        //     if(!$find_plan){
        //         $notify_message = trans('translate.You do not have active plan, please renew or purchase');
        //         return response()->json([
        //             'message' => $notify_message,
        //         ], 403);
        //     }

        //     if($find_plan->expiration_date != 'lifetime' && date('Y-m-d') > $find_plan->expiration_date){

        //         $notify_message = trans('translate.You subscription plan has expired, please renew or purchase');
        //         return response()->json([
        //             'message' => $notify_message,
        //         ], 403);
        //     }

        //     $existing_listing = $job_posts = Listing::where('seller_id', $auth_user->id)->count();

        //     if($find_plan->max_listing != '-1' && $existing_listing >= $find_plan->max_listing){
        //         $notify_message = trans('translate.You subscription plan limit exceeded, please renew or purchase new plan');
        //         return response()->json([
        //             'message' => $notify_message,
        //         ], 403);
        //     }
        // }


        $listing = new Listing();

        if ($request->thumb_image) {
            $file_path = uploadPublicFile($request->thumb_image, 'uploads/custom-images');
            $listing->thumb_image = $file_path;
        }

        $listing->seller_id = $auth_user->id;
        $listing->category_id = $request->category_id;
        $listing->sub_category_id = $request->sub_category_id;
        $listing->slug = $request->slug;
        $listing->status = 'enable';
        $listing->is_draft = 'draft';
        $listing->thumb_image = 'default.png';
        $listing->save();



        $languages = Language::all();
        foreach ($languages as $language) {
            $listing_translate = new ListingTranslation();
            $listing_translate->lang_code = $language->lang_code;
            $listing_translate->listing_id = $listing->id;
            $listing_translate->title = $request->title;
            $listing_translate->description = $request->description;
            $listing_translate->save();
        }


        $listing = Listing::findOrFail($listing->id);

        $listing_translate = ListingTranslation::where(['listing_id' => $listing->id, 'lang_code' => admin_lang()])->first();

        $notify_message = trans('translate.Created successfully, please awaiting for admin approval');
        return response()->json([
            'message' => $notify_message,
            'listing' => $listing,
            'listing_translate' => $listing_translate,
        ]);
    }



    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit(Request $request, $id)
    {
        $categories = Category::where('status', 'enable')->get();

        $listing = Listing::findOrFail($id);


        $lang_code = admin_lang();
        if ($request->lang_code) {
            $lang_code = $request->lang_code;
        }
        $listing_translate = ListingTranslation::where(['listing_id' => $id, 'lang_code' => $lang_code])->first();

        $listing_package = ListingPackage::where('listing_id', $id)->first();

        $galleries = ListingGallery::where('listing_id', $id)->get();


        $sub_categories = SubCategory::where('status', 'enable')->latest()->get();

        // $sub_categories = SubCategory::where('category_id', $listing->category_id)->with('translate')->get();

        return response()->json([
            'categories' => $categories,
            'sub_categories' => $sub_categories,
            'listing' => $listing,
            'listing_translate' => $listing_translate,
            'listing_package' => $listing_package,
            'galleries' => $galleries,
        ]);
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(ListingBasicRequest $request, $id)
    {
        $listing = Listing::findOrFail($id);

        if ($request->lang_code == admin_lang()) {

            if ($request->thumb_image) {
                $file_path = uploadPublicFile($request->thumb_image, 'uploads/custom-images', $listing->thumb_image);
                $listing->thumb_image = $file_path;
            }

            $listing->category_id = $request->category_id;
            $listing->sub_category_id = $request->sub_category_id;
            $listing->save();
        }

        $listing_translate = ListingTranslation::findOrFail($request->translate_id);
        $listing_translate->title = $request->title;
        $listing_translate->description = $request->description;
        $listing_translate->save();



        $listing = Listing::findOrFail($listing->id);

        $listing_translate = ListingTranslation::where(['listing_id' => $listing->id, 'lang_code' => $request->lang_code ?? admin_lang()])->first();

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

    public function store_listing_package(ListingPackageRequest $request, $id)
    {
        $listing = Listing::find($id);

        if (!$listing) {
            $notify_message = trans('Service not found');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }


        $package = ListingPackage::where('listing_id', $id)->first();

        if (!$package) {
            $package = new ListingPackage();
        }

        $package->listing_id = $listing->id;
        $package->basic_name = 'Basic';
        $package->basic_description = $request->basic_description;
        $package->basic_price = $request->basic_price;
        $package->basic_delivery_date = $request->basic_delivery_date;
        $package->basic_revision = $request->basic_revision;
        $package->basic_fn_website = $request->basic_fn_website;
        $package->basic_page = $request->basic_page;
        $package->basic_responsive = $request->basic_responsive;
        $package->basic_source_code = $request->basic_source_code;
        $package->basic_content_upload = $request->basic_content_upload;
        $package->basic_speed_optimized = $request->basic_speed_optimized;

        $package->standard_name = 'Standard';
        $package->standard_description = $request->standard_description;
        $package->standard_price = $request->standard_price;
        $package->standard_delivery_date = $request->standard_delivery_date;
        $package->standard_revision = $request->standard_revision;
        $package->standard_fn_website = $request->standard_fn_website;
        $package->standard_page = $request->standard_page;
        $package->standard_responsive = $request->standard_responsive;
        $package->standard_source_code = $request->standard_source_code;
        $package->standard_content_upload = $request->standard_content_upload;
        $package->standard_speed_optimized = $request->standard_speed_optimized;

        $package->premium_name = 'Premium';
        $package->premium_description = $request->premium_description;
        $package->premium_price = $request->premium_price;
        $package->premium_delivery_date = $request->premium_delivery_date;
        $package->premium_revision = $request->premium_revision;
        $package->premium_fn_website = $request->premium_fn_website;
        $package->premium_page = $request->premium_page;
        $package->premium_responsive = $request->premium_responsive;
        $package->premium_source_code = $request->premium_source_code;
        $package->premium_content_upload = $request->premium_content_upload;
        $package->premium_speed_optimized = $request->premium_speed_optimized;
        $package->save();

        $notify_message = trans('Package information added successful');
        return response()->json([
            'message' => $notify_message,
            'listing' => $listing,
            'package' => $package,
        ]);
    }

    public function listing_seo(Request $request, $id)
    {
        $listing = Listing::find($id);

        if (!$listing) {
            $notify_message = trans('Service not found');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }

        $listing->tags = $request->tags;
        $listing->seo_title = $request->seo_title ? $request->seo_title : $request->title;
        $listing->seo_description = $request->seo_description ? $request->seo_description : $request->title;
        $listing->save();

        $notify_message = trans('SEO information added successful');
        return response()->json([
            'message' => $notify_message,
        ]);
    }




    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        $order_qty = Order::where('listing_id', $id)->count();

        if ($order_qty > 0) {
            $notify_message = trans('translate.Multiple order created under it, so you can not delete it');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }

        $listing = Listing::find($id);

        if (!$listing) {
            $notify_message = trans('Service not found');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }


        $old_image = $listing->thumb_image;

        deleteFile($old_image);

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

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

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

            $gallery->delete();
        }

        $listing->delete();

        $notify_message =  trans('translate.Delete Successfully');
        return response()->json([
            'message' => $notify_message,
        ]);
    }

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

        $listing = Listing::find($id);

        if (!$listing) {
            $notify_message = trans('Service not found');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }

        foreach ($request->file as $index => $image) {
            $gallery_image = new ListingGallery();

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

            $gallery_image->listing_id = $id;
            $gallery_image->save();
        }

        if ($request->file) {
            foreach ($request->file as $index => $image) {
                $gallery_image = new ListingGallery();

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

                $gallery_image->listing_id = $id;
                $gallery_image->save();
            }
        }


        return response()->json([
            'message' => trans('translate.Images uploaded successfully'),
        ]);
    }

    public function delete_listing_gallery($id)
    {
        $gallery = ListingGallery::findOrFail($id);
        $old_image = $gallery->image;

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

        $gallery->delete();

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

    public function listing_status($id)
    {
        $service = Listing::findOrFail($id);
        if ($service->status == 'enable') {
            $service->status = 'disable';
            $service->save();
            $message = trans('translate.Status Changed Successfully');
        } else {
            $service->status = 'enable';
            $service->save();
            $message = trans('translate.Status Changed Successfully');
        }

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

    public function listing_publish(Request $request, $id)
    {
        $listing = Listing::find($id);

        if (!$listing) {
            $notify_message = trans('Service not found');
            return response()->json([
                'message' => $notify_message,
            ], 403);
        }

        if ($listing->is_draft == 'no') {
            return response()->json([
                'message' => trans('Publish request already send'),
            ], 403);
        }

        $listing->is_draft = 'no';
        $listing->save();

        return response()->json([
            'message' => trans('Your request has been submited, please await for admin approval'),
        ]);
    }

    public function getSubcategories($categoryId)
    {
        $subcategories = SubCategory::where('category_id', $categoryId)
            ->with('translate')
            ->get();

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