<?php

namespace Modules\Subscribe\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Modules\Coupon\Services\CouponService;
use Modules\Notification\Enums\ManagementNotificationStatusEnum;
use Modules\Notification\Services\ManagementNotificationService;
use Modules\Notification\Services\NotificationService;
use Modules\Order\Repositories\Payment\MyFatoorahPayment;
use Modules\Order\Services\PaymentService;
use Modules\Package\Services\PackageService;
use Modules\Subscribe\Enums\SubscribePaymentStatusEnum;
use Modules\Subscribe\Enums\SubscribeStatusEnum;
use Modules\Subscribe\Interfaces\SubscribeRepositoryInterface;
use Modules\Subscribe\Models\Subscribe;
use Modules\Product\Models\ProductAttribute;
use Modules\User\Enums\AccountStatusEnum;
use Modules\User\Services\AccountService;

class SubscribeService
{
    private SubscribeRepositoryInterface $subscribeRepository ;
    private PackageService $packageService ;

    public function __construct(SubscribeRepositoryInterface $subscribeRepository,PackageService $packageService)
    {
        $this->subscribeRepository = $subscribeRepository;
        $this->packageService = $packageService;
    }

    public function get(Request $request)
    {
        $subscribes= $this->subscribeRepository->get($request);
        return $subscribes;
    }
    public function getItem(Subscribe $subscribe)
    {
        $subscribe = $this->subscribeRepository->getItem($subscribe);
        return $subscribe;
    }
    public function create(Request $request,$package)
    {
        $token = str_replace(str_split('%\\/:*?"<>|.'), '', bcrypt(rand(11111, 99999) . time()));
        $request->merge(['store_id'=>Auth::user()->store_id,'token'=>$token,'total'=>$package->price,'package_id'=>$package->id]);

        $subscribe = $this->subscribeRepository->create($request);

        $subscribe->delete();
        $content = [
            'token'=>$token,
            'total'=>$package->price
        ];

        $url = (new PaymentService(new MyFatoorahPayment()))->payment($content);

        return $url;
    }
    public function update(Request $request , $subscribe) :Subscribe
    {
        $subscribe = $this->subscribeRepository->update($request, $subscribe);
        if ($subscribe->user_status == AccountStatusEnum::USER->value)
        {
            $requestData = [
                'status' => $subscribe->status,
                'user_id' => $subscribe->user_id,
                'subscribe_id' => $subscribe->id,
            ];
            $this->notificationService->subscribeChangeStatus($request, $requestData);
        }
        return $subscribe;
    }
    public function paymentStatus(Request $request)
    {
        $subscribe = null;
        if (isset($_GET['paymentId'])) {
            $username = Config::get('app.username');
            $password = Config::get('app.password');
            $tokenApi = Config::get('app.tokenApi');
            $transaction = Config::get('app.transaction');

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $tokenApi);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('grant_type' => 'password', 'username' => $username, 'password' => $password)));
            $result = curl_exec($curl);
            $error = curl_error($curl);
            $info = curl_getinfo($curl);
            curl_close($curl);
            $json = json_decode($result, true);

            $access_token = $json['access_token'];
            $token_type = $json['token_type'];
            if (isset($_GET['paymentId'])) {
                $id = $_GET['paymentId'];
            }
            $url = $transaction . $id;
            $soap_do1 = curl_init();
            curl_setopt($soap_do1, CURLOPT_URL, $url);
            curl_setopt($soap_do1, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($soap_do1, CURLOPT_TIMEOUT, 10);
            curl_setopt($soap_do1, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($soap_do1, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($soap_do1, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($soap_do1, CURLOPT_POST, false);
            curl_setopt($soap_do1, CURLOPT_POST, 0);
            curl_setopt($soap_do1, CURLOPT_HTTPGET, 1);
            curl_setopt($soap_do1, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Accept: application/json', 'Authorization: Bearer ' . $access_token));
            $result_in = curl_exec($soap_do1);

            $err_in = curl_error($soap_do1);
            $file_contents = htmlspecialchars(curl_exec($soap_do1));
            curl_close($soap_do1);
            $getRecorById = json_decode($result_in, true);
            $customFiles = explode('&', $getRecorById['ApiCustomFileds']);
            foreach ($customFiles as $value) {
                $field = explode('=', $value);
                $fields[$field[0]] = $field[1];
            }

            $token = $fields['token'];

            $subscribe = $this->subscribeRepository->getItemByToken($token);

            if (in_array($getRecorById['TransactionStatus'], array(1, 2)) && $subscribe) {
                $date = date('Y-m-d',strtotime(Auth::user()->store->expire_subscribe .' + '.$subscribe->package->length.' months'));

                Auth::user()->store->update(['expire_subscribe'=>$date]);
                $subscribe->restore();
                $start_date = date('Y-m-d');
                $end_date = date('Y-m-d',strtotime($start_date.' + '.$subscribe->package->length.' months'));
                $request->merge(['payment_log' => $result_in, 'payment_id' => $getRecorById['InvoiceId'],'token'=>null,'start_date'=>$start_date,'end_date'=>$end_date]);
                $this->subscribeRepository->update($request,$subscribe);

            }
        }
        return $subscribe;
    }

}
