<?php

namespace API\Service\Http\Controllers;

use API\User\Http\Resources\UserResource;
use App\Http\Controllers\Controller;
use Mamad\Brand\Models\Brand;
use Mamad\Category\Repositories\CategoryRepository;
use Mamad\Order\Models\Order;
use Mamad\Order\Repository\OrderRepository;
use Mamad\PostMeta\Repository\PostMetaRepository;
use Mamad\Product\Service\CouponService;
use Mamad\Service\Models\Service;
use Illuminate\Http\Request;
use API\Service\Http\Resources\ServiceResource;
use Mamad\Service\Repository\ServiceRepository;
use API\Service\Repositories\APIServiceRepository;
use Mamad\Shop\Service\ShopService;
use Mehrab\Media\Services\MediaFileService;
use Mehrab\OrderService\Http\Requests\OrderService_address_store_request;
use Mehrab\OrderService\Http\Requests\OrderService_store_request;
use Mehrab\OrderService\Repositories\OrderServiceRepo;
use Mehrab\Payment\Gateways\Gateway;
use Mehrab\Payment\Services\PaymentCashService;
use Mehrab\Payment\Services\PaymentOnlineService;
use Mehrab\Service\Repositories\ServiceRepo;
use Mehrab\User\Models\User;
use Mehrab\User\Repositories\UserRepo;


class ServiceController extends Controller
{
    public function recent_Services(){
        $Services=\Mehrab\Service\Models\Service::query()->whereNotNull("parent_id")->orderByDesc("priority")->paginate((int) request()->limit,['*'],"page",\request()->page??1);
        return ServiceResource::collection($Services);
    }
    public function parent_Services(){
        $Services=\Mehrab\Service\Models\Service::query()->whereNull("parent_id")->orderByDesc("priority")->get();
        return ServiceResource::collection($Services);
    }
    public function Service_detail(ServiceRepo $serviceRepo){

        $Service=$serviceRepo->findBySlug_with(request()->slug);
        $related=$Service->parent->children->except($Service->id);
        return [
            "service"=>new ServiceResource($Service),
            "related_services"=> ServiceResource::collection($related)
        ];
    }
    public function search(){
        if(!empty(request()->s)){
            $Services=ServiceRepository::like_not_paginate(request()->s);
        }
        if(!empty(request()->code)){
            $Services=PostMetaRepository::find_by_key_like("technicalCodes",(new Service())->getMorphClass(),request()->code,Service::class);
            $Services=$Services->get()->pluck("metaable")->filter();
        }
        if(!empty(\request()->filter) || !empty(\request()->type)|| !empty(\request()->brand)){
            $brandId=null;
            if(\request()->brand){
                $brand=Brand::query()->where("name",\request()->brand)->first();
                if($brand){
                    $brandId=$brand->id;
                }
            }
            $Services=ServiceRepository::get_Services_by_categories(false,request()->filter,request()->type,$brandId);

        }


        if($Services->isNotEmpty()){
            return ServiceResource::collection($Services);

        }
    }


    public function address_store(OrderService_address_store_request $request)
    {

        list($address,$address_id) = (new OrderServiceRepo())->address_store_frontend($request,$request->user());
        return new UserResource($request->user());
    }

    public function add_order(OrderService_store_request $request, UserRepo $userRepo, ServiceRepo $serviceRepo)
    {

        //$this->authorize('set_order',OrderService::class);
        $service = $serviceRepo->findBySlug_with_questions($request->slug);

        if ($request->media) {
            $idMedia = (MediaFileService::privateUpload($request->media)->id);
        }

        $operator_users = $userRepo->random_user_permission_operator_order();
        $user_address = $userRepo->get_user_address($request->address_id);

        $answers = array();
        $price = 0;

        //validate checkbox
        $questionsCheckbox = $service->questions->where('type', 'checkbox')->toArray();
        list($answers, $price) = $serviceRepo->validate_checkbox($request, $questionsCheckbox, $answers, $price);
//        if (!$answers || !$price) {
//            return 'چک باکس ها کامل شوند';
//        }
        //valid radio
        $questionsRadio = $service->questions->where('type', 'radio')->toArray();
        list($answers, $price) = $serviceRepo->validate_radio($request, $questionsRadio, $answers, $price);
//        if (!$answers || !$price) {
//            return 'رادیو باتن ها کامل شوند';
//        }
        $order = (new OrderServiceRepo())->store_order_frontend($request, $user_address, $operator_users, $service, $answers, $idMedia ?? null,$price);
        if ($order) return ["status"=>"success"];

        return ["status"=>"error"];
    }



    public function cancel_order(Request $request,OrderServiceRepo $orderServiceRepo){
        $cancel = $orderServiceRepo->cancelOrderServiceByUser($request,$request->order_id);
        return new UserResource($request->user());
    }

    public function pay_order(Request $request){
        $orderServiceRepo = new OrderServiceRepo();
        $order = $orderServiceRepo->findByID($request->order_id);
        $amount = $order->price;



        if ($request->paymentMethod == 'onlinePayment' || !isset($request->paymentMethod)){
            PaymentOnlineService::generate($amount,$order, $request->user(),$order->expert_id);
            $gateway_name="zarinpal";

            if($amount > 0 && $gateway_name!="home"){

                return ShopService::send_to_gateway($gateway_name,$amount,$order);

            }



        }elseif ($request->paymentMethod == 'cashPayment' || $amount <= 0){
            PaymentCashService::generate($amount,$order, $request->user(),$order->expert_id);
        }
        return error();
    }


}










