<?php
require "vendor/autoload.php";
use Razorpay\Api\Api;
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Front 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 index(){
        $this->session->unset_userdata('app_donation_id');
		//Set Language For Website
        $dt_app_site_setting=dt_app_site_setting();
		$language=trim($dt_app_site_setting['language']);	
		$this->session->set_userdata("language",$language);
		$language_session = $this->session->userdata('language');

        $data['title'] = dt_translate('home');
        $data['home_content_title'] = $this->model_customer->getData('app_content', '*', 'title ="home_content_title"')[0];
        $data['home_content_description'] = $this->model_customer->getData('app_content', '*', 'title ="home_content_description"')[0];
        $this->load->view('front/'.$this->theme.'/index', $data);
    }
    public function privacy_policy(){
        $data['title'] = dt_translate('privacy_policy');
        $data['privacy']=dt_get_cms_page_status('privacy');

        $this->load->view('front/'.$this->theme.'/privacy_policy', $data);
    }

    public function terms_and_conditions(){
        $data['title'] = dt_translate('terms_and_conditions');
        $data['terms']=dt_get_cms_page_status('terms');
        $this->load->view('front/'.$this->theme.'/terms_and_conditions', $data);
    }

    public function about_us(){
        $data['title'] = dt_translate('about_us');
        $this->load->view('front/'.$this->theme.'/about_us', $data);
    }

    public function team(){
        $data['title'] = dt_translate('team');
        $this->load->view('front/'.$this->theme.'/team', $data);
    }

    public function contact_us(){
        $data['title'] = dt_translate('contact_us');
        $this->load->view('front/'.$this->theme.'/contact_us', $data);
    }

    public function volunteer(){
        $data['title'] = dt_translate('volunteer');
        $this->load->view('front/'.$this->theme.'/volunteer', $data);
    }

    public function gallery(){
        $data['title'] = dt_translate('gallery');
        $this->load->view('front/'.$this->theme.'/gallery', $data);
    }

    public function causes(){
        $data['title'] = dt_translate('causes');
        $this->load->view('front/'.$this->theme.'/causes', $data);
    }

    public function cause_details($id){

        $data['title'] = dt_translate('causes')." ".dt_translate('details');
        $id=(int)$id;
        $app_causes= $this->model_customer->getData('app_causes', '*', 'id='.$id);
        if(count($app_causes)==0){
            redirect('causes');
        }

        $data['app_causes']=$app_causes[0];
        $this->load->view('front/'.$this->theme.'/causes_details', $data);
    }

    public function projects(){
        $data['title'] = dt_translate('projects');
        $data['app_projects']= $this->model_customer->getData('app_projects', '*','status="A"');
        $this->load->view('front/'.$this->theme.'/projects', $data);
    }

    public function project_details($id){
        $data['title'] = dt_translate('project')." ".dt_translate('details');
        $id=(int)$id;

        $app_project= $this->model_customer->getData('app_projects', '*', 'id='.$id.' AND status="A"');
        if(count($app_project)==0){
            redirect('projects');
        }

        $data['app_project']=$app_project[0];
        $data['recent_projects']=$this->model_customer->getData('app_projects', '*', 'id!='.$id.' AND status="A"');

        $this->load->view('front/'.$this->theme.'/project_details', $data);
    }

    public function events(){
        $data['title'] = dt_translate('events');
        $data['app_events']= $this->model_customer->getData('app_events', '*','status="A"');
        $this->load->view('front/'.$this->theme.'/events', $data);
    }

    public function event_details($id){

        $data['title'] = dt_translate('event')." ".dt_translate('details');
        $id=(int)$id;

        $app_event= $this->model_customer->getData('app_events', '*', 'event_id='.$id.' AND status="A"');
        if(count($app_event)==0){
            redirect('events');
        }

        $data['app_event']=$app_event[0];
        $data['recent_event']=$this->model_customer->getData('app_events', '*', 'event_id!='.$id.' AND status="A"');

        $this->load->view('front/'.$this->theme.'/event_details', $data);
    }

    public function news(){
        $data['title'] = dt_translate('news');
        $this->load->view('front/'.$this->theme.'/news', $data);
    }

    public function news_details($id){
        $data['title'] = dt_translate('news')." ".dt_translate('details');

        $id=(int)$id;
        $app_news= $this->model_customer->getData('app_news', '*', 'id='.$id);
        if(count($app_news)==0){
            redirect('news');
        }

        $data['app_news']=$app_news[0];
        $data['recent_news']=$this->model_customer->getData('app_news', '*', 'id!='.$id.' AND status="A"');
        $this->load->view('front/'.$this->theme.'/news_details', $data);
    }

    public function donate(){
        $data['title'] = dt_translate('home');
        $orders = "title  ASC";
        $data['app_donation_category'] = $this->model_customer->getData("app_donation_category", "*", "status='A'", "", $orders);

        $this->load->view('front/'.$this->theme.'/donation', $data);
    }

    public function save_contact_us(){
        $name=$this->input->post('name');
        $email=$this->input->post('email');
        $subject=$this->input->post('subject');
        $message=$this->input->post('message');

        $this->form_validation->set_rules('name', dt_translate('name'), 'trim|required');
        $this->form_validation->set_rules('email', dt_translate('email'), 'trim|required');
        $this->form_validation->set_rules('subject', dt_translate('subject'), 'trim|required');
        $this->form_validation->set_rules('message', dt_translate('message'), 'trim|required');

        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        if ($this->form_validation->run() == false) {
            $this->contact_us();
        }else{
            $data['email'] = $this->input->post('email', true);
            $data['subject'] = $this->input->post('subject', true);
            $data['message'] = $this->input->post('message', true);
            $data['name'] = $this->input->post('name', true);
            $data['created_date'] =date("Y-m-d H:i:s");
            $this->model_customer->insert('app_contact_us', $data);

            $this->session->set_flashdata('msg', dt_translate('contact_request_success'));
            $this->session->set_flashdata('msg_class', 'success');

            redirect('contact-us#success');
        }
    }

    /*Donation Action Method*/
    public function donate_action() {

        $this->form_validation->set_rules('donation_type', dt_translate('donation_type'), 'trim|required');
        $this->form_validation->set_rules('first_name', dt_translate('name'), 'trim|required');
        $this->form_validation->set_rules('last_name', dt_translate('email'), 'trim|required');
        $this->form_validation->set_rules('email', dt_translate('subject'), 'trim|required');
        $this->form_validation->set_rules('phone', dt_translate('message'), 'trim|required');
        $this->form_validation->set_rules('amount', dt_translate('message'), 'trim|required');
        $this->form_validation->set_rules('city', dt_translate('message'), 'trim|required');
        $this->form_validation->set_rules('payment_by', dt_translate('message'), 'trim|required');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        if ($this->form_validation->run() == false) {
            $this->donate();
        }else{
            $donation_type=$this->input->post('donation_type',true);
            $first_name=$this->input->post('first_name',true);
            $last_name=$this->input->post('last_name',true);
            $email=$this->input->post('email',true);
            $phone=$this->input->post('phone',true);
            $amount=$this->input->post('amount',true);
            $city=$this->input->post('city',true);
            $payment_by=$this->input->post('payment_by');
            $category_id=$this->input->post("category_id");
            $notes=$this->input->post("notes");
            $cause_id=$this->input->post("cause_id");

            $dt_get_all_payment_setting=dt_get_all_payment_setting();
            $get_current_currency=dt_get_current_currency();

            if(isset($payment_by) && in_array($payment_by,array("stripe","paypal","razorpay","paystack","flutterwave","offline"))){

                $insert['notes'] = $notes;
                $insert['cause_id'] = $cause_id;
                $insert['donation_type'] = $donation_type;
                $insert['first_name'] = $first_name;
                $insert['last_name'] = $last_name;
                $insert['email'] = $email;
                $insert['created_on'] = date("Y-m:d H:i:s");
                $insert['amount'] = $amount;
                $insert['phone'] = $phone;
                $insert['city'] = $city;
                $insert['type']=$payment_by;
                $insert['created_by'] = 1;
                $insert['category_id']=$category_id;
                $app_donation_id = $this->model_customer->insert("app_donation", $insert);

                if($payment_by=="stripe"){

                    if ($dt_get_all_payment_setting['stripe'] && $dt_get_all_payment_setting['stripe']=='Y'){
                        try {

                            //Subscription
                            $stripe = new \Stripe\StripeClient($dt_get_all_payment_setting['stripe_secret']);
                            \Stripe\Stripe::setApiKey($dt_get_all_payment_setting['stripe_secret']);

                            $metaDatas = [
                                'donation_id' => $app_donation_id,
                                'payment_by' => $payment_by,
                                'payment_type' => 'onetime',
                            ];

                            $product = $stripe->products->create([
                                'name' => "Donation to ".dt_get_CompanyName(),
                            ]);

                            //Price
                            $price_array = [
                                'unit_amount' => $amount * 100,
                                'currency' => $get_current_currency['code'],
                                'product' => $product->id
                            ];

                            $price = $stripe->prices->create($price_array);

                            $checkout_session = \Stripe\Checkout\Session::create([
                                'line_items' => [[
                                    'price' => $price->id,
                                    'quantity' => 1
                                ]],
                                'mode' => 'payment',
                                'success_url' => base_url('stripe/stripe-success?session_id={CHECKOUT_SESSION_ID}'),
                                'cancel_url' => base_url('stripe/stripe-cancelled?donation=' . $app_donation_id),
                                'client_reference_id' => $app_donation_id,
                                'metadata' => $metaDatas,
                                'payment_intent_data' => [
                                    'metadata' => $metaDatas
                                ]
                            ]);

                            return redirect($checkout_session->url);

                        } catch (\Exception $e) {
                            $this->session->set_flashdata('msg',$e->getMessage());
                            $this->session->set_flashdata('msg_class', 'failure');
                            redirect(base_url('donate/'));
                        }
                    }else{
                        $this->session->set_flashdata('msg', "Something went wrong. Please try again.");
                        $this->session->set_flashdata('msg_class', 'failure');
                        redirect(base_url('donate/'));
                    }

                }elseif($payment_by=="razorpay"){

                    $this->load->library('razorpay');
                    $razorpay_merchant_key_id=dt_get_payment_setting('razorpay_merchant_key_id');
                    $razorpay_merchant_key_secret=dt_get_payment_setting('razorpay_merchant_key_secret');


                    $api = new Api($razorpay_merchant_key_id, $razorpay_merchant_key_secret);

                    try{
                        $order  = $api->order->create([
                            'receipt'=>$app_donation_id,
                            'amount'=> $amount*100, // amount in the smallest currency unit
                            'currency'=>trim($get_current_currency['code']),
                            'payment_capture'=>1
                        ]);

                        if(isset($order['id']) && $order['id']!=""){

                            $this->razorpay->add_field('key_id',$razorpay_merchant_key_id);
                            $this->razorpay->add_field('order_id',$order['id']);
                            $this->razorpay->add_field('name',dt_get_CompanyName());
                            $this->razorpay->add_field('description',dt_translate('donation'));
                            $this->razorpay->add_field('image',dt_get_CompanyLogo());
                            $this->razorpay->add_field('prefill[name]',$first_name," ".$last_name);
                            $this->razorpay->add_field('prefill[contact]',$phone);
                            $this->razorpay->add_field('prefill[email]',$email);
                            $this->razorpay->add_field('notes[shipping address]',$city);

                            $this->razorpay->add_field('callback_url', base_url('razorpay-success'));
                            $this->razorpay->add_field('cancel_url', base_url('razorpay-cancel'));

                            $this->razorpay->submit();

                        }else{
                            redirect('donate');
                        }
                    }catch (Exception $e){
                        $this->session->set_flashdata('msg',$e->getMessage());
                        $this->session->set_flashdata('msg_class', 'failure');
                        redirect('donate');
                    }
                }else if($payment_by=="paypal"){

                    if (isset($dt_get_all_payment_setting['paypal']) && $dt_get_all_payment_setting['paypal']=='Y'){

                        // integrate paypal
                        $apiContext = new \PayPal\Rest\ApiContext(
                            new \PayPal\Auth\OAuthTokenCredential($dt_get_all_payment_setting['paypal_client_id'],$dt_get_all_payment_setting['paypal_secret_key'])
                        );

                        $payer = new \PayPal\Api\Payer();
                        $payer->setPaymentMethod("paypal");
                        //Itemized information (Optional) Lets you specify item wise information

                        $item1 = new \PayPal\Api\Item();
                        $item1->setName('Donation')
                            ->setCurrency($get_current_currency['code'])
                            ->setQuantity(1)
                            ->setPrice($this->input->post('amount',true));

                        $itemList = new \PayPal\Api\ItemList();
                        $itemList->setItems(array($item1));

                        $amount = new \PayPal\Api\Amount();
                        $amount->setCurrency($get_current_currency['code'])->setTotal($this->input->post('amount',true));

                        $transaction = new \PayPal\Api\Transaction();
                        $transaction->setAmount($amount)
                            ->setItemList($itemList)
                            ->setDescription("Donation Payment Description")
                            ->setInvoiceNumber($app_donation_id);

                        $redirectUrls = new \PayPal\Api\RedirectUrls();
                        $redirectUrls->setReturnUrl(base_url('paypal/success/'.$app_donation_id))
                            ->setCancelUrl(base_url('paypal/cancel/'.$app_donation_id));

                        $payment = new \PayPal\Api\Payment();

                        $payment->setIntent("sale")
                            ->setPayer($payer)
                            ->setRedirectUrls($redirectUrls)
                            ->setTransactions(array($transaction))->setId($app_donation_id);

                        try {
                            $paymentdetail = $payment->create($apiContext);
                            $approvalUrl = $payment->getApprovalLink();
                            return redirect($approvalUrl);
                        } catch (Exception $ex) {
                            $this->session->set_flashdata('msg',$ex->getMessage());
                            $this->session->set_flashdata('msg_class', 'failure');
                            redirect('donate');
                        }

                    }

                }else if($payment_by=="paystack"){

                    $paystack = new Yabacon\Paystack($dt_get_all_payment_setting['paystack_secret_key']);
                    try
                    {
                        $tranx = $paystack->transaction->initialize([
                            'amount'=>$amount,       // in kobo
                            'email'=>$email,         // unique to customers
                            'reference'=>$app_donation_id, // unique to transactions
                        ]);
                    } catch(\Yabacon\Paystack\Exception\ApiException $e){
                        $this->session->set_flashdata('msg',$e->getMessage());
                        $this->session->set_flashdata('msg_class', 'failure');
                        redirect('donate');
                    }

                    // redirect to page so User can pay
                    header('Location: ' . $tranx->data->authorization_url);

                }else if($payment_by=="flutterwave"){

                    if(isset($dt_get_all_payment_setting['flutterwave']) && $dt_get_all_payment_setting['flutterwave']=="Y" && $dt_get_all_payment_setting['flutterwave_public_key']!=null){
                        $this->load->library('flutterwave');

                        $this->flutterwave->add_field('public_key',$dt_get_all_payment_setting['flutterwave_public_key']);
                        $this->flutterwave->add_field('customer[email]',$email);
                        $this->flutterwave->add_field('customer[name]',$first_name." ".$last_name);
                        $this->flutterwave->add_field('meta[token]',$app_donation_id);
                        $this->flutterwave->add_field('tx_ref',$app_donation_id);
                        $this->flutterwave->add_field('amount',$amount);
                        $this->flutterwave->add_field('currency',$get_current_currency['code']);
                        $this->flutterwave->add_field('redirect_url', base_url('flutterwave-payment'));
                        $this->flutterwave->submit();
                    }else{
                        redirect('donate/');
                    }
                }else if($payment_by=="offline"){
                    $this->db->select('*');
                    $this->db->where('id',$app_donation_id);
                    $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($app_donation_id);
                            $update_donation['receipt_sent']=true;
                        }

                        $update_donation['payment_status']='success';
                        $update_donation['transaction_id']=0;
                        $update_donation['transaction_response']=null;

                        $this->model_customer->update('app_donation', $update_donation, "id=".$app_donation_id);

                        $this->session->set_userdata("donation_id",$app_donation_id);
                        $this->session->set_flashdata('msg',dt_translate('transaction_success'));
                        $this->session->set_flashdata('msg_class', 'success');
                        redirect(base_url('success/'));

                    }
                }

            }else{
                redirect('donate/');
            }
        }
    }

    public function getPaypalApiContext($client_id, $secret_key)
    {
        return new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential($client_id,$secret_key)
        );
    }

    public function donation_success(){

        $app_donation_id = $this->session->userdata('donation_id',true);
        if(isset($app_donation_id) && $app_donation_id>0){

            $app_donation_array=$this->model_customer->getData("app_donation", "*", "id=".$app_donation_id);
            if(isset($app_donation_array) && count($app_donation_array)>0){

                $this->session->unset_userdata('donation_id');

                $data['title'] = dt_translate('transaction_successful');
                $data['app_donation']=$app_donation_array[0];
                $this->load->view('front/'.$this->theme.'/donation_success', $data);

            }else{
                redirect('donate/');
            }
        }else{
            redirect('donate/');
        }

    }

}
