<?php

class Subscription_ApplicationController extends Application_Controller_Default
{

    public function createAction() {

        if($errors = $this->getApplication()->isAvailableForPublishing()) {
            $message = $this->_('In order to publish your application, we need:<br />- ');
            $message .= join('<br />- ', $errors);
            $this->getSession()->addError($message);
            $this->redirect("application/customization_publication_infos");
            return $this;
        } else if($this->getApplication()->getSubscription()->isActive()) {
            $this->getSession()->addWarning($this->_("You already have a subscription for this application"));
            $this->redirect("application/customization_publication_infos");
            return $this;
        }

        $this->loadPartials();

    }

    public function saveaddressAction() {

        $html = array();

        if($data = $this->getRequest()->getPost()) {

            try {

                $admin = $this->getSession()->getAdmin();

                if(empty($data["company"])) {
                    throw new Exception($this->_("Please, enter a company"));
                }
                if(empty($data["address"])) {
                    throw new Exception($this->_("Please, enter an address"));
                }
                if(empty($data["country_code"])) {
                    throw new Exception($this->_("Please, enter a country"));
                }
                if(!empty($data["vat_number"])) {

                    if(!$this->__checkVatNumber($data["vat_number"], $data["country_code"])) {
                        throw new Exception($this->_("Your VAT Number is not valid"));
                    }
                }

                $admin->setCompany($data["company"])
                    ->setFirstname($data["firstname"])
                    ->setLastname($data["lastname"])
                    ->setAddress($data["address"])
                    ->setCountryCode($data["country_code"])
                    ->setVatNumber($data["vat_number"])
                    ->setPhone($data["phone"])
                    ->save()
                ;

                $html = array("success" => 1);

                if($this->getSession()->subscription_id) {
                    $subscription = new Subscription_Model_Subscription();
                    $subscription->find($this->getSession()->subscription_id);

                    $order_details = $this->_getOrderDetailsHtml($subscription);

                    $html["order_details_html"] = $order_details;

                }

            } catch (Exception $e) {
                $html = array(
                    'error' => 1,
                    'message' => $e->getMessage()
                );
            }

            $this->_sendHtml($html);
        }
    }

    public function setAction() {

        if($data = $this->getRequest()->getPost()) {

            try {

                if(empty($data["subscription_id"])) {
                    throw new Exception($this->_("An error occurred while saving. Please try again later."));
                }

                $subscription = new Subscription_Model_Subscription();
                $subscription->find($data["subscription_id"]);

                if(!$subscription->getId()) {
                    throw new Exception($this->_("An error occurred while saving. Please try again later."));
                }

                $order_details = $this->_getOrderDetailsHtml($subscription);

                $this->getSession()->subscription_id = $subscription->getId();

                $html = array(
                    "success" => 1,
                    "order_details_html" => $order_details
                );


            } catch(Exception $e) {
                $html = array(
                    "error" => 1,
                    "message" => $e->getMessage()
                );
            }

            $this->_sendHtml($html);

        }

    }

    public function processAction() {

        if($subscription_id = $this->getSession()->subscription_id) {

            try {

                $subscription = new Subscription_Model_Subscription();
                $subscription->find($subscription_id);

                if (!$subscription->getId()) {
                    throw new Exception($this->_("An error occurred while saving. The selected subscription is not valid."));
                }

                $admin = $this->getAdmin();
                $subscription->setCurrentApplication($this->getApplication())
                    ->setAdmin($admin)
                ;
                $order = $subscription->toOrder();
                $order->setStatus(Sales_Model_Order::DEFAULT_STATUS)
                    ->setAppId($this->getApplication()->getId())
                    ->setAppName($this->getApplication()->getName())
                    ->setSubscriptionId($subscription->getId())
                    ->setAdminId($admin->getId())
                    ->setAdminCompany($admin->getCompany())
                    ->setAdminName($admin->getFirstname() . " " . $admin->getLastname())
                    ->setAdminEmail($admin->getEmail())
                    ->setAdminAddress($admin->getAddress())
                    ->setAdminCountry($admin->getCountry())
                    ->setAdminPhone($admin->getPhone())
                    ->save()
                ;

                $this->getSession()->order_id = $order->getId();

                $paypal = new Payment_Model_Paypal();

                $return_url = parent::getUrl('subscription/application/success', array('order_id' => $order->getId()));
                $cancel_url = parent::getUrl('subscription/application/cancel');

                $paypal->setOrder($order)
                    ->setReturnUrl($return_url)
                    ->setCancelUrl($cancel_url);

                //  redirect to Paypal here
                if(!$paypal_url = $paypal->getUrl()){
                    Zend_Registry::get("logger")->sendException("Error when retrieving the Paypal URL:\n".print_r($paypal->getErrors(), true)."\nAnd params:\n".print_r($paypal->getParams(), true), "paypal_error_", false);
                    throw new Exception($this->_("An error occurred while saving. Please try again later"));
                }
                $this->redirect($paypal_url);

            } catch(Exception $e) {
                $this->getSession()->addError($e->getMessage());
                $this->redirect("subscription/application/create");
            }

        }

    }

