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

class Stripe_ach extends App_Controller
{
    public function update_bank_details(){
        check_invoice_restrictions($this->input->get('invoiceid'), $this->input->get('hash'));
        if($this->input->post()){
            $data = $this->input->post();
            $this->load->model('invoices_model');
            $invoice_data = $this->invoices_model->get($this->input->get('invoiceid'));
            $client = get_client($invoice_data->clientid);
            $custom_fields = $data['custom_fields'];
            handle_custom_fields_post(get_contact_user_id(), $custom_fields);
            add_contact_meta(get_contact_user_id(), 'stripe_token_id', $data['stripe_token_id']);
            add_contact_meta(get_contact_user_id(), 'stripe_token_account_id', $data['stripe_token_account_id']);
            
            $this->create_customer(get_contact_meta(get_contact_user_id(), 'stripe_token_id'), ['description' => $client->company]);
            set_alert('success', _l('stripe_update_bank_details_sucess'));
            echo json_encode(array(
                'success' => true
            ));
        } else {
            set_alert('danger', _l('stripe_update_bank_details_err'));
            echo json_encode(array(
                'success' => false
            ));
        }
        
    }

    public function create_customer($stripe_token_id, $additional_data) {
        $this->stripe_ach_gateway->createCustomer($stripe_token_id, $additional_data);
    }


    public function complete_purchase($id, $hash)
    {
        check_invoice_restrictions($id, $hash);

        if ($this->input->post()) {
            $data = $this->input->post();
            $total = $data['total'];
            $this->load->model('invoices_model');
            $invoice = $this->invoices_model->get($id);

            load_client_language($invoice->clientid);

            $data['amount'] = $total;

            $data['description'] = str_replace('{invoice_number}', format_invoice_number($invoice->id), $this->stripe_gateway->getSetting('description_dashboard'));

            $data['currency'] = $invoice->currency_name;
            $data['clientid'] = $invoice->clientid;
            $data['email']    = $this->input->post('stripeEmail');

            try {
                $charge        = $this->stripe_gateway->finish_payment($data);
                $transactionid = $charge->id;

                $success         = $this->stripe_gateway->addPayment(
                    [
                      'amount'        => (strcasecmp($data['currency'], 'JPY') == 0 ? $charge->amount : $charge->amount / 100),
                      'invoiceid'     => $invoice->id,
                      'transactionid' => $transactionid,
                      ]
                    );

                set_alert('success', _l($success ? 'online_payment_recorded_success' : 'online_payment_recorded_success_fail_database'));

                redirect(site_url('invoice/' . $invoice->id . '/' . $invoice->hash));
            } catch (Exception $e) {
                set_alert('danger', $e->getMessage());
                redirect(site_url('invoice/' . $invoice->id . '/' . $invoice->hash));
            }
        }
    }

    public function make_payment()
    {

        check_invoice_restrictions($this->input->get('invoiceid'), $this->input->get('hash'));
        $this->load->model('invoices_model');
        $invoice = $this->invoices_model->get($this->input->get('invoiceid'));
        $language = load_client_language($invoice->clientid);
        $data['locale'] = get_locale_key($language);

        $data['invoice'] = $invoice;
        if (is_client_logged_in()) {
            $data['contact'] = $this->clients_model->get_contact(get_contact_user_id());
        }

        if(!empty($invoice->client->stripe_id)){
            $this->load->library('stripe_core');
            $data['stripe_customer'] = $this->stripe_core->get_customer($invoice->client->stripe_id);
        }
        $data['total'] = $this->input->get('total');
       
        echo $this->get_view($data);
    }

    public function verify_bank_account() {
        check_invoice_restrictions($this->input->get('invoiceid'), $this->input->get('hash'));
        if($this->input->post()){
            $data = $this->input->post();
            
            
            $res = $this->stripe_ach_gateway->verifyAccount(get_contact_meta(get_contact_user_id(), 'stripe_token_id'), ['amount_1' => str_replace("0.","",$data['amount_1']), 'amount_2' => str_replace("0.","",$data['amount_2'])]);
            if ($res == true) {
                set_alert('success', _l('stripe_verify_bank_acc_sucess'));
            } else {
                set_alert('danger', _l('stripe_verify_bank_acc_err'));
            }
            redirect(site_url('stripe_ach/gateways/stripe_ach/make_payment?invoiceid='.$this->input->get('invoiceid').'&total='.$this->input->get('total').'&hash='.$this->input->get('hash')));
            
        } else {
            set_alert('danger', _l('stripe_verify_bank_acc_err'));
        }
        
    }

