<?php

namespace App\Services;

use App\Models\CardToken;
use App\Models\Sale;
use App\Models\TmpSale;
use App\Models\UserPackage;
use App\Services\Payment\GateWay;
use App\Services\Payment\Payment;
use App\Services\Package;
use App\Utility\Email;

class PaymentService
{
    public array $data = [];
    public string $message = "";
    public string $status_code = "";
    public string $customer_token="";
    public string $tracking_token="";
    public string $payment_status_code = "";
    public  string $transaction_id = "";
    public function payment($inputData)
    {
        $modelData=[];
        $result = false;
        $modelData['token']=$inputData['cc-number'];
        $modelData['user_id']=$inputData['User']->id;
        if ($saved = (new CardToken())->createPayment($modelData)) {
            $result = true;
        }
        return $result;

    }
    public  function  getUserPackage($user_id)
    {
        $userPackage = UserPackage::join('packages', 'user_packages.package_id', '=', 'packages.id')
            ->where('user_packages.user_id',$user_id)
            ->first(['user_packages.*', 'packages.amount']);
        return $userPackage;
    }
    public function makePayment($inputData){
        $result = false;
        $this->status_code = config('constant.API_FAILED_CODE');
        $inputData['order_id'] = generateOrderId();
        $inputData['order_description'] = "Creditzombies Package";
        $inputData['ip'] = getClientIpAddress();
        // create pending sale
        $tmpSaleData=[
            'order_id' => $inputData['order_id']
        ];

        $tmpSaleInsertedData = (new TmpSale())->createTmpSale($tmpSaleData);

        // send payment request
        $response = (new Payment(GateWay::getGateWayInstance(config('constant.PAYMENT_GATEWAY.NMI')), $inputData))->pay();

        // log from payment gate way
        appLog([
            'action'=>'PAYMENT_GATEWAY_RESPONSE',
            'response'=>$response
        ]);

        $this->message = $response['message'];

        $sale_status = config('constant.SALE_STATUS.FAILED');
        $inputData['status_code'] = $response['status_code'];

        if($response['status_code'] == config('constant.API_SUCCESS_CODE')){

            $this->status_code = $response['status_code'];
            $sale_status = config('constant.SALE_STATUS.COMPLETED');
            $this->message = __("Successfully paid");

        }

        // from payment response insert sale table with auth_code, trans_id, invoice_id, order_id
        $inputData['sale_status'] = $sale_status;
        $inputData['auth_code'] = $response['auth_code'] ?? "";
        $inputData['transaction_id'] = $response['transaction_id'] ?? "";
        $this->sales($inputData);
        // delete pending sale
        (new TmpSale())->deleteTmpSaleById($tmpSaleInsertedData->id);

        if($inputData['status_code'] == config('constant.API_FAILED_CODE')) {
            $this->paymentFailedMail($inputData);
        }

        if($sale_status == config('constant.SALE_STATUS.COMPLETED')){
            $result = true;
        }

        return [
            'status'=>$result,
            'order_id'=> $inputData['order_id'] ?? 0
        ];
    }
    private function sales($inputData){
        $saleData = [];
        $saleData['order_id'] = $inputData['order_id'];
        $saleData['ip'] = getClientIpAddress();
        $saleData['status'] = $inputData['sale_status'];
        $saleData['auth_code'] = $inputData['auth_code'];
        $saleData['transaction_id'] = $inputData['transaction_id'];
        $saleData['user_id'] = $inputData['user_id'] ?? 0;
        $saleData['cc_number'] =creditCardNumberMasking($inputData['card_number']);
        return (new Sale())->createSale($saleData);
    }

    public function paymentFailedMail($inputData)
    {

        $data['email'] = $inputData['email'];
        $data['email_body'] = $inputData['first_name'] . ' ' . $inputData['last_name'];
        $data['email_subject'] = "Payment Failed";
        $from = null;
        $attachment = null;
        (new Email())->send($data, $data['email_subject'], $from, $attachment, 'email.payment_failed_letter', $data['email']);

    }

}
