<?php

class Payment_PaypalController extends Core_Controller_Default
{

    public function checkrecurrencesAction() {

        $date = Zend_Date::now();
        $subscription = new Subscription_Model_Subscription_Application();
        $collection = $subscription->findAll(
            array(
                "not_null" => new Zend_Db_Expr("profile_id IS NOT NULL"),
                "expire_at <= ?" => $date->toString("yyyy-MM-dd HH:mm:ss")
            )
        );

        $paypal = new Payment_Model_Paypal();
        foreach($collection as $subscription) {

            $response = $paypal->request(
                Payment_Model_Paypal::GET_RECURRING_EXPRESS_CHECKOUT_DETAILS,
                array('PROFILEID' => $subscription->getProfileId()));

            $paypal_date = new Zend_Date($response['NEXTBILLINGDATE'],'yyyy-MM-dd"T"HH:mm:ss"Z"');

            // Payment OK
            if($response['FAILEDPAYMENTCOUNT'] == 0) {

                if($paypal_date->compare(new Zend_Date($subscription->getExpireAt()), Zend_Date::DATES) >= 0) {
                    $subscription->setIsActive(1)->update();
                }

            } else {
                // Payment error
                $subscription->setIsActive(0)
                    ->save()
                ;
            }
        }

        die;

    }


}