    // Success action for Paypal
    public function successAction() {

        if($order_id = $this->getSession()->order_id) {

            try {
                if($token = $this->getRequest()->getParam('token')) {

                    $order = new Sales_Model_Order();
                    $order->find($order_id);

                    if(!$order->getId()) {
                        throw new Exception($this->_("An error occurred while processing your order. Please, try again later."));
                    }

                    $return_url = parent::getUrl('subscription/application/success', array('order_id' => $order->getId()));
                    $cancel_url = parent::getUrl('subscription/application/cancel');

                    $paypal = new Payment_Model_Paypal();

                    $payment_is_ok = $paypal->setToken($token)
                        ->setOrder($order)
                        ->setReturnUrl($return_url)
                        ->setCancelUrl($cancel_url)
                        ->pay();

                    if($payment_is_ok) {

                        $response = $paypal->getResponse();

                        $order->pay();

                        $subscription = new Subscription_Model_Subscription_Application();
                        $subscription->create($order->getAppId(), $order->getSubscriptionId());

                        $subscription->setProfileId(!empty($response['PROFILEID']) ? $response['PROFILEID'] : null)
                            ->setCorrelationId(!empty($response['CORRELATIONID']) ? $response['CORRELATIONID'] : null)
                            ->save()
                        ;

                    }
                    else{
                        throw new Exception($this->_('An error occurred while processing the payment. For more information, please feel free to contact us.'));
                    }

                    $this->getSession()->order_id = null;
                    $this->getSession()->subscription_id = null;

                    $this->loadPartials();
                }
                else{
                    throw new Exception($this->_("An error occurred while processing your order. Please, try again later."));
                }

            } catch(Exception $e) {
                $this->getSession()->addError($e->getMessage());
                $this->redirect("subscription/application/create");
            }

        }

    }

    // Cancel action for Paypal
    public function cancelAction() {

        if($order_id = $this->getSession()->order_id) {

            try {
                $order = new Sales_Model_Order();
                $order->find($order_id);

                if (!$order->getId()) {
                    throw new Exception($this->_("An error occurred while processing your order. Please, try again later."));
                }

                $order->cancel();

                $this->getSession()->addWarning($this->_("Your order has been canceled. If you need any help to place your order, please feel free to contact us."));

                $this->getSession()->order_id = null;
                $this->getSession()->subscription_id = null;

            }
            catch(Exception $e) {
                $this->getSession()->addError($e->getMessage());
            }

            $this->redirect("subscription/application/create");

        }

    }

    protected function _getOrderDetailsHtml($subscription) {

        $subscription->setCurrentApplication($this->getApplication())
            ->setAdmin($this->getSession()->getAdmin())
        ;

        return $this->getLayout()->addPartial("order_details", "admin_view_default", "subscription/application/create/order_details.phtml")
            ->setTmpOrder($subscription->toOrder())
            ->toHtml()
        ;

    }

    private function __checkVatNumber($vatNumber, $countryCode) {

        // Serialize the VAT Number
        $vatNumber = str_replace(array(' ', '.', '-', ',', ', '), '', $vatNumber);
        // Retrieve the country code
        $countryCodeInVat = substr($vatNumber, 0, 2);
        // Retrieve the VAT Number
        $vatNumber = substr($vatNumber, 2);

        // Check the VAT Number syntax
        if (strlen($countryCode) != 2 || is_numeric(substr($countryCode, 0, 1)) || is_numeric(substr($countryCode, 1, 2))) {
            return false;
        }

        // Check if the country code in the VAT Number is the same than the parameter
        if ($countryCodeInVat != $countryCode) {
            return false;
        }

        // Call the webservice
        $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
        $params = array('countryCode' => $countryCode, 'vatNumber' => $vatNumber);
        $result = $client->checkVat($params);

        // Return the result
        return $result->valid;
    }

}
