<?php

namespace App\Console\Commands;

use App\Models\Recurring;
use App\Models\Sale;
use App\Models\User;
use App\Services\Payment\GateWay;
use App\Services\Payment\Payment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SubscriptionUpdateByCronJob extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscription:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update subscription and payment date by payment api';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Start subscription:update');
        $this->updateSubscription();
        $this->info('End subscription:update');
    }


    private function updateSubscription()
    {
        $recurringData = (new Recurring())->getRecurringDataForScheduler();

        $log_id = time() . rand();
        $logData['log_id'] = $log_id;

        $logData['action'] = "CLIENT_SUBSCRIPTION_UPDATE_START";
        appLog($logData);

        if (!empty($recurringData)) {

            foreach ($recurringData as $recurring) {

                $logData = [];
                $logData['log_id'] = $log_id;
                $logData['action'] = "CLIENT_SUBSCRIPTION_UPDATE_START_IN_LOOP";
                appLog($logData);

                $paymentData = [];
//               dd(getStringToDateTime('20230130082542'));
                $paymentData['start_date'] = getDateAfterSpicificDay($recurring['last_process_date'], 1, 'YmdHis');
                $paymentData['end_date'] = getCurrentDateTime('YmdHis');
                $paymentData['subscription_id'] = $recurring['subscription_id'];

                $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $paymentData))->getSubscriptionInfoBySubscriptionId();

                // log api response
                $logData = [];
                $logData['log_id'] = $log_id;
                $logData['action'] = "SUBSCRIPTION_FROM_API_LOG";
                $logData['response'] = $response;
                $logData['inputData'] = $recurring;
                appLog($logData);

                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[] = $response['data'];
                    }

                    $logData = [];
                    $logData['log_id'] = $log_id;
                    $logData['action'] = "PER_RESPONSE_DATA";
                    $logData['data'] = $search_data_by_date;
                    appLog($logData);

                    foreach ($search_data_by_date as $item) {

                        if (!empty($item)) {
                            $logData_subscription['log_id'] = $log_id;
                            $logData_subscription['action_by_subscription_start'] = "CLIENT_SUBSCRIPTION_START";

                            $logData = [];
                            $logData['log_id'] = $log_id;
                            $logData['action'] = "PER_ITEM_DATA";
                            $logData['item'] = $item;
                            appLog($logData);

                            $date = isset($item['action']['date']) ? $item['action']['date'] : $item['action'][0]['date'];

//                            $last_payment_date = getStringToDateTime($item['action'][0]['date']);

                            $last_payment_date = getStringToDateTime($date);

                            try {
                                DB::beginTransaction();
                                // user update
                               /*
                               $user_input['last_payment_date'] = $last_payment_date;
                                $user_input['user_access_end_date'] = getDateAfterSpicificDay($last_payment_date, config('constant.PAYMENT_INTERVAL_DAY'));
                                $user_input['subscription_status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
                                $user_input['status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
                                (new User())->userupdate($user_input, $recurring['user_id']);
                               */
                                $this->updateUserData($last_payment_date,$recurring['user_id']);

                                // recurring update

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

                                // sales insert

                                $this->insertSalesData($recurring,$last_payment_date,$item);
                                /*
                                $order_id = !empty($item['order_id']) ? $item['order_id'] : generateUniqueId();
                                $salesData['order_id'] = $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'];
                                $salesData['created_at'] = $last_payment_date;

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

                                if (empty($saleData)) {
                                    (new Sale())->createSale($salesData);
                                }
                                */
                                $logData_subscription['message'] = 'Update and insert data successfully';
                                DB::commit();
                            } catch (\Exception $ex) {
                                DB::rollback();
                                $logData_subscription['message'] = $ex->getMessage();

                            }

                            $logData_subscription['transaction'] = $item;
                            $logData_subscription['action_by_subscription_end'] = "CLIENT_SUBSCRIPTION_END";
                            appLog($logData_subscription);
                        }

                    }

                }

                $logData = [];
                $logData['log_id'] = $log_id;
                $logData['action'] = "CLIENT_SUBSCRIPTION_UPDATE_END_IN_LOOP";
                appLog($logData);
            }
        }

        $logData = [];
        $logData['log_id'] = $log_id;
        $logData['action'] = "CLIENT_SUBSCRIPTION_UPDATE_END";
        appLog($logData);
    }

    private function updateUserData($last_payment_date,$user_id)
    {
        $user_input['last_payment_date'] = $last_payment_date;
        $user_input['user_access_end_date'] = getDateAfterSpicificDay($last_payment_date, config('constant.PAYMENT_INTERVAL_DAY'));
        $user_input['subscription_status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
        $user_input['status'] = config('constant.SUBSCRIPTION_STATUS.SUBSCRIBED');
        (new User())->userupdate($user_input, $user_id);
    }

    private function insertSalesData($recurring,$last_payment_date,$item)
    {
        $order_id = !empty($item['order_id']) ? $item['order_id'] : generateUniqueId();

        $salesData['order_id'] = $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'];
        $salesData['created_at'] = $last_payment_date;

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

        if (empty($saleData)) {
            (new Sale())->createSale($salesData);
        }
    }
}
