<?php

/*
 * 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/Member/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() 
    {
        _crm_initialize();

        $config =& CRM_Core_Config::singleton();
        $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_Member_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.
                            $membershipLog =& new CRM_Member_BAO_MembershipLog( );
                            $membershipLog->membership_id = $memb->id;
                            $membershipLog->status_id   = $memb->status_id;
                            $membershipLog->start_date  = CRM_Utils_Date::customFormat($memb->start_date,'%Y%m%d');
                            $membershipLog->end_date    = CRM_Utils_Date::customFormat($memb->end_date,'%Y%m%d');
                            $membershipLog->modified_id = $dao->contact_id;
                            $membershipLog->modified_date = date("Ymd");
                            $membershipLog->renewal_reminder_date = date("Ymd");
                            $membershipLog->save( );
                            $membershipLog->free( );
                        }
                        $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";

?>
