public function __construct()
 {
     $this->core = AT_Core::get_instance();
     // if ( !$this->core->get_option( 'theme_is_activated', false ) && is_user_logged_in() ) {
     // 	AT_Notices::set_frontend_notice(
     // 		'<h3>'.__( 'New to AutoDealer?' , AT_TEXTDOMAIN ) . '</h3>' .
     // 		__( 'You almost ready to use full theme features. Please complete two last steps before move your website to production mode.' , AT_TEXTDOMAIN ) .
     // 		'<br />' .
     // 		sprintf(__( '<a href="%1$s">Click here to continue &rarr;</a>' , AT_TEXTDOMAIN ), get_admin_url() . 'admin.php?page=at_site_options_general'),
     // 		$class = 'notice'
     // 	);
     // 	Header('Location: ' . get_admin_url() . 'admin.php?page=at_site_options_general');
     // 	die();
     // 	// exit( __( 'Theme is not activated' , AT_TEXTDOMAIN ) );
     // }
     // SSL and ajax tricks
     // if ( ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] != rtrim( home_url(), '/' ) ) {
     // 	AT_Common::redirect( AT_Router::get_instance()->server('REQUEST_URI'), '301' );
     // }
     $this->uri = AT_Router::get_instance();
     if ($this->uri->get_method() != 'show_underconstruction' && $this->core->get_option('status_site', 'production') == 'underconstruction') {
         AT_Core::show_underconstruction();
     }
     $this->view = $this->core->view;
     $this->load = AT_Loader::get_instance();
     $this->session = AT_Session::get_instance();
     $this->registry = AT_Registry::get_instance();
     $this->load->library('breadcrumbs');
     $this->breadcrumbs = AT_Breadcrumbs::get_instance();
     $validation_rules = $this->load->helper('validation_rules', true);
     $this->validation = $this->load->library('form_validation', true, $validation_rules->rules);
     //$this->validation->set_rules();
     if (AT_Common::is_user_logged() && $this->core->get_option('theme_is_activated', false)) {
         $user_model = $this->load->model('user_model');
         $user_info = $user_model->get_user_by_id(AT_Common::get_logged_user_id());
         $this->registry->set('user_info', $user_info);
         if ($this->core->get_option('confirm_email_enable', true) && !in_array($this->uri->segments(1), array('confirm_email', 'unlogged')) && (is_null($user_info['date_active']) || empty($user_info['date_active']))) {
             AT_Common::redirect('auth/confirm_email');
         }
     }
 }
 public function checkout()
 {
     if (!empty($_POST)) {
         $plan_id = $_POST['plan'];
         $car_id = AT_Session::get_instance()->userdata('paidEntityID');
         $car_model = $this->load->model('car_model');
         $plans = $this->core->get_option('merchant_plan', false);
         // $entityID = $plans[$plan_id];
         $price = $plan['rate'];
         if (isset($_POST['payment_method'])) {
             if ($_POST['payment_method'] === 'paypal') {
                 // Save session data
                 AT_Session::get_instance()->set_userdata('paymentMethod', $_POST['payment_method']);
                 // AT_Session::get_instance()->set_userdata('paymentAmount',$price);
                 AT_Session::get_instance()->set_userdata('paymentPlanID', $plan_id);
                 AT_Session::get_instance()->set_userdata('checkoutAllower', true);
                 AT_Common::redirect('merchant_paypal/query');
             }
         }
     } else {
         AT_Session::get_instance()->unset_userdata('checkoutAllower');
         $this->view->use_layout('header_content_footer')->add_block('content', 'payments/denied', array());
     }
 }
 public function callback()
 {
     $this->validation();
     //Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         $payments_model = $this->load->model('payments_model');
         //we will be using these two variables to execute the "DoExpressCheckoutPayment"
         //Note: we haven't received any payment yet.
         $token = $_GET["token"];
         $payer_id = $_GET["PayerID"];
         //get session variables
         $planID = AT_Session::get_instance()->userdata('paymentPlanID');
         $plan = $this->core->get_option('merchant_plan', array());
         $plan = $plan[$planID];
         $ItemName = $plan['name'];
         $ItemPrice = number_format($plan['rate'], 2);
         $ItemNumber = AT_Session::get_instance()->userdata('paidEntityID');
         //Item Number
         $ItemDesc = $plan['name'] . __('for ', AT_TEXTDOMAIN) . '#' . AT_Session::get_instance()->userdata('paidEntityID');
         $ItemQty = 1;
         // Item Quantity
         $ItemTotalPrice = $ItemPrice * $ItemQty;
         //(Item Price x Quantity = Total) Get total amount of product;
         //Other important variables like tax, shipping cost
         $TotalTaxAmount = 0.0;
         $HandalingCost = 0.0;
         $InsuranceCost = 0.0;
         $ShippinDiscount = 0.0;
         $ShippinCost = 0.0;
         $GrandTotal = $ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount;
         $padata = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payer_id) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . '&RETURNURL=' . urlencode($this->urlReturn) . '&CANCELURL=' . urlencode($this->urlCancel) . '&L_PAYMENTREQUEST_0_NAME0=' . urlencode($ItemName) . '&L_PAYMENTREQUEST_0_NUMBER0=' . urlencode($ItemNumber) . '&L_PAYMENTREQUEST_0_DESC0=' . urlencode($ItemDesc) . '&L_PAYMENTREQUEST_0_AMT0=' . urlencode($ItemPrice) . '&L_PAYMENTREQUEST_0_QTY0=' . urlencode($ItemQty) . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($this->core->get_option('paypal_currency_code', 'USD'));
         //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
         // $paypal= new MyPayPal();
         $this->method = 'DoExpressCheckoutPayment';
         $this->nvp = $padata;
         $httpParsedResponseAr = $this->connect();
         //Check if everything went ok..
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             $remote_transaction_id = isset($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]) ? $httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"] : false;
             $data = array('sid' => 2, 'ack' => $httpParsedResponseAr["ACK"], 'msg' => '', 'payerid' => $payer_id, 'timestamp' => $httpParsedResponseAr["TIMESTAMP"]);
             $payments_model->update_transaction_by_token($token, $data);
             // $this->view->use_layout('header_content_footer')
             // 	->add_block( 'content', 'payments/paypal/success', array( 'response' => $httpParsedResponseAr, 'transaction_id' => $httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"] ) );
             /*
             //Sometimes Payment are kept pending even when transaction is complete. 
             //hence we need to notify user about it and ask him manually approve the transiction
             */
             if (isset($httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) && 'Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 $data = array('sid' => 1, 'payerid' => $payer_id, 'completed_at' => date('Y-m-d H:s:i'));
                 $payments_model->update_transaction_by_token($token, $data);
                 //AT_Session::get_instance()->set_userdata('paypal_transaction_id',$httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
                 // $this->destroy();
                 AT_Common::redirect('payments/success');
                 // $this->view->use_layout('header_content_footer')
                 // 	->add_block( 'content', 'payments/success', array( 'response' => $httpParsedResponseAr, 'transaction_id' => $remote_transaction_id ) );
             } elseif (isset($httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) && 'Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 // AT_Session::get_instance()->set_userdata('paypal_transaction_id',$httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
                 // $this->destroy();
                 $this->view->use_layout('header_content_footer')->add_block('content', 'payments/paypal/pending', array('response' => $httpParsedResponseAr, 'transaction_id' => $remote_transaction_id));
             }
             // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
             // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
             // $padata =
             //                         '&TOKEN='.urlencode($token).
             //                         '&PAYERID='.urlencode($payer_id).
             //                         '&PAYMENTACTION='.urlencode("SALE").
             //                         '&AMT='.urlencode($GrandTotal).
             //                         '&CURRENCYCODE='.urlencode($this->core->get_option( 'paypal_currency_code', 'USD' ));
             // $padata = '&TOKEN='.urlencode($token);
             // $paypal= new MyPayPal();
             // DoExpressCheckoutPayment
             $this->method = 'GetExpressCheckoutDetails';
             $this->nvp = $padata;
             $httpParsedResponseAr = $this->Connect();
             // $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
             if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                 $data = array('sid' => 1, 'ack' => $httpParsedResponseAr["ACK"], 'msg' => '', 'payerid' => $payer_id, 'completed_at' => date('Y-m-d H:s:i'));
                 $payments_model->update_transaction_by_token($token, $data);
                 // $this->destroy();
                 AT_Common::redirect('payments/success');
                 // $this->view->use_layout('header_content_footer')
                 // 	->add_block( 'content', 'payments/success', array( 'response' => $httpParsedResponseAr, 'transaction_id' => $remote_transaction_id ) );
                 // echo '<br /><b>Stuff to store in database :</b><br /><pre>';
                 // echo '<pre>';
                 // print_r($httpParsedResponseAr);
                 // echo '</pre>';
             } else {
                 // $this->destroy();
                 $data = array('sid' => 3, 'ack' => $httpParsedResponseAr["ACK"], 'payerid' => $payer_id, 'msg' => $httpParsedResponseAr["L_SHORTMESSAGE0"]);
                 $payments_model->update_transaction_by_token($token, $data);
                 $this->view->use_layout('header_content_footer')->add_block('content', 'payments/paypal/error', array('response' => $httpParsedResponseAr, 'msg' => $httpParsedResponseAr["L_LONGMESSAGE0"]));
                 // echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
                 // echo '<pre>';
                 // print_r($httpParsedResponseAr);
                 // echo '</pre>';
             }
         } else {
             // $this->destroy();
             $data = array('sid' => 3, 'ack' => $httpParsedResponseAr["ACK"], 'msg' => $httpParsedResponseAr["L_SHORTMESSAGE0"]);
             $payments_model->update_transaction_by_token($token, $data);
             // $payments_model->update_transaction( $transaction_id, $data );
             $this->view->use_layout('header_content_footer')->add_block('content', 'payments/paypal/error', array('response' => $httpParsedResponseAr, 'msg' => $httpParsedResponseAr["L_LONGMESSAGE0"]));
             // echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
             // echo '<pre>';
             // print_r($httpParsedResponseAr);
             // echo '</pre>';
         }
     }
 }
 public static function get_logged_user_id()
 {
     return !self::is_user_logged() ? 0 : AT_Session::get_instance()->userdata('user_id');
 }
 public static function get_instance()
 {
     if (is_null(self::$_instance)) {
         self::$_instance = new self();
     }
     return self::$_instance;
 }
 public function index($page = 1)
 {
     if ($this->uri->is_ajax_request() && !empty($_POST)) {
         try {
             if (!AT_Common::get_logged_user_id()) {
                 throw new Exception('You dont\'t autorized!');
             }
             if (empty($_POST['action']) || empty($_POST['car_id']) || !is_numeric($_POST['car_id'])) {
                 throw new Exception(__('Error!', AT_TEXTDOMAIN));
             }
             switch ($_POST['action']) {
                 case 'car_archive':
                     $post = array('ID' => $_POST['car_id'], 'post_status' => 'archive');
                     wp_update_post($post);
                     $message = __('Car was archived!', AT_TEXTDOMAIN);
                     break;
                 case 'car_republish':
                     if ($this->_get_limit_publish()) {
                         $post_date = current_time('mysql');
                         $post_date_gmt = current_time('mysql', true);
                         $post = array('ID' => $_POST['car_id'], 'post_date' => $post_date, 'post_date_gmt' => $post_date_gmt);
                         wp_update_post($post);
                         $message = date('F d, Y', strtotime($post_date));
                     } else {
                         throw new Exception(__('Publish limit!', AT_TEXTDOMAIN));
                     }
                     break;
                 case 'car_add_best_offer':
                     update_post_meta($_POST['car_id'], '_best_offer', true);
                     $message = __('Remove best offer', AT_TEXTDOMAIN);
                     break;
                 case 'car_remove_best_offer':
                     update_post_meta($_POST['car_id'], '_best_offer', false);
                     $message = __('Add best offer', AT_TEXTDOMAIN);
                     break;
                 case 'promote_top':
                     //update_post_meta( $_POST['car_id'], '_best_offer', true );
                     AT_Session::get_instance()->set_userdata('paidEntityID', $_POST['car_id']);
                     AT_Session::get_instance()->set_userdata('paidEntity', 'promote_top');
                     $redirect_url = AT_Common::site_url('payments');
                     $message = __('Promote to top', AT_TEXTDOMAIN);
                     break;
                 case 'promote_featured':
                     //update_post_meta( $_POST['car_id'], '_best_offer', true );
                     AT_Session::get_instance()->set_userdata('paidEntityID', $_POST['car_id']);
                     AT_Session::get_instance()->set_userdata('paidEntity', 'promote_featured');
                     $message = __('Promote to featured', AT_TEXTDOMAIN);
                     $redirect_url = AT_Common::site_url('payments');
                     break;
                 default:
                     throw new Exception(__('Error!', AT_TEXTDOMAIN));
                     break;
             }
             $response = array('status' => 'OK', 'message' => $message);
             if (isset($redirect_url) && !empty($redirect_url)) {
                 $response['redirect'] = $redirect_url;
             }
         } catch (Exception $e) {
             $response = array('status' => 'ERROR', 'message' => $e->getMessage());
         }
         $this->view->add_json($response)->display();
         exit;
     }
     $car_model = $this->load->model('car_model');
     $user_model = $this->load->model('user_model');
     $paginator = $this->load->library('paginator');
     $count_cars = $car_model->get_cars_count_by_user_id(AT_Common::get_logged_user_id(), 'publish');
     if ($page < 1) {
         $page = 1;
     }
     $paginator = $paginator->get(4, $count_cars, 10, 1, 2, 'profile/vehicles/index/' . $page . '/', 'profile/vehicles/');
     $this->view->use_layout('profile');
     $this->view->add_block('content', 'vehicles/list', array('cars' => $car_model->get_cars_by_user_id(AT_Common::get_logged_user_id(), $paginator['offset'], $paginator['per_page'], 'publish'), 'count_cars' => $count_cars, 'car_status' => 'publish', 'paid' => array('featured' => $this->core->get_option('merchant_module_featured', false), 'top' => $this->core->get_option('merchant_module_promote', false)), 'user_info' => $user_model->get_user_by_id(AT_Common::get_logged_user_id()), 'publish_limit' => $this->_publish_limit))->add_block('content/pagination', 'general/pagination', $paginator);
     $this->breadcrumbs->add_item(__('Account', AT_TEXTDOMAIN), 'profile/');
     $this->breadcrumbs->add_item(__('My cars', AT_TEXTDOMAIN), 'profile/vehicles/');
     $menu_model = $this->load->model('menu_model');
     $this->view->add_block('left_side', 'general/navigation', $menu_model->get_menu('main', 'vehicles'));
 }