<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Stripe_ach_gateway extends App_gateway
{
    public function __construct()
    {
        parent::__construct();

        $this->setId('stripe_ach');

        $this->setName('Stripe ACH');

        $this->setSettings([
            [
                'name'      => 'api_secret_key',
                'encrypted' => true,
                'label'     => 'settings_paymentmethod_stripe_api_secret_key',
            ],
            [
                'name'  => 'api_publishable_key',
                'label' => 'settings_paymentmethod_stripe_api_publishable_key',
            ],
            [
                'name'          => 'description_dashboard',
                'label'         => 'settings_paymentmethod_description',
                'type'          => 'textarea',
                'default_value' => 'stripe_settings_paymentmethod_description_def_val',
            ],
            [
                'name'             => 'webhook_key',
                'label'            => 'stripe_webhook_key',
                'default_value'    => app_generate_hash(),
                'after'            => '<p class="mbot15">Webhook URL: <br> '.site_url('stripe_ach/gateways/stripe_ach/webhook/<b>Stripe ACH Webhook Key *</b>').'<br>* Change text "Stripe ACH Webhook Key" with your Stripe ACH Webhook Key</p>',
                'field_attributes' => ['required' => true],
            ],
            [
                'name'          => 'currencies',
                'label'         => 'settings_paymentmethod_currencies',
                'default_value' => 'USD,CAD',
            ],
            [
                'name'          => 'fee_surcharge',
                'label'         => 'stripe_settings_fee_surcharge',
                'default_value' => '',
            ],
            [
                'name'          => 'fee_surcharge_type',
                'type'          => 'select', 
                'label'         => 'fee_surcharge_type',
                'values' => ['%','fixed_amount'],
            ],
            [
                'name'          => 'allow_primary_contact_to_update_credit_card',
                'type'          => 'yes_no',
                'default_value' => 1,
                'label'         => 'allow_primary_contact_to_update_credit_card',
            ],
            
            
        ]);
    }

    public function process_payment($data)
    {
        $redirectGatewayURI = 'stripe_ach/gateways/stripe_ach/make_payment';

        $redirectPath = $redirectGatewayURI . '?invoiceid='
        . $data['invoiceid']
        . '&total='
        . $data['amount']
        . '&hash='
        . $data['invoice']->hash;

        redirect(site_url($redirectPath));
    }

    public function finish_payment($data)
    {
        $this->ci->load->library('stripe_core');

        $client           = $this->ci->clients_model->get($data['clientid']);
        $stripeCustomerId = $client->stripe_id;

        $charge = [
            'amount'   => strcasecmp($data['currency'], 'JPY') == 0 ? intval($data['amount']) : $data['amount'] * 100,
            'metadata' => [
                'ClientID' => $data['clientid'],
            ],
            'customer'    => $stripeCustomerId,
            'description' => $data['description'],
            'currency'    => $data['currency'],
        ];

        if (isset($data['stripeToken']) && empty($stripeCustomerId)) {
            $stripeCustomer = $this->ci->stripe_core->create_customer([
                'email'       => $data['email'],
                'source'      => $data['stripeToken'],
                'description' => $client->company,
            ]);

            $this->ci->db->where('userid', $client->userid);
            $this->ci->db->update(db_prefix().'clients', ['stripe_id' => $stripeCustomer->id]);
            $charge['customer'] = $stripeCustomer->id;
        } elseif (isset($data['stripeToken']) && !empty($stripeCustomerId)) {
            $stripeCustomer = $this->ci->stripe_core->get_customer($stripeCustomerId);
            $token          = $this->ci->stripe_core->retrieve_token($data['stripeToken']);
            $sourceFound    = false;

            foreach ($stripeCustomer->sources->data as $source) {
                if ($source->fingerprint == $token->card->fingerprint) {
                    $sourceFound = $source;

                    break;
                }
            }

            $charge['source'] = !$sourceFound
                ? $stripeCustomer->sources->create(['source' => $data['stripeToken']])
                : $sourceFound;
        }

        if (!empty($stripeCustomerId) && isset($data['stripeToken'])) {
            $stripeCustomer = $this->ci->stripe_core->get_customer($stripeCustomerId);
            if (empty($stripeCustomer->default_source)) {
                $stripeCustomer->source = $data['stripeToken'];
                $stripeCustomer->save();
            }
        }

        $result = $this->create_charges($charge);

        return $result;
    }
    public function create_charges($data)
    {
        return \Stripe\Charge::create($data);
    }
    public function subscribenow($data)
    {
        \Stripe\Stripe::setApiKey($this->decryptSetting('api_secret_key'));
        $responce=    \Stripe\Subscription::create([
        "customer" => $data['customer'],
        "items" => [
                       [
                          "plan" => $data['plan'],
                       ],
                 ]
            ]);
           return  ($responce);
    }
    public function create_charge($charge) {
        $this->ci->load->library('stripe_core');
        \Stripe\Stripe::setApiKey($this->decryptSetting('api_secret_key'));
        $result = $this->create_charges($charge);
        return $result;
    }

    public function createCustomer($token_id, $additional_data = []) {
        $this->ci->load->library('stripe_core');
        \Stripe\Stripe::setApiKey($this->decryptSetting('api_secret_key'));
        if (!get_contact_meta(get_contact_user_id(), 'contact_stripe_customer_id'))
        {
            $stripeCustomer = $this->ci->stripe_core->create_customer([
                'source'      => $token_id,
                'description' => $additional_data['description'],
            ]);
            add_contact_meta(get_contact_user_id(), 'contact_stripe_customer_id', $stripeCustomer->id);
        }
    }

    public function verifyAccount($token_id, $amounts = []) {
        $this->ci->load->library('stripe_core');
        \Stripe\Stripe::setApiKey($this->decryptSetting('api_secret_key'));
       
        if (!get_contact_meta(get_contact_user_id(), 'contact_stripe_bank_verified')) {
            try {
              
                $bank_account = \Stripe\Customer::retrieveSource(
                    get_contact_meta(get_contact_user_id(), 'contact_stripe_customer_id'),
                    get_contact_meta(get_contact_user_id(), 'stripe_token_account_id')
                );
                
                $bank_account->verify(['amounts' => [$amounts['amount_1'], $amounts['amount_2']]]);
                
                if ($bank_account->status == 'verified') {
                    add_contact_meta(get_contact_user_id(), 'contact_stripe_bank_verified', $bank_account->status);
                    return true;
                }
                else return false;
            } catch (\Throwable $th) {
               
                return false;
            }  
        }
        return true;
    }
    
}

