<?php
class Stripe extends Shop_Abstract_Payment_Gateway
{
	private $config = array();

	public function init()
	{
		$CI =& get_instance();
		$query = $CI->db->query("SELECT * FROM shop_payment_gateways WHERE filename='stripe' LIMIT 1");

		foreach($query->result() as $row)
		{
			$configs = explode("\n", $row->configuration);
			$this->config = array();

			foreach($configs as $config)
			{
				if($config)
				{
					$line = explode("=", $config, 2);
					$this->config[$line[0]] = $line[1];
				}
			}
		}
	}

    public function process($order, $payment_vars, &$messages)
    {
    	require_once(APPLICATION_PATH . '/third_party/stripe-php/init.php');

    	$this->init();
    	\Stripe\Stripe::setApiKey($this->config["private_key"]);

    	$token = $payment_vars['stripeToken'];

    	try
    	{
  			$charge = \Stripe\Charge::create(array(
    			"amount" => $order->order_total * 100, // Amount in cents
    			"currency" => strtolower((class_exists("Shop") ? Shop::currency()->currency_code : "CAD")),
    			"source" => $token,
    			"description" => COMPANY_NAME . " Order #" . $order->order_id
    		));
    		$messages[] = "Transaction #: " . $charge->id;

    		$order->paid = 1;
    		$order->save();

    		return $charge->id;
		}
		catch(\Stripe\Error\Card $e)
		{
			// The card has been declined
			$messages[] = $e->getmessage();
			return false;
		}
    }

    public function qualifies($gateway_data)
    {
    	return true;
    }
}
