// it's useful to disbale that during testing.  0=allow update, 1= no update
define('ALERT_DEBUG_LASTSENT_NO_UPDATE', 0);
// Set this to an email address if you want to redirect alerts to an address for debugging
define('ALERT_DEBUG_RECIPIENT', '');
require_once dirname(__FILE__) . "/include_path.php";
require_once dirname(__FILE__) . "/../includes/init.php";
$email_alert = factory::create('email_alert');
$sql = "SELECT * FROM email_alert \n        WHERE HOUR(TIMEDIFF(NOW(), last_sent)) >= frequency_hours AND activated = 1 ";
$email_alerts = $email_alert->execute($sql);
if (ALERT_DEBUG > 0) {
    print "{$sql} \n";
    print count($email_alerts) . " alerts to process\n";
}
foreach ($email_alerts as $email_alert) {
    //send email
    $leaflets = get_leaflets($email_alert);
    if (ALERT_DEBUG > 0) {
        print count($leaflets) . " leaflets\n";
    }
    if (count($leaflets) > 0) {
        send_alert($email_alert, $leaflets);
    }
    //update last_sent
    $email_alert->last_sent = mysql_date(time());
    if (!ALERT_DEBUG_LASTSENT_NO_UPDATE) {
        $email_alert->update();
    }
}
// retrieve array of leaflets which match the alert type and time period
function get_leaflets($email_alert)
{
<?php

/*
    Map leaflets to UK parliamentry constituencies
*/
require_once dirname(__FILE__) . "/include_path.php";
require_once dirname(__FILE__) . "/../includes/init.php";
//get all constituencies
$constituencies = get_constituencies();
//get the constituency type for UK Parliament
$leaflets = get_leaflets();
//for each leaflet, try to map it to a consituency
foreach ($leaflets as $leaflet) {
    try {
        $twfy_constituency = lookup_constituency($leaflet->postcode);
        $constituency = match_constituency($twfy_constituency['name'], $constituencies);
        if ($constituency != false) {
            $leaflet_constituency = factory::create('leaflet_constituency');
            $leaflet_constituency->leaflet_id = $leaflet->leaflet_id;
            $leaflet_constituency->constituency_id = $constituency->constituency_id;
            $leaflet_constituency->insert();
            print_message($twfy_constituency['name'] . ' - ' . $leaflet->title);
        } else {
            print_message("skipped " . $leaflet->postcode);
        }
    } catch (Exception $e) {
        print_message("skipped " . $leaflet->postcode);
    }
    //sleep
    sleep(1);
}