<?php
require "vendor/autoload.php";
use Dompdf\Dompdf;
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class StripePayment extends CI_Controller
{

    public $theme;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('model_customer');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        dt_set_time_zone();
        dt_run_default_query();
        $this->theme = "theme1";
    }
    public function stripe_donation_success()
    {

        $session_id =$this->input->get('session_id');
        $dt_get_all_payment_setting=dt_get_all_payment_setting();
        $get_current_currency=dt_get_current_currency();

        try {

            $stripe_secret_key =$dt_get_all_payment_setting['stripe_secret'];

            $stripe = new \Stripe\StripeClient($stripe_secret_key);
            \Stripe\Stripe::setApiKey($stripe_secret_key);

            $checkout_session = \Stripe\Checkout\Session::retrieve($session_id);
            $donation_id = ($checkout_session->client_reference_id);

            $this->db->from('app_donation');
            $this->db->where('id',$donation_id);
            $donation_data=$this->db->get()->row_array();

            if (isset($donation_data) && $donation_data!=null){

                $payment_intent = ($checkout_session->payment_intent);
                $payment_intent_data = $stripe->paymentIntents->retrieve(
                    $payment_intent,
                    []
                );

                $transaction_id = ($payment_intent_data->latest_charge);
                $payment_by = ($payment_intent_data->metadata->payment_by);
                $payment_type = ($payment_intent_data->metadata->payment_type);

                if ($donation_data['receipt_sent']==false){
                    $this->sendreceipt->generate($donation_id);
                    $update_donation['receipt_sent']=true;
                }

                if (isset($donation_data['cause_id']) && $donation_data['cause_id']>0){
                    dt_get_cause_and_update_staus($donation_data['cause_id']);
                }

                $update_donation['payment_status']='success';
                $update_donation['transaction_id']=$transaction_id;
                $update_donation['transaction_response']=json_encode($checkout_session);

                $this->model_customer->update('app_donation', $update_donation, "id=".$donation_id);
                $this->session->set_userdata("donation_id",$donation_id);
                $this->session->set_flashdata('msg',dt_translate('transaction_success'));
                $this->session->set_flashdata('msg_class', 'success');
                redirect(base_url('success/'));
            }else{
                $this->session->set_flashdata('msg', dt_translate('transaction_fail'));
                $this->session->set_flashdata('msg_class', 'failure');
                redirect(base_url('donate/'));
            }

        } catch (\Exception $exception) {
            return redirect('home')->withErrors(['msg' => trans('system.plans.invalid_payment')]);
        }
    }

    public function stripe_donation_cancelled(Request $request)
    {
        return redirect('home')->with('Error', trans('system.messages.operation_canceled'));
    }

    public function webhook(){
        $json = file_get_contents('php://input');
        $action = json_decode($json, true);

        $data['details']=$json;
        $data['type']="stripe";
        $this->model_customer->insert('app_webhook', $data);

        if (isset($action['event']) && $action['event']=='charge.success'){
            if (isset($action['data']['reference']) && $action['data']['reference']>0){

                $this->db->select('*');
                $this->db->where('id',$action['data']['reference']);
                $donation_data=$this->db->get('app_donation')->row_array();

                if (isset($donation_data) && $donation_data!=null){


                    if (isset($donation_data['cause_id']) && $donation_data['cause_id']>0){
                        dt_get_cause_and_update_staus($donation_data['cause_id']);
                    }

                    if ($donation_data['receipt_sent']==false){
                        $this->sendreceipt->generate($action['data']['reference']);
                        $update_donation['receipt_sent']=true;
                    }

                    $update_donation['payment_status']='success';
                    $update_donation['transaction_id']=isset($action['data']['id'])?$action['data']['id']:"";
                    $update_donation['transaction_response']=json_encode($action);

                    $this->model_customer->update('app_donation', $update_donation, "id=".$action['data']['reference']);
                }
            }
        }
    }
}