+
+ // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
+ // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
+ // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
+ // value via UNION operation
+ if (strpos($selectColumns, 'reference_date') !== FALSE) {
+ $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
+ $referenceQuery = "
+INSERT INTO civicrm_action_log ({$selectColumns})
+{$selectClause}
+{$fromClause}
+{$joinClause}
+ LEFT JOIN {$reminderJoinClause}
+{$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
+ reminder.action_date_time IS NOT NULL AND
+ (reminder.reference_date IS NOT NULL AND reminder.reference_date != {$dateField})
+LIMIT 0,1
+";
+
+ // As per the usage of UNION clause above we always INSERT a new reminder if reference_date (RD)
+ // got outdated or mismatches to start_action_date criteria so we need to update RD with actual
+ // start_action_date of already sent reminder, so to prevent redeundancy in sending new reminder
+ // due to above INSERT-UNION query
+ $updateQuery = "UPDATE civicrm_action_log reminder
+ INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id AND
+ reminder.reference_date IS NOT NULL AND reminder.action_date_time IS NOT NULL
+ INNER JOIN civicrm_action_log new_reminder ON
+ new_reminder.action_schedule_id = reminder.action_schedule_id AND
+ new_reminder.reference_date = {$dateField} AND
+ new_reminder.action_date_time IS NULL
+ SET reminder.reference_date = {$dateField}
+ WHERE reminder.action_schedule_id = %1 AND reminder.reference_date IS NOT NULL AND reminder.reference_date != {$dateField}
+";
+ }
+