<?php

/*
 +--------------------------------------------------------------------+
 | CiviCRM version 1.9                                                |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2007                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the Affero General Public License Version 1,    |
 | March 2002.                                                        |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the Affero General Public License for more details.            |
 |                                                                    |
 | You should have received a copy of the Affero General Public       |
 | License along with this program; if not, contact CiviCRM LLC       |
 | at info[AT]civicrm[DOT]org.  If you have questions about the       |
 | Affero General Public License or the licensing  of CiviCRM,        |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

/*
 * This file checks and updates the status of all membership records for a given domain using the calc_membership_status and 
 * update_contact_membership APIs.
 * It takes the first argument as the domain-id if specified, otherwise takes the domain-id as 1.
 *
 * IMPORTANT: You must set a valid FROM email address on line 63 before and then save the file as
 * UpdateMembershipRecord.php prior to running this script.
 */

require_once '../civicrm.config.php';
require_once 'CRM/Core/Config.php';

require_once 'api/crm.php';
require_once 'CRM/Member/BAO/Membership.php';
require_once 'CRM/Contact/DAO/Contact.php';
require_once "CRM/Core/BAO/MessageTemplates.php";
require_once "CRM/Member/BAO/MembershipType.php";
require_once 'CRM/Member/BAO/MembershipLog.php';
require_once "CRM/Utils/Date.php";

class CRM_UpdateMembershipRecord {
    
    function __construct() 
    {
        $config =& CRM_Core_Config::singleton();

        // this does not return on failure
        require_once 'CRM/Utils/System.php';
        CRM_Utils_System::authenticateScript( true );

        $config->userFramework          = 'Soap';
        $config->userFrameworkClass     = 'CRM_Utils_System_Soap';
        $config->userHookClass          = 'CRM_Utils_Hook_Soap';
    }
    
    public function updateMembershipStatus( $domainID )
    {
        $query = "
SELECT civicrm_membership.id                 as membership_id,
       civicrm_membership.is_override        as is_override,
       civicrm_membership.reminder_date      as reminder_date,
       civicrm_membership.membership_type_id as membership_type_id,
       civicrm_contact.id                    as contact_id
FROM   civicrm_membership, civicrm_contact
WHERE  civicrm_membership.contact_id = civicrm_contact.id
       AND civicrm_contact.domain_id = %1
";
        $params = array( 1 => array( $domainID, 'Integer' ) );
        $dao =& CRM_Core_DAO::executeQuery( $query, $params );

        $today = date( "Y-m-d" );
        $count = 0;
        while ( $dao->fetch( ) ) {
            echo ".";

            /**
            $count++;
            echo $dao->contact_id . ', '. CRM_Utils_System::memory( ) . "<p>\n";

            CRM_Core_Error::debug( 'fBegin', count( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] ) );
            if ( $count > 2 ) {
                foreach ( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] as $r ) {
                    CRM_Core_Error::debug( 'r', $r->query );
                }
                // CRM_Core_Error::debug( 'f', $GLOBALS['_DB_DATAOBJECT']['RESULTS'] );
                exit( );
            }
            **/

            $newStatus = crm_calc_membership_status( $dao->membership_id );
            if ( $newStatus && ! $dao->is_override ) {
                crm_update_contact_membership( array('id'        => $dao->membership_id,
                                                     'status_id' => $newStatus['id']) );
            }

            //send reminder for membership renewal
            if ( $dao->reminder_date &&
                 ( $dao->reminder_date <= $today ) ) {
                $memType =& new CRM_Member_BAO_MembershipType( );
                $memType->id = $dao->membership_type_id;
                if ( $memType->find( true ) &&
                     $memType->renewal_msg_id ) {
                    $toEmail  = CRM_Contact_BAO_Contact::getPrimaryEmail( $dao->contact_id );

                    if ( $toEmail ) {
                        // Set the FROM email address for reminder emails here.
                        // This must be a valid account for your SMTP service.
                        $from = "EMAIL@FIXME.ORG";
                        CRM_Core_BAO_MessageTemplates::sendReminder( $dao->contact_id,
                                                                       $toEmail,
                                                                       $domainID,
                                                                       $memType->renewal_msg_id,
                                                                       $from);

                        //Set membership reminder date to NULL since we've sent the reminder.
                        crm_update_contact_membership( array('id'             => $dao->membership_id,
                                                             'reminder_date'  => 'null' ) );

                                 
                        //insert the log record.
                        $memb = new CRM_Member_BAO_Membership( );
                        $memb->id = $membership->id;
                        if ( $memb->find( true ) ) {
                            //insert the log record.
                            $logParams = array( 
                                         'membership_id'         => $memb->id,
                                         'status_id'             => $memb->status_id,
                                         'start_date'            => ( CRM_Utils_Date::customFormat($memb->start_date,'%Y%m%d') ),
                                         'end_date'              => ( CRM_Utils_Date::customFormat($memb->end_date,'%Y%m%d') ),
                                         'modified_id'           => $dao->contact_id,
                                         'modified_date'         => date("Ymd"),
                                         'renewal_reminder_date' => date("Ymd") );
                            
                            $dontCare = null;
                            CRM_Member_BAO_MembershipLog::add( $logParams, $dontCare );
                        }
                        $memb->free( );
                    }
                }
                $memType->free( );
                
            }
            // CRM_Core_Error::debug( 'fEnd', count( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] ) );
        }
    }
}

$domainId = isset( $argv[1] ) ? $argv[1] : 1;
$obj =& new CRM_UpdateMembershipRecord( );
echo "\n Updating ";
$obj->updateMembershipStatus( $domainId );
echo "\n\n Membership records updated. (Done) \n";

?>
