<?php

namespace App\Http\Controllers;

use App\Models\Recurring;
use App\Models\Sale;
use App\Models\User;
use App\Services\Package;
use App\Services\Payment\GateWay;
use App\Services\Payment\Payment;
use App\Services\PaymentService;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\PaymentSettingRequest;
use App\Utility\ActionLogCreate;

class PaymentController extends Controller
{
    public function paymentSetting(PaymentSettingRequest $request)
    {

        $message = "Can not update card number.";
        $type = 'error';
        $status_code = config('constant.API_FAILED_CODE');
        $inputData = $request->all();
        $inputData['save_card'] = request('save_card', 0);
        $inputData['clear_card'] = request('clear_card', 0);
        $action = 'PAYMENT_SETTING';
        $inputData['user'] = auth()->user();
        $inputData['ip'] = request()->getClientIp(true);

        $requestData = $this->prepareData($inputData);

        try {
            $findData['user_id'] = $requestData['user_id'];
            $findData['status'] = 1;
            $recurringData = (new Recurring())->getRecurringByUserId($findData);

            if(!empty($recurringData)) {
//                $package = new Package();
//            $package->makePayments($requestData);
                $deleteRecurringData['email'] = $requestData['email'];
                $deleteRecurringData['subscription_id'] = $recurringData['subscription_id'];
                $deleteRecurringResponse = (new Package())->deleteRecurringPackage($deleteRecurringData);

                if ($deleteRecurringResponse['status_code'] == config('constant.API_SUCCESS_CODE')) {
                    $updateRecurring['status'] = 2;
                    $recurringData->update($updateRecurring);

                    $recurringResponse = (new Package())->recurringPackage($requestData);

                     if($recurringResponse['status_code'] == config('constant.API_SUCCESS_CODE')) {
                         Auth::user()->update([
                             'subscription_status' => config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED'),
                             'last_payment_date' => getCurrentDateTime(),
                             'user_access_end_date' => getDateAfterSpicificDay(getCurrentDateTime(),config('constant.PAYMENT_INTERVAL_DAY'))
                         ]);
                         $message = "Card number has been updated successful.";
                         $status_code = config('constant.API_SUCCESS_CODE');
                         $type = 'success';
                     }
                }
            }else{

                $onetimePayment = (new PaymentService())->makePayment($requestData);

                if($onetimePayment['status']) {
                    // for recurring
                    $recurringResponse = (new Package())->recurringPackage($requestData);
                    $this->updateUser($requestData);
                    $message = "Payment and Card number has been updated successful.";
                    $status_code = config('constant.API_SUCCESS_CODE');
                    $type = 'success';
                }
            }

        }catch (\Exception $ex){
            $message = "Can not update card number.";
            $status_code = config('constant.API_FAILED_CODE');
        }

        if ($status_code == config('constant.API_SUCCESS_CODE')) {
            $this->updateCookies($inputData);
            $message = "Card number has been updated successful.";
            $type = 'success';
        }
        ActionLogCreate::logDataCreate($action, getModelDataMasking($inputData), $message, "", $status_code);
        return back()->with([$type => $message]);
    }

    public function  subscriptionUpdateByCronJob()
    {
        $recurringData = (new Recurring())->getRecurringDataForScheduler();

        if(!empty($recurringData)) {

            foreach ($recurringData as $recurring) {

                $logData['action_by_subscription_id_start'] = "CLIENT_SUBSCRIPTION_UPDATE_START";
                $paymentData = [];
                $paymentData['subscription_id'] = $recurring['subscription_id'];
                $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $paymentData))->getSubscriptionInfoBySubscriptionId();

                if (!empty($response['data']) && array_key_exists(0,$response['data'])) {

                    $search_data_by_date = [];
                    $current_date = getCurrentDate();
//                    $current_date ='2023-03-02';

                    foreach ($response['data'] as $item) {

                        if($item['condition'] == 'complete' && array_key_exists(0,$item['action']))
                        {
                            $dtr = getStringToDateTime($item['action'][0]['date'], 'Y-m-d');

                            if($dtr >= $current_date)
                            {
                                $search_data_by_date = $item;

                                break;
                            }

                        }

                    }

                    if(!empty($search_data_by_date)) {

                        $logData_subscription['action_by_subscription_start'] = "CLIENT_SUBSCRIPTION_START";
                        // user update
                        $user_input['last_payment_date'] = getCurrentDateTime();
                        $user_input['subscription_status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
                        $user_input['status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
                        $return_data = (new User())->userupdate($user_input, $recurring['user_id']);

                        // recurring update
                        $recurring_input['last_process_date'] = getCurrentDateTime();
                        $recurring->update($recurring_input);

                        // sales insert

                        $salesData['order_id'] = $search_data_by_date['order_id'];
                        $salesData['cc_number'] = $search_data_by_date['cc_number'];
                        $salesData['status'] = "1";
                        $salesData['auth_code'] = '';
                        $salesData['transaction_id'] = $search_data_by_date['transaction_id'];
                        $salesData['ip'] = getClientIpAddress();
                        $salesData['user_id'] = $recurring['user_id'];
                        $salesData['recurring_id'] = $recurring['id'];
                        (new Sale())->createSale($salesData);
                        $logData_subscription['action_by_subscription_end'] = "CLIENT_SUBSCRIPTION_END";
                        appLog($logData_subscription);
                    }
                }


                $logData['status_code'] = $response['status_code'];
                $logData['message'] = $response['message'];
                $logData['inputData'] = $recurring;
                $logData['action_by_subscription_id_end'] = "CLIENT_SUBSCRIPTION_UPDATE_END";
                appLog($logData);
            }
        }
    }

    private function prepareData($inputData): array
    {
        $user_info = $inputData['user'];
        $amount=0;
        $prepareData['user_id'] = $user_info->id;
        $prepareData['password']=customDecrypt($user_info->password);
        $prepareData['first_name'] = $user_info['first_name'];
        $prepareData['last_name'] = $user_info['last_name'];
        $prepareData['wave']=$user_info->wave;
        $prepareData['last_payment_date']=$user_info->last_payment_date;
        $prepareData['company'] = $user_info['company'] ?? config('app.name');
        $prepareData['street_no'] = $user_info['street_no'];
        $prepareData['street_name'] = $user_info['street_name'];
        $prepareData['city'] = $user_info['city'];
        $prepareData['state'] = $user_info['state'];
        $prepareData['zip_code'] = $user_info['zip_code'];
        $prepareData['country'] = $user_info['country'] ?? 'US';
        $prepareData['phone'] = $user_info['phone'];
        $prepareData['fax'] = $user_info['fax'] ?? "";
        $prepareData['email'] = $user_info['email'];
        $prepareData['website'] = $user_info['website'] ?? "";


        $prepareData['tax'] = 1;
        $prepareData['shipping'] = 1;
        $prepareData['ponumber'] = "PO1234";
        $prepareData['ip'] = $inputData['ip'];

        $prepareData['amount'] = "24.97";
        $prepareData['card_number'] = $inputData['card_number'];
        $prepareData['expiry'] = $inputData['expiry'];
        return $prepareData;
    }

    private function updateCookies($inputData)
    {
        $user_id = $inputData['user']->id;

        if ($inputData['save_card'] == 1) {
            setCache('card_' . $user_id, $inputData['card_number']);
            setCache('expiration_' . $user_id, $inputData['expiry']);
            setCache('cvv_' . $user_id, $inputData['cvv']);
        }

        if ($inputData['clear_card'] == 1) {
            unsetCache('card_' . $user_id);
            unsetCache('expiration_' . $user_id);
            unsetCache('cvv_' . $user_id);
        }
    }

    private function updateUser($inputData)
    {
        $updateUserData['is_import'] = 1;
        $updateUserData['subscription_status'] = 1;
        $updateUserData['wave'] = 1;
        $updateUserData['last_payment_date'] = getCurrentDateTime();
        $updateUserData['user_access_end_date'] = getDateAfterSpicificDay(getCurrentDateTime(),config('constant.PAYMENT_INTERVAL_DAY'));
        (new User())->userupdate($updateUserData,$inputData['user_id']);
    }

}
