<?php

namespace App\Http\Controllers;

use App\Models\Recurring;
use App\Models\Sale;
use App\Models\User;
use App\Services\Package;
use App\Services\CreditReportService;
use App\Services\Encryption;
use App\Services\Payment\GateWay;
use App\Services\Payment\Payment;
use App\Services\SmartCredit\SmartCredit;
use App\Utility\PdfWriter;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function testing(Request $request){
             $this->updateLastProcessDate();
            $this->updateUserAccessEndDateDate();
//        $dtr = getStringToDateTime( '20230301094338','Y-m-d');
//        dd($dtr);
//             echo date('m/d/Y H:i:s', 20230301094338);
//             echo date('m/d/Y H:i:s', 20230302021811);
//           $dtr = strtotime('20230301094338');
//        $dtr1 = strtotime('20230302021811');
//        $dtr = date('m/d/Y H:i:s', $dtr);
//        echo "date 1 :". $dtr;
//        $dtr1 = date('m/d/Y H:i:s', $dtr1);
//        echo "<br/>"." date 2 :". $dtr1;
//       $recurringData = (new Recurring())->getRecurringDataForScheduler();

//        $this->testrecurringPackage();

//          $this->subscriptionUpdateByCronJob();

//        $id=[51,52,53];
//        $returndata=  $this->deleteUser($id);
//        dd($returndata);

//        $client_key = "ddeada92-6310-4850-82c4-0b99159b9339";
//                $sc = (new SmartCredit($client_key))->security_questions();
//                dd($sc);
//        $this->generateCurrentPDF();
//        $inputData['email'] = "ciydugitrj2002@vusra.com";
//        $inputData['planType'] = "PREMIUM";
//        $inputData['password'] = "Nop@ss1234";
//        $inputData['first_name'] = "Adam";
//        $inputData['last_name'] = "Miller";
//        $inputData['client_ip'] = getClientIpAddress();
//        $inputData['zip'] = "91709";
//        $inputData['street'] = "Ironwood Dr Chino Hills";
//        $inputData['state']="CA";
//        $inputData['phone'] = "(317) 328-0603";
//        $inputData['city']="California(CA)";
//        $inputData['dob'] = "04/15/1990";
//        $inputData['ssn'] = "555-55-5555";
//        $inputData['partial_ssn'] = "5555";
//        $inputData['card_number'] = "4111111111111111";
//        $inputData['cvv'] = "123";
//        $inputData['expiry'] = "01/25";
//        $inputData['amount'] = 10.00;
//        $inputData['sqa_answer']="test";
//        $inputData['sqa_question']=1;
//
//        $smart_credit = (new SmartCredit(config('app.CLIENT_KEY')))
//            ->setData($inputData)
//            ->register()
//            ->register();

//        $inputData['sqa_answer'] = "hawk";
//        $inputData['sqa_question'] = 1;
//        $inputData['company'] = 'CHTL';
//        $inputData['address1'] = 'abcd';
//        $inputData['address2'] = 'abed';
//        $inputData['city'] = 'ctg';
//        $inputData['state'] = 'ctg';
//        $inputData['zip'] = 'ctg';
//        $inputData['country'] = 'ctg';
//        $inputData['phone'] = 'ctg';
//        $inputData['fax'] = 'ctg';
//        $inputData['website'] = 'ctg';
//        $inputData['order_id'] = generateOrderId();
//        $inputData['order_description'] = 'adfsdfdf';
//        $inputData['tax'] = 1;
//        $inputData['shipping'] =1;
//        $inputData['ponumber']="PO1234";

//            $inputData['ip']=getClientIpAddress();

//        $inputData['recurring'] = 'add_subscription';
//        $inputData['plan_payments'] = 0;
//        $inputData['plan_amount'] = 5.00;
//        $inputData['plan_name'] = 'creditzombies';
//        $inputData['plan_id'] = '01';
//        $inputData['plan_id'] = rand(0,999);
//        $inputData['day_frequency']= false;
        $inputData['month_frequency']= '1-1';
        $inputData['day_of_month']= 31;
        $inputData['ccnumber']= "4111111111111111";
        $inputData['ccexp']= "10/25";
        //update subscription
//        $inputData['recurring'] = 'update_subscription';
//        $inputData['subscription_id'] = 7625231059;

        //get information transaction id
//        $inputData['type']= 'capture';
//        $inputData['security_key']= '';
//        $inputData['transaction_id']= 7625231059;
//        $inputData['amount']= 5.0;


        $client_key = "ddeada92-6310-4850-82c4-0b99159b9339";
//        $sc = (new SmartCredit($client_key))
//              ->setData($inputData)
//              ->register()
//              ->register();
//
//        dd($sc);
//        $response = (new ayment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $inputData))->makeRecurringPayment();
//      $returnData=  (new Package())-> recurringPackage();
//        dd($response,$inputData['plan_id']);
    }

    private function testforimport()
    {
        $inputData['email'] = 'faust_89@ukr.net' ;
        $inputData['password'] = 'Faust_4639672';
        $inputData['ssn'] = "5150";
                $inputData['source_type'] = 1;

//        $inputData['email'] = 'starstudjesse44@gmail.com' ;
//        $inputData['password'] = 'Catalina@05';
//        $inputData['ssn'] = "0653";
//        $inputData['source_type'] = 1;


//        $inputData['email'] = 'stevetest@consumerdirect.com' ;
//        $inputData['password'] = '123456789';
//        $inputData['source_type'] = 3;


        $isValid = (new CreditReportService())->validateUserInCreditReportProvider($inputData);

        dd($isValid);

    }

    private function testrecurringPackage()
    {
        $inputData['first_name'] = 'faust';
        $inputData['last_name'] = 'test';
        $inputData['email'] = 'test@soft.com.net';
        $inputData['card_number'] = '4111111111111111';
        $inputData['expiry'] = '10/25';

        $inputData['street_no'] = 'dd';
        $inputData['street_name'] = 'ff';
        $inputData['city'] = 'sd';
        $inputData['state'] = 'sf';
        $inputData['zip_code'] ='121';
        $inputData['phone'] = '012121';


//        $inputData['email'] = 'starstudjesse44@gmail.com' ;
//        $inputData['password'] = 'Catalina@05';
//        $inputData['ssn'] = "0653";
//        $inputData['source_type'] = 1;


//        $inputData['email'] = 'stevetest@consumerdirect.com' ;
//        $inputData['password'] = '123456789';
//        $inputData['source_type'] = 3;


//        $recurringResponse = (new Package())->recurringPackage($inputData);
//        $paymentData['subscription_id'] = '8019724977';
//        $paymentData['subscription_id'] = '8019722958';


//        1. 8019544042 -2
//2. 8019590113 -2
//3. 8019590105 -1
//3. 8017176034 -1
//4. 8019727001 -0 1
//5. 8179630905 -0 0

//        dd($paymentData['end_date']);
        $paymentData['subscription_id'] = '8019544042';
//        $paymentData['subscription_id'] = '8019590113';
//        $paymentData['subscription_id'] = '8019590105';
//        $paymentData['subscription_id'] = '8017176034';
//        $paymentData['subscription_id'] = '8019727001';
//        $paymentData['subscription_id'] = '8179630905';
//        $paymentData['subscription_id'] = '8019532537';
//                $paymentData['subscription_id'] = '8019727001';
//                $paymentData['subscription_id'] = '8019588105';
//                $paymentData['subscription_id'] = '8019586600';
//                $paymentData['subscription_id'] = '8019552079';
                $paymentData['subscription_id'] = '8025917930';

//        $last_process_date = '2023-01-12 19:57:53';
        $last_process_date = '2023-01-02 00:34:31';
//        $last_process_date = '2023-01-04 10:32:23';
//        $last_process_date = '2023-01-04 10:32:23';
        $paymentData['start_date'] = getDateAfterSpicificDay($last_process_date,1,'YmdHis');
        $paymentData['end_date'] = getCurrentDateTime('YmdHis');
//        $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $paymentData))->deleteSubscription();
        $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $paymentData))->getSubscriptionInfoBySubscriptionId();
