<?php

/**
 * Subscription actions.
 *
 * @package www.katao.fr
 * @subpackage Subscription
 * @author Your name here
 * @version SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class SubscriptionActions extends sfActions {
    public function executeSubscribe($request)
    {
        $this->initializeCatalyzVariables();
        $this->form = new AdherentSubscriptionForm();

        if ($request->isMethod('post')) {
            $this->form->bind($request->getParameter('form_subscription'));
/*
            if ($this->form->isValid()) {
                $this->forward('Subscription', 'thank');
            }*/
        	$values = $this->form->getValues();
        	$mode  = $values['user_payment_mode'];

        	// Montant
        	$amount = $values['user_payment_amount'];
        	$hash = array('0' => 50,
        	'1' => 25,
        	'2' => 100);

        	$amount = $hash[$amount];

        	$this->getUser()->setAttribute('amount', $amount);

        	if($mode == KataoMemberDeposit::PAYMENT_MODE_OTHER){  // Si carte bleue choisie
        		$this->forward('Subscription', 'paypalSubscribeStep1');
        	} else {
        		$this->forward('Subscription', 'thank');
        	}
        }
    }

    public function executeRenew($request)
    {
        $this->initializeCatalyzVariables();

        $this->form = new RenewForm();

        if ($request->isMethod('post')) {
            $this->form->bind($request->getParameter('form_renew'));

            if ($this->form->isValid()) {
            	$values = $this->form->getValues();
            	$mode  = $values['user_payment_mode'];

            	// Montant
            	$amount = $values['user_payment_amount'];
            	$hash = array('0' => 50,
            					'1' => 25,
            					'2' => 100);

            	$amount = $hash[$amount];

            	$this->getUser()->setAttribute('amount', $amount);

            	if($mode == KataoMemberDeposit::PAYMENT_MODE_OTHER){  // Si carte bleue choisie
            		$this->forward('Subscription', 'paypalSubscribeStep1');
            	} else {
            		$this->forward('Subscription', 'thank');
            	}
            }
        }
    }

    public function executeChoice($request)
    {
        $this->initializeCatalyzVariables();
        $this->form = new choiceSubscriptionForm;

        if ($request->isMethod('post')) {
            $this->form->bind($request->getParameter('form_choice_subscription'));

            if ($this->form->isValid()) {
                $value = $request->getParameter('subscribe');

                switch ($value) {
                    case '0':$this->forward('Subscription', 'subscribe');
                        break;
                    case '1':$this->forward('Subscription', 'renew');
                        break;
                    case null: wpFlashMessages::addError('Veuillez choisir une action avant de continuer');
                        $this->redirect('@sol_violette_suscribe_choice');
                        break;
                    default : $this->redirect('@sol_violette_suscribe_choice');
                }
            }
        }
    }

    public function executeThank($request)
    {
        $this->initializeCatalyzVariables();

        $requested_form = $request->getParameter('form_subscription');
        (!empty($requested_form)) ? $this->form = new AdherentSubscriptionForm() : $this->form = new RenewForm();

        if ($request->isMethod('post')) {
            (!empty($requested_form)) ? $this->form->bind($request->getParameter('form_subscription')) : $this->form->bind($request->getParameter('form_renew'));
            // Téléchargement du fichier
            $filename = 'recapitulatif_adhesion_' . md5(uniqid(rand(), true)) . '.pdf';

            (!empty($requested_form)) ? $title = 'Adhésion à Sol Violette' : $title = 'Ré-adhésion à Sol Violette';

            $pdf = new ScanReportPdf($title);
            $pdf->setAdherentSubscriptionDatas($this->form->getValues());

            $doc = $pdf->execute($filename);

            unlink(sfConfig::get('sf_upload_dir') . '/pdf/' . $filename);

            $this->filename = $filename;
        }
    }

	public function executePaypalSubscribeStep1($request){
		$this->initializeCatalyzVariables();

		$this->amount = $this->getUser()->getAttribute('amount');
		$this->label = utf8_decode("Adhesion Sol Violette");
	}

	public function executePaypalThank($request){
		$this->initializeCatalyzVariables();
	}

	public function executePaypalCancel($request){
		$this->initializeCatalyzVariables();
	}

	public function executePaypalConfirm($request){
		$this->initializeCatalyzVariables();

		//permet de traiter le retour ipn de paypal
/*		$email_account = "cbarra_1354609815_biz@waterproof.fr";
		$req = 'cmd=_notify-validate';

		foreach ($_REQUEST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}

		$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
		$item_name = $_REQUEST['item_name'];
		$item_number = $_REQUEST['item_number'];
		$payment_status = $_REQUEST['payment_status'];
		$payment_amount = $_REQUEST['mc_gross'];
		$payment_currency = $_REQUEST['mc_currency'];
		$txn_id = $_POST['txn_id'];
		$receiver_email = $_REQUEST['receiver_email'];
		$payer_email = $_REQUEST['payer_email'];
		parse_str($_REQUEST['custom'],$custom);

		if (!$fp) {

		} else {
			fputs ($fp, $header . $req);
		while (!feof($fp)) {
			$res = fgets ($fp, 1024);
			if (strcmp ($res, "VERIFIED") == 0) {
				// vérifier que payment_status a la valeur Completed
				if ( $payment_status == "Completed") {
					if ( $email_account == $receiver_email) {
						/**
						 * C'EST LA QUE TOUT SE PASSE
						 * PS : tjrs penser à vérifier la somme !!
						 * /
		                file_put_contents(sfConfig::get('sf_web_dir') . '/uploads/paypal_' . time() . '.log', print_r($_REQUEST, true)); // Fichier log transaction

						/**
						 * FIN CODE
						 * /
					}
				}
				else {
					// Statut de paiement: Echec
				}
				exit();
			}
			else if (strcmp ($res, "INVALID") == 0) {
				// Transaction invalide
			}
		}
			fclose ($fp);
		}*/

		return sfView::NONE;
		//session_id($_REQUEST['custom']);  // Récupérer les identifiants
	}

    protected function initializeCatalyzVariables()
    {
        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTreeNode = $this->ContentTree->getRoot();
        $this->node = $this->ContentTreeNode->getNode();
        $this->page = $this->ContentTreeNode->getPage();
    }
}