<?php

namespace App\Controllers\Api\V1;

use Exception;
use App\Services\JSpaymentService;
use App\Controllers\BaseController;
use App\Models\PaymentsDetailModel;
use App\Models\InsuranceProductsModel;
use App\Models\WeeklySubscriptionModel;
use CodeIgniter\HTTP\ResponseInterface;

class JsPaymentController extends BaseController
{
    private $jsService;
    protected  $insuranceProductModel;
    protected  $weeklySubscriptionModel;
    protected  $PaymentsDetailModel;

    public function __construct()
    {
        $this->jsService = new JSpaymentService();
        $this->insuranceProductModel = new InsuranceProductsModel();
        $this->weeklySubscriptionModel = new WeeklySubscriptionModel();
        $this->PaymentsDetailModel = new PaymentsDetailModel();
    }

    public function debitInquery()
    {

        try {
            $rules = [
                'mobileNo' => 'required',
            ];
            $errors = [
                'mobileNo' => [
                    'required' => 'Mobile number field is required.',
                ],
            ];
            $input = $this->getApiRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                        ResponseInterface::HTTP_OK
                    );
            }

            // This is the data which pass to api dynamiclly
            $input['merchantType'] = '0088';
            $input['traceNo'] = '000014';
            $input['companyName'] = 'NOVA';
            $input['channelId'] = 'NOVA';
            $input['terminalId'] = 'NOVA';
            $input['productId'] = '10245185';
            $input['pinType'] = '02';
            $input['transactionAmount'] = '20.0';
            $input['reserved1'] = '02';