    public function finish_payment() {
        check_invoice_restrictions($this->input->get('invoiceid'), $this->input->get('hash'));
        if($this->input->post()){
            $_post = $this->input->post();
            $invoice = $this->invoices_model->get($_post['invoice_id']);
            $data = [
                'amount' => floatval(get_invoice_total_left_to_pay($_post['invoice_id'])) * 100, 
                'currency' => $invoice->currency_name, 
                'customer' => get_contact_meta(get_contact_user_id(), 'contact_stripe_customer_id'), 
                'metadata' => ['invoice_id' => $_post['invoice_id']]
            ];
            try {
                $charge        = $this->stripe_ach_gateway->create_charge($data);
               
                $transactionid = $charge->id;
                
                set_alert('success', _l($charge->status == 'pending' ? 'online_payment_recorded_success' : 'online_payment_recorded_success_fail_database'));
                
                redirect(site_url('invoice/' . $_post['invoice_id'] . '/' . $_post['hash']));
            } catch (Exception $e) {
                
                set_alert('danger', $e->getMessage());
                redirect(site_url('invoice/' . $_post['invoice_id'] . '/' . $_post['hash']));
            }
            
        } else {
            set_alert('danger', _l('stripe_finish_payment_err'));
        }
    }

    public function get_view($data = [])
    {
        ?>
        <?php echo payment_gateway_head(_l('payment_for_invoice') . ' ' . format_invoice_number($data['invoice']->id)); ?>
        <body class="gateway-stripe">
            <div class="container">
                <div class="col-md-8 col-md-offset-2 mtop30">
                  <div class="mbot30 text-center">
                      <?php echo payment_gateway_logo(); ?>
                    </div>
                    <div class="row">
                    <div class="col-lg-12" id="alerts">
                    <?php
                    $company_name = @get_client($this->invoices_model->get($data['invoice'])->clientid)->company;
                    $alertclass = "";
                    if($this->session->flashdata('message-success')){
                        $alertclass = "success";
                    } else if ($this->session->flashdata('message-warning')){
                        $alertclass = "warning";
                    } else if ($this->session->flashdata('message-info')){
                        $alertclass = "info";
                    } else if ($this->session->flashdata('message-danger')){
                        $alertclass = "danger";
                    }
                    if($this->session->flashdata('message-'.$alertclass)){ ?>
                        <div class="text-center alert alert-<?php echo $alertclass; ?>">
                            <?php
                            echo $this->session->flashdata('message-'.$alertclass);
                            ?>
                        </div>
                    <?php } ?>
                    </div>
                    </div>

                    <div class="row">
                        <div class="panel_s">
                            <div class="panel-body">
                               
                              <?php
                                $bank_details = ['contacts_bank_routing_number','contacts_bank_account_number','contacts_bank_account_holder_name','contacts_bank_account_holder_type'];
                                $custom_fields = get_custom_fields('contacts');
                                $user_bank = [];
                                $bank_details_missing = false;
                                foreach ($custom_fields as $field) {
                                    if(in_array($field['slug'],$bank_details))
                                        $user_bank[$field['slug']] = get_custom_field_value(get_contact_user_id(), $field['id'], 'contacts');
                                    
                                }
                                
                                $ach_stripe_tokken = get_contact_meta(get_contact_user_id(), 'stripe_token_id');
                                $is_stripe_account_verified = get_contact_meta(get_contact_user_id(), 'contact_stripe_bank_verified');
                               
                                if(empty($ach_stripe_tokken)){
                                    
                                    ?>
                                    <h3 class="no-margin">
		                                  <b><?php echo _l('stripe_verify_bank_acc_subj'); ?></b>
		                            </h3>
		                            <hr />
                                    <?php
                                    
                                    echo _l('stripe_new_bank_acc_info')." <b>".$company_name."</b>:</h4><br>";
                                    
                                    echo form_open(site_url('stripe_ach/gateways/stripe_ach/update_bank_details?invoiceid='.$data['invoice']->id.'&total='.$data['total'].'&hash='. $data['invoice']->hash),array('id' => 'bank_details_submit'));
                                        foreach( $custom_fields as $bank_fields ) {
                                            if(in_array($bank_fields['slug'],$bank_details)){
                                                echo '<div class="col-md-6">
                                                    <div class="form-group '.$bank_fields['slug'].'">
                                                        <label for="custom_fields[contacts]['.$bank_fields['id'].']" class="control-label">'.$bank_fields['name'].'</label>
                                                        <input class="form-control" type="text" id="'.$bank_fields['slug'].'" name="custom_fields[contacts]['.$bank_fields['id'].']" value="'.get_custom_field_value(get_contact_user_id(), $bank_fields['slug'], 'contacts').'" required>
                                                    </div>
                                                </div>';
                                            }
                                       }
                                        echo '<div class="col-md-6">';
                                            echo '<button type="submit" name="update_bank_details" value="true" class="btn btn-success mbot15">';
                                            echo  'update bank details';
                                            echo '</button>';
                                        echo '</div>';
                                    echo form_close();

                                    echo '<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>';
                                    echo '<script src="https://js.stripe.com/v3/"></script>';
                                    echo "<script>
                                        var stripe = Stripe('".$this->stripe_ach_gateway->getSetting('api_publishable_key')."');
                                        $('#bank_details_submit').on('submit',function(){
                                            $('#alerts').html('');
                                            $('div').removeClass('has-error');
                                            form = $(this);
                                            stripe.createToken('bank_account', {
                                                country: 'US',
                                                currency: 'usd',
                                                routing_number: $('#contacts_bank_routing_number').val(),
                                                account_number: $('#contacts_bank_account_number').val(),
                                                account_holder_name: $('#contacts_bank_account_holder_name').val(),
                                                account_holder_type: $('#contacts_bank_account_holder_type').val(),
                                            }).then(function(result) {
                                                if(result.error){
                                                    $('#alerts').html('<div class=\"text-center alert alert-danger\">'+result.error.message+'</div>');
                                                    switch(result.error.code){
                                                        case 'routing_number_invalid':
                                                            $('.contacts_bank_routing_number').addClass('has-error');
                                                        break;
                                                        case 'account_number_invalid':
                                                            $('.contacts_bank_account_number').addClass('has-error');
                                                        break;
                                                    }
                                                } else {
                                                    var data = form.serializeArray();
                                                    data.push({name: 'stripe_token_id', value: result.token.id});
                                                    data.push({name: 'stripe_token_account_id', value: result.token.bank_account.id});
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: '".site_url('stripe_ach/gateways/stripe_ach/update_bank_details?invoiceid='.$data['invoice']->id.'&total='.$data['total'].'&hash='. $data['invoice']->hash)."',
                                                        data: data,
                                                        success: (res) => {
                                                            location.reload();
                                                        },
                                                        error: (res) => {
                                                            $('#alerts').html('<div class=\"text-center alert alert-danger\">'+res.statusText+'</div>');
                                                        }
                                                    });
                                                }
                                            });
                                            return false;
                                        });
                                        
                                
                                    </script>";
                                    
                                } else if (!$is_stripe_account_verified) {
                                    
                                    ?>
                                    <h3 class="no-margin">
		                                  <b><?php echo _l('stripe_verify_bank_acc_subj'); ?></b>
		                            </h3>
		                            <hr />
                                    <?php
                                    
                                    echo _l('stripe_verify_bank_acc_info')." <b>".$company_name."</b>:</h4><br>";
                                    
                                    echo form_open(site_url('stripe_ach/gateways/stripe_ach/verify_bank_account?invoiceid='.$data['invoice']->id.'&total='.$data['total'].'&hash='. $data['invoice']->hash),array('id' => 'verify_account'));
                                        
                                    echo '<div class="col-md-6">
                                        <div class="form-group amount_1">
                                            <label for="amount_1" class="control-label">'._l('stripe_payment_gateway_amount').' 1</label>
                                            <input class="form-control" type="text" id="amount_1" name="amount_1" value="" required>
                                        </div>
                                    </div>';
                                    echo '<div class="col-md-6">
                                        <div class="form-group amount_2">
                                            <label for="amount_2" class="control-label">'._l('stripe_payment_gateway_amount').' 2</label>
                                            <input class="form-control" type="text" id="amount_2" name="amount_2" value="" required>
                                        </div>
                                    </div>';
                                       
                                    echo '<div class="col-md-6">';
                                        echo '<button type="submit" name="verify_bank_account" value="true" class="btn btn-success mbot15">';
                                        echo  _l('stripe_payment_gateway_verify_btn');
                                        echo '</button>';
                                    echo '</div>';
                                    echo form_close();

                                    echo '<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>';
                                    echo '<script src="https://js.stripe.com/v3/"></script>';
                                    echo "<script>
                                        var stripe = Stripe('".$this->stripe_ach_gateway->getSetting('api_publishable_key')."');
                                        $('#verify_account').on('submit',function(){
                                            form = $(this);
                                            stripe.create('customers', {
                                                source: 'tokenID',
                                                description: '".$company_name."'
                                            }).then(function (err, customer){
                                                console.log(err);
                                            });
                                        });
                                    </script>";
                                    
                                } else {
                                    
                                    ?>
                                    <h3 class="no-margin">
		                                  <b><?php echo _l('payment_for_invoice'); ?></b>
		                                  <a href="<?php echo site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash); ?>">
		                                    <b>
		                                        <?php echo format_invoice_number($data['invoice']->id); ?>
		                                    </b>
		                                  </a>
		                              <?php echo " (".$company_name.")"; ?>
		                              </h3>
		                              <h4><?php echo _l('payment_total', app_format_money($data['total'], $data['invoice']->currency_name)); ?></h4>
		                              <hr />
                                    <p><b><?= _l('stripe_account_holder_name') ?>: </b> <?= $user_bank['contacts_bank_account_holder_name']; ?></p>
                                    <p><b><?= _l('stripe_account_ends_at') ?>: </b> <?= substr($user_bank['contacts_bank_account_number'], -4); ?></p>
                                    <?php
                                    echo form_open(site_url('stripe_ach/gateways/stripe_ach/finish_payment?invoiceid='.$data['invoice']->id.'&total='.$data['total'].'&hash='. $data['invoice']->hash),array('id' => 'finish_payment'));
                                    echo '<input type="hidden" name="amount" value="'.$data['total'].'">';
                                    echo '<input type="hidden" name="invoice_id" value="'.$data['invoice']->id.'">';
                                    echo '<input type="hidden" name="hash" value="'.$data['invoice']->hash.'">';
                                    echo '<div class="col-md-6">';
                                    echo '<button type="submit"  id="finish_payment" value="true" class="btn btn-success mbot15">';
                                    echo  _l('invoice_html_online_payment_button_text');
                                    echo '</button>';
                                    echo '</div>';
                                    echo form_close();
                                }
                    ?>
                    </div>
                </div>
            </div>
        </div>
        <?php echo payment_gateway_scripts(); ?>
        <?php if(!isset($data['stripe_customer']) || (isset($data['stripe_customer']) && empty($data['stripe_customer']->default_source))) { ?>
            <script>
                $(function(){
                    $('.stripe-button-el').click();
                });
            </script>
         <?php } ?>
        <?php echo payment_gateway_footer(); ?>
    <?php
    }

    public function webhook($key='')
    {
        if(!empty($key)) {
	        $saved_key = $this->stripe_ach_gateway->getSetting('webhook_key');
	        if ($saved_key == $key) {
	            $input = json_decode(file_get_contents('php://input'), true);
	            if($input['data']['object']['status'] == 'succeeded' && !empty($input['data']['object']['metadata']['invoice_id'])) {
	                $success  = $this->stripe_gateway->addPayment(
	                    [
	                        'amount'        => floatval($input['data']['object']['amount']) / 100,
	                        'invoiceid'     => $input['data']['object']['metadata']['invoice_id'],
	                        'transactionid' => $input['data']['object']['id'],
	                    ]
	                );
	            }
	
	        } else {
	            header('HTTP/1.0 403 Not Authorized');
	            echo 'Webhook key is not matching';
	        }
         } else {
            header('HTTP/1.0 403 Not Authorized');
            echo 'Webhook key is missing';
        }
    }
}
