<?php

namespace App\Http\Controllers\Admin;

use App\Models\Service;
use App\Lib\CurlRequest;
use App\Models\Category;
use App\Models\ApiProvider;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Database\Eloquent\Collection;

class ServicesController extends Controller
{

    public function index(){
        $pageTitle = 'All Services';
        $services = Service::with(['category','provider'])->orderBy('created_at','desc')->paginate(getPaginate());
        $apiProviders = ApiProvider::where('status',1)->latest()->get();
        $categories = Category::where('status',1)->latest()->get();
        return view('admin.services.index',compact('pageTitle','services','apiProviders','categories'));
    }

    public function create(){
        $pageTitle = 'Add Service';
        $categories = Category::where('status',1)->get();
        $apiLists   = ApiProvider::where('status',1)->get();
        return view('admin.services.create',compact('pageTitle','categories','apiLists'));
    }

    public function store(Request $request){

        $request->validate([
            'name'=>'required|unique:services,name',
            'price'=>'required|numeric',
            'min'=>'required',
            'max'=>'required',
            'category_id' => function ($attribute, $value, $fail) use ($request) {
                if (empty($value) && empty($request->category)) {
                    $fail('Category  is required.');
                }
            },
            'category' => function ($attribute, $value, $fail) use ($request) {
                if (empty($value) && empty($request->category_id)) {
                    $fail('Category  is required.');
                }
            },
        ]);


        if(isset($request->category)){
            $existsCategory = Category::where('name',$request->category)->first();
            if($existsCategory){
             $category = $existsCategory;
            }else{
                $category = new Category();
                $category->name = $request->category;
                $category->status = $request->status == 1  ? 1 : 0;
                $category->save();
            }
        }

        $service = new Service();
        $service->api_provider_id = $request->api_provider_id ?? 0;
        $service->api_service_id  = $request->api_service_id ?? 0;
        $service->name = $request->name;
        $service->category_id = $request->category_id ?? $category->id;
        $service->price = $request->price;
        $service->min = $request->min;
        $service->max = $request->max;
        $service->status = $request->status == 1  ? 1 : 0;
        $service->drip_feed = $request->drip_feed == 1  ? 1 : 0;
        $service->details = $request->details;
        $service->save();

        $notify[] = ['success', 'service has been created successfully'];
        return to_route('admin.services.index')->withNotify($notify);
    }

    public function edit($id){
        $pageTitle = 'Update';
        $services = Service::findOrFail($id);
        $categories = Category::where('status',1)->get();
        return view('admin.services.edit',compact('pageTitle','categories','services'));
    }

    public function update(Request $request ,$id){
        $request->validate([
            'name'=>'required',
            'price'=>'required|numeric',
            'category_id'=>'required',
            'min'=>'required',
            'max'=>'required',
        ]);

        $service = Service::findOrFail($id);
        $service->name = $request->name;
        $service->category_id = $request->category_id;
        $service->price = $request->price;
        $service->min = $request->min;
        $service->max = $request->max;
        $service->status = $request->status == 1  ? 1 : 0;
        $service->drip_feed = $request->drip_feed == 1  ? 1 : 0;
        $service->api_provider_id = $request->api_provider_id ? $request->api_provider_id : 0;
        $service->api_service_id = $request->api_service_id ? $request->api_service_id : 0;
        $service->details = $request->details;
        $service->save();

        $notify[] = ['success', 'service has been updated successfully'];
        return to_route('admin.services.index')->withNotify($notify);
    }

    public function statusChange(Request $request){

        $service = Service::findOrFail($request->id);
        $service->status = $request->status;
        $service->save();

        $notify[] = ['success', 'Service has been status change successfully'];
        return back()->withNotify($notify);
    }

    public function filter(Request $request)
    {
        $pageTitle = 'Search Services';
        $query = Service::with(['category', 'provider']);

        if ($request->filled('search')) {
            $query->where('name', 'LIKE', '%' . $request->input('search') . '%');
        }

        if ($request->filled('category')) {
            $query->where('category_id', $request->input('category'));
        }

        if ($request->filled('provider')) {
            $query->where('api_provider_id', $request->input('provider'));
        }

        $services = $query->latest()->paginate(getPaginate());

        $apiProviders = ApiProvider::latest()->get();
        $categories = Category::where('status', 1)->latest()->get();

        return view('admin.services.index', compact('pageTitle', 'services', 'apiProviders', 'categories'));
    }