            $result = $this->jsService->debitInquirys($input);
            if (!empty($result) && $result['DebitInqResponse']['responseCode'] == '00') {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => 'OTP send successfully.',
                            'data' => $result,
                        ]
                    );
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => $result['DebitInqResponse']['responseDetails'][0],
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }

    public function debitPayments()
    {

        try {
            $rules = [
                'mobileNo' => 'required',
                'profileId' => 'required',
                'otpPin' => 'required',
            ];
            $errors = [
                'mobileNo' => [
                    'required' => 'Mobile number field is required.',
                ],
                'profileId' => [
                    'required' => 'Profile field is required.',
                ],
                'otpPin' => [
                    'required' => 'OTP field is required.',
                ],
            ];
            $input = $this->getApiRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                        ResponseInterface::HTTP_OK
                    );
            }

            // This is the data which pass to api dynamiclly
            $input['merchantType'] = '0088';
            $input['traceNo'] = '000014';
            $input['companyName'] = 'NOVA';
            $input['channelId'] = 'NOVA';
            $input['terminalId'] = 'NOVA';
            $input['productId'] = '10245185';
            $input['pinType'] = '02';
            $input['reserved1'] = '02';



            $patientProfileId = $input['profileId'];

            $result = '';
            $package = $this->insuranceProductModel->where('Id', $input['packageId'])->first();
            $result = $this->jsService->debitPayments($input, $package);
            if (!empty($result) && $result['DebitPaymentResponse']['responseCode'] == '00') {
                $SubscriptionId = $this->packageSubscription($package, $patientProfileId);
                $this->paymentDetail($result, $SubscriptionId);
            }
            if (!empty($result) && $result['DebitPaymentResponse']['responseCode'] == '00') {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => $result['DebitPaymentResponse']['responseDetails'][0],
                            'data' => $result,
                        ]
                    );
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => $result['DebitPaymentResponse']['responseDetails'][0],
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }
    // public function makePayment()
    // {

    //     try {
    //         $this->jsService->intiatePyament();
    //         exit;
    //         $rules = [
    //             'merchant_type' => 'required',
    //             'trace_no' => 'required',
    //             'company_name' => 'required',
    //             'date_time' => 'required|valid_date[Y-m-d H:i:s]',
    //             'receiver_mobile_number' => 'required',
    //             'sender_mobile_no' => 'required',
    //             'otp_pin' => 'required',
    //         ];
    //         $errors = [
    //             'merchant_type' => [
    //                 'required' => 'Merchant type field is required.',
    //             ],
    //             'trace_no' => [
    //                 'required' => 'Trace number field is required.',
    //             ],
    //             'company_name' => [
    //                 'required' => 'Company name field is required.',
    //             ],
    //             'date_time' => [
    //                 'required' => 'Date and time field is required.',
    //                 'valid_date' => 'Date and time must be in the format: YYYY-MM-DD HH:MM:SS.',
    //             ],
    //             'receiver_mobile_number' => [
    //                 'required' => 'Receiver mobile number field is required.',
    //             ],
    //             'sender_mobile_no' => [
    //                 'required' => 'Sender mobile number field is required.',
    //             ],
    //             'otp_pin' => [
    //                 'required' => 'OTP pin field is required.',
    //             ],
    //         ];

    //         $input = $this->getApiRequestInput($this->request);
    //         if (!$this->validateApiRequest($input, $rules, $errors)) {
    //             return $this
    //                 ->getApiResponse(
    //                     [
    //                         'statusCode' => 3,
    //                         'message' => array_values($this->validator->getErrors()),
    //                     ],
    //                     ResponseInterface::HTTP_OK
    //                 );
    //         }
    //     } catch (Exception $e) {
    //         return $this->getApiResponse(
    //             [
    //                 'statusCode' => 3,
    //                 'message' => $e->getMessage()
    //             ],
    //         );
    //     }
    // }

    public function verify()
    {
        try {
            $rules = [
                'CNIC' => 'required',
                'MobileNo' => 'required',
            ];
            $errors = [
                'CNIC' => [
                    'required' => 'CNIC field is required.',
                ],
                'MobileNo' => [
                    'required' => 'Mobile number field is required.',
                ],
            ];
            $input = $this->getApiRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                        ResponseInterface::HTTP_OK
                    );
            }
            $result = $this->jsService->accountVerification($input);
            if (!empty($result) && $result['VerifyAccLinkAccResponse']['ResponseCode'] == '00') {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => $result['VerifyAccLinkAccResponse']['ResponseDetails'][0],
                            'data' => $result,
                        ]
                    );
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => '3',
                            'message' => $result['VerifyAccLinkAccResponse']['ResponseDetails'][0],
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }

    public function resetSecret()
    {
        try {
            $result = $this->jsService->resetSecret();
            if (!empty($result)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => 'Secret reset successfully.',
                            'data' => $result,
                        ]
                    );
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => '3',
                            'message' => 'Something went wrong.',
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }

    private function packageSubscription($packageDetail, $patientProfileId)
    {
        $durationString = $packageDetail['Duration'];
        $duration = intval($durationString);

        $totalWeeks = ceil($duration / 7);
        $data = [
            'InsuranceProductId' => $packageDetail['Id'],
            'PatientProfileId' => $patientProfileId,
            'ActiveDate' => date('Y-m-d H:i:s'),
            'ExpiryDate' => date('Y-m-d H:i:s', strtotime('+' . $packageDetail['Duration'])),
            'LastPaidDate' => date('Y-m-d H:i:s'),
            'TotalWeeks' => $totalWeeks,
            'PaidWeeks' => $totalWeeks,
            'Status' => 'Active',
            'VoiceCalls' => $packageDetail['VoiceCallLimit'],
            'VideoCalls' => $packageDetail['VideoCallLimit'],
            'Corporate' => null,
            'ExternalUniqueId' => null,
        ];
        $insertedId = $this->weeklySubscriptionModel->insert($data);
        return $insertedId;
    }
    private function paymentDetail($paymentDetail, $SubscriptionId)
    {
        $debitPaymentResponse = $paymentDetail['DebitPaymentResponse'];

        $data = [
            'WeeklySubscriptionId' => $SubscriptionId,
            'TraceNo'             => $debitPaymentResponse['traceNo'],
            'CompanyName'         => $debitPaymentResponse['companyName'],
            'DateTime'            => date('Y-m-d H:i:s'),
            'Rrn'                 => $debitPaymentResponse['rrn'],
            'TransactionId'       => $debitPaymentResponse['transactionId'],
            'CommissionAmount'    => $debitPaymentResponse['commissionAmount'],
            'TransactionAmount'   => $debitPaymentResponse['transactionAmount'],
            'TotalTransactionAmount' => $debitPaymentResponse['totalTransactionAmount'],
        ];
        $this->PaymentsDetailModel->insert($data);
    }
}