dd($response);
        if (!empty($response['data']) && array_key_exists(0,$response['data'])) {

            $search_data =[];
            $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 = $item;

                        break;
                    }

                }

            }

            dd($search_data);
        }

        dd($response['data'],array_key_exists(0,$response['data']));
        dd(is_array($response['data']));
        $current_date = '2023-03-02';

        $filtered_events = array_filter($response['data'], function($var) use ($current_date) {
            $dtr = date('Y-m-d', strtotime($var['date']));
            return $dtr >= $current_date ;
        });
        dd($filtered_events);
//        if($response['status']){
//            (new Recurring())->deleteRecurringBySubscription_id($paymentData);
//        }

        dd($response);

    }

    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 = [];
//                $recurring['last_process_date']
//               dd(getStringToDateTime('20230130082542'));
                $paymentData['start_date'] = getDateAfterSpicificDay($recurring['last_process_date'],1,'YmdHis');
//                $paymentData['start_date'] = '20230201014416';
                $paymentData['end_date'] = getCurrentDateTime('YmdHis');
//                $paymentData['end_date'] = '20230201014416';
                $paymentData['subscription_id'] = $recurring['subscription_id'];
//                dd($paymentData);
                $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $paymentData))->getSubscriptionInfoBySubscriptionId();

                dd($response['data']);
                if (!empty($response['data']) ) {

                    $search_data_by_date = $response['data'];

                    if(!array_key_exists(0,$search_data_by_date))
                    {
                        $search_data_by_date = [];
                        $search_data_by_date[0] = $response['data'];
                    }

                    foreach ($search_data_by_date as $item) {

                        if(!empty($item)) {

                            $logData_subscription['action_by_subscription_start'] = "CLIENT_SUBSCRIPTION_START";

                            $last_payment_date = getStringToDateTime($item['action'][0]['date']);
                            // user update
                            $user_input['last_payment_date'] = $last_payment_date;
                            $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'] = $last_payment_date;
//                            $recurring->update($recurring_input);

                            // sales insert

                            $salesData['order_id'] = $item['order_id'];
                            $salesData['cc_number'] = $item['cc_number'];
                            $salesData['status'] = "1";
                            $salesData['auth_code'] = '';
                            $salesData['transaction_id'] = $item['transaction_id'];
                            $salesData['ip'] = getClientIpAddress();
                            $salesData['user_id'] = $recurring['user_id'];
                            $salesData['recurring_id'] = $recurring['id'];

                            $saleData = (new Sale())->getDataByTransactionId($item['transaction_id']);

                            if(empty($saleData)) {
                                (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);
                }
            }
    }

    public function updateLastProcessDate()
    {
        $recurring_users = (new Recurring())->getRecurrings();
        if(!empty($recurring_users)) {
            foreach($recurring_users as $recurring_user) {
                  $sale_data = (new Sale())->getLatestSalesByUserId($recurring_user['user_id']);
                  if(!empty($sale_data)) {
                      $inputData['last_process_date'] = $sale_data['created_at'];
                      $recurring_user->update($inputData);
                  }
                }
            }
    }
    public function updateUserAccessEndDateDate()
    {
        $users = (new User())->getAllClients();
        if(!empty($users)) {
            foreach($users as $user) {
                $user_access_end_date = null;
                if($user->last_payment_date != null)
                {
                    $user_access_end_date = getDateAfterSpicificDay($user->last_payment_date,config('constant.PAYMENT_INTERVAL_DAY'));
                }
                $inputData['user_access_end_date'] = $user_access_end_date;
                $user->update($inputData);
            }
        }
    }

    private function encryptionTest($request){
        try {
            $encrypt = new Encryption();
            if ($request->type == "encrypt") {
                $response = $encrypt->encryptByPublicKey($request->data);
            } else {
                $response = $encrypt->decryptByPrivateKey($request->data);
            }
        }catch (\Exception $ex){
            $response = $ex->getMessage();
        }

        dd($response);
    }

    public function reverse(Request $request){

        try {
            $encrypt = new Encryption();
            if ($request->type == "encrypt") {
                $response = $encrypt->encryptByPrivateKey($request->data);
            } else {
                $response = $encrypt->decryptByPublicKey($request->data);
            }
        }catch (\Exception $ex){
            $response = $ex->getMessage();
        }

        dd($response);
    }

    public function generateKeys(){

        (new Encryption())->generateKeys();
    }
    private function generateCurrentPDF() {

       $html='<!DOCTYPE html>
<html>
<body>
<img src="1_Deb-Pulak_PI-Ew1L1D1-bureau_EXPERIAN_1666781257.pdfuGwr8.jpg" alt="" style="width: 100%;" />

</body>
</html>';

        $pdfWriter = new PdfWriter();
        $file_path= $this->getfolder();
        $file_name='test.pdf';
//echo $html;exit;
//        $pdfWriter->write($html, $file_path. '/' . $file_name);
        $pdfWriter->mpdfWrite($html, $file_path. '/' . $file_name,$file_name);
        //$pdfWriter->snappyImage($html, $file_path);
    }

    private  function  getfolder()
    {
        $destinationPath = storage_path('app/public/resources/epicvelocity/letters'); // for localhost

        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $folder_name = $destinationPath . '/' . 123 . "_" . time() . '-' . mt_rand(00000, 999999);

        try {
            if (!is_dir($folder_name)) {
                mkdir($folder_name, 0777, true);
            }
        } catch (Exception $e) {
            Log::error($e);

        }

       return  $folder_name;
    }

    private function deleteUser($id)
    {
       return (new User())->deleteUser($id);
    }
}