    //Api services
    public function fetchApiServices($id)
    {
        $api = ApiProvider::where('status',1)->findOrFail($id);
        $pageTitle  = $api->name ." Services";
        $categories = Category::where('status',1)->get();

        $existsServices = Service::where('api_provider_id', $api->id)->count();
        $url = $api->api_url;

        $arr = [
            'key'=> $api->api_key,
            'action'=> 'services',
        ];

        $response = CurlRequest::curlPostContent($url, $arr);
        $response = json_decode($response);


        if (@$response->error) {
            $notify[] = ['error', @$response->error];
            return back()->withNotify($notify);
        }

        $data = [];
        foreach ($response as $value) {
            $value->api_id = $id;
            array_push($data, $value);
        }

        $response = collect($data);
        $response = $response->skip($existsServices);
        $services = $response;

        return view('admin.services.api_services', compact('pageTitle', 'services','categories'));
    }

    //bulk service import
    public function getApiServices(Request $request,$id)
    {
        $provider = ApiProvider::where('status',1)->findOrFail($id);
        $existsServices = Service::where('api_provider_id', $id)->count();
        $pageTitle = $provider->name." Services list";
        $url = $provider->api_url;

        $arr = [
            'key'=> $provider->api_key,
            'action' =>'services',
        ];

        $response = CurlRequest::curlPostContent($url, $arr);
        $response = json_decode($response);

        if (@$response->error) {
            $notify[] = ['error', @$response->error];
            return back()->withNotify($notify);
        }

        $data = [];
        foreach($response as $value) {
            $value->api_id = $id;
            array_push($data, $value);
        }

        $response = collect($data);
        $response = $response->skip($existsServices);

        $apiServiceLists = $this->paginate($response, getPaginate(50), null,['path' => route('admin.services.get.api', $id)]);

        return view('admin.services.show_api_services', compact('apiServiceLists','provider','pageTitle'));
    }

    public function importSingle(Request $request)
    {
        // Check exists categories
        $category = Category::where('name', $request->category)->first();
        if (!$category) {
            $category = new Category();
            $category->name =$request->category;
            $category->status = 1;
            $category->save();
        }

        // Check exists services
        $existService = Service::where('api_provider_id',$request->provider)
                                ->where('api_service_id',$request->id)
                                ->exists();

        if (!$existService) {
            $increased_price = ($request->rate / 100) * $request->price_peentage_increase;

            $service = new Service();
            $service->name = $request->name;
            $service->category_id = $category->id;
            $service->min = $request->min;
            $service->max = $request->max;
            $service->price = $request->rate + $increased_price;
            $service->status = 1;
            $service->api_provider_id = $request->provider;
            $service->api_service_id = $request->id;
            $service->api_provider_price = $request->rate;
            $service->drip_feed = $request->dripfeed ?? 0;
            $service->save();

            $notify[] = ['success', 'Sevices has been added successfully'];
            return back()->withNotify($notify);
        } else {
            $notify[] = ['warning', 'Already have this service'];
            return back()->withNotify($notify);
        }
    }

    public function importMulti(Request $request)
    {
        $provider = ApiProvider::findOrFail($request->provider_id);
        $url = $provider->api_url;
        $arr = [
            'key' => $provider->api_key,
            'action' => 'services',
        ];
        $response = CurlRequest::curlPostContent($url, $arr);
        $apiServicesData = json_decode($response);

        $count = 0;
        foreach($apiServicesData as $apiService) {
            $category = Category::where('name', $apiService->category)->first();
            if (!$category) {
                $category = new Category();
                $category->name = $apiService->category;
                $category->status = 1;
                $category->save();
            }

            $existingService = Service::where('api_service_id', $apiService->service)->exists();

            if (!$existingService) {
                $increased_price = ($apiService->rate / 100) * $request->percentage ?? 10;
                $service = new Service();
                $service->name = $apiService->name;
                $service->category_id = $category->id;
                $service->min = $apiService->min;
                $service->max = $apiService->max;
                $service->price = $apiService->rate + $increased_price;
                $service->status = 1;
                $service->api_provider_id = $request->provider_id;
                $service->api_service_id = $apiService->service;
                $service->api_provider_price = $apiService->rate;
                $service->drip_feed = $apiService->dripfeed;
                $service->save();
            }

            $count++;
            if ($request->import_quantity != 'all' && $request->import_quantity == $count) {
                break;
            }
        }

        $notify[] = ['success', 'Multiple services have been created successfully'];
        return back()->withNotify($notify);
    }

    public function paginate($items, $perPage = 15, $page = null, $options = [])
    {
        $page  = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }


}
