#!/usr/bin/php
<?php

$CAMPSITE_DIR = dirname(dirname(__FILE__));
$GLOBALS['g_campsiteDir'] = $CAMPSITE_DIR;
$ETC_DIR = $CAMPSITE_DIR . '/conf';

require_once("cli_script_lib.php");

if (!camp_is_readable("$ETC_DIR/install_conf.php")) {
	exit(1);
}

if (!is_file("$ETC_DIR/database_conf.php")) {
	echo "\n";
	echo "Database configuration file is missed!\n";
	echo "\n";
	exit(1);
}

// includes newscoop initialisation
require_once("$CAMPSITE_DIR/include/campsite_init.php");

// defines the notifier template file name
define('NOTIFIER_TEMPLATE', '_subscription_notifier.tpl');

// connects to database server
if (db_server_connect() == false) {
    msg_error('Connecting to DB server');
    exit;
}

// sets the array which holds message data
$message = array();

// reads reply address
$message['reply'] = get_reply_address();

// sets the notifications counter
$notified_index = 0;

// reads ending subscriptions
$sql_query = "SELECT p.Name AS PubName, p.IdDefaultLanguage AS PubDefLang, "
. "u.Title AS UserTitle, u.Name AS UserName, u.EMail AS UserEMail, "
. "s.Id AS SubsId, s.Type AS SubsType, p.Id AS PubId, a.Name AS AliasName "
. "FROM Subscriptions AS s, Publications AS p, "
. "Aliases AS a, liveuser_users AS u "
. "WHERE u.Id = s.IdUser AND p.Id = s.IdPublication AND s.Active = 'Y' "
. "AND p.IdDefaultAlias = a.Id AND s.ToPay = \"0.00\"";
if (!$result = mysql_query($sql_query)) {
    msg_error('Reading ending subscriptions');
    exit;
}

// inits smarty template system
$tpl = init_smarty();

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $sql_query = "SELECT MAX(Number) AS MaxNumber "
        . " FROM Issues WHERE IdPublication = " . $row['PubId']
        . " AND IdLanguage = " . $row['PubDefLang'] . " AND Published = 'Y'";
    if (!$isn_result = mysql_query($sql_query)) {
        continue;
    }

    if (mysql_num_rows($isn_result) <= 0) {
        continue;
    }

    $isn_row = mysql_fetch_array($isn_result, MYSQL_ASSOC);
    mysql_free_result($isn_result);

    $sql_query = "SELECT COUNT(*) AS NumberOfSections "
        . "FROM Sections "
        . "WHERE IdPublication = " . $row['PubId']
        . " AND NrIssue = " . $isn_row['MaxNumber']
        . " AND IdLanguage = " . $row['PubDefLang'];
    $psc_result = mysql_query($sql_query);
    $psc_row = mysql_fetch_array($psc_result, MYSQL_ASSOC);
    $pub_sections = $psc_row['NumberOfSections'];
    mysql_free_result($psc_result);

    $sql_query = "SELECT StartDate, DATE_FORMAT(StartDate, '%M %D, %Y'), "
        . "PaidDays, TO_DAYS(StartDate), TO_DAYS(now()), "
        . "DATE_FORMAT(ADDDATE(StartDate, INTERVAL PaidDays DAY), '%M %D, %Y') "
        . "FROM SubsSections "
        . "WHERE IdSubscription = " . $row['SubsId'] . " and NoticeSent = 'N' "
        . "GROUP BY StartDate, PaidDays";
    $dts_result = mysql_query($sql_query);
    $dts_num_rows = mysql_num_rows($dts_result);
    if ($dts_num_rows <= 0) {
        continue;
    }

    $text = '';
    $notify = false;
    $subs_sections = 0;
    $counter = 0;
    $sections = '';
    while($sec_row = mysql_fetch_row($dts_result)) {
        $sd = $sec_row[0];
        $sdf = $sec_row[1];
        $paid_days = $sec_row[2];
        $sd_days = $sec_row[3];
        $now_days = $sec_row[4];
        $edf = $sec_row[5];
        if ($now_days > ($paid_days + $sd_days)) {
            continue;
        }
        $remained_days = $paid_days + $sd_days - $now_days;
        if ($remained_days > 14 || $remained_days <= 0) {
            continue;
        }
        $notify = true;
        if ($dts_num_rows == 1) {
            $sql_query = "SELECT count(*) FROM SubsSections "
                . "WHERE IdSubscription = " . $row['SubsId']
                . " AND NoticeSent = 'N' AND StartDate = '" . $sd
                . "' AND PaidDays = " . $paid_days;
            $sec_nr_result = mysql_query($sql_query);
            $sec_nr_row = mysql_fetch_row($sec_nr_result);
            $subs_sections = $sec_nr_row[0];
            mysql_free_result($sec_nr_result);
        }

        if ($counter == 0) {
            $subs_type = ($row['SubsType'] == 'P') ? 'paid' : 'trial';
            $tpl->assign('user_title', $row['UserTitle']);
            $tpl->assign('user_name', $row['UserName']);
            $tpl->assign('subs_type', $subs_type);
            $tpl->assign('subs_date', $sdf);
            $tpl->assign('publication_name', $row['PubName']);
        }

        if ($subs_sections == $pub_sections && $dts_num_rows == 1) {
            $tpl->assign('subs_expire', 1);
            $tpl->assign('subs_expire_date', $edf);
            $tpl->assign('subs_remained_days', $remained_days);
        } else {
            $sql_query = "SELECT s.Name, s.Number "
                . "FROM Sections AS s, SubsSections AS u "
                . "WHERE u.IdSubscription = " . $row['SubsId']
                . " AND u.NoticeSent = 'N'"
                . " AND u.StartDate = '" . $sd . "'"
                . " AND u.PaidDays = " . $paid_days
                . " AND s.IdPublication = " . $row['PubId']
                . " AND s.NrIssue = " . $isn_row['MaxNumber']
                . " AND s.IdLanguage = " . $row['PubDefLang']
                . " AND s.Number = u.SectionNumber";
            $res_date_sec = mysql_query($sql_query);
            if ($counter == 0) {
                $tpl->assign('subs_expire_plan', 1);
            }

            $expire_plan = '\t- ';
            $is_first = true;
            while ($row_date_sec = mysql_fetch_row($res_date_sec)) {
                if (!$is_first) {
                    $expire_plan .= ', ';
                } else {
                    $is_first = false;
                }
                if (strlen($sections)) {
                    $sections .= ' OR ';
                }
                $expire_plan .= '"' . $row_date_sec[0] . '"';
                $sections .= 'SectionNumber = ' . $row_date_sec[1];
            }

            $tpl->assign('expire_plan', $expire_plan);
            mysql_free_result($res_date_sec);

            $tpl->assign('subs_expire_date', $edf);
            $tpl->assign('subs_remained_days', $remained_days);
            $tpl->assign('subs_start_date', $sdf);

            $counter++;
        }
    }

    $tpl->assign('site', $row['AliasName']);
    if (!$notify) {
        continue;
    }

    $message['recipients'] = array($row['UserEMail']);
    $message['text'] = $tpl->fetch(NOTIFIER_TEMPLATE);
    $message['subject'] = 'Subscription to ' . $row['PubName'];

    if (send_email($message) == false) {
        continue;
    }

    $sql_query = "UPDATE SubsSections "
        . "SET NoticeSent = 'Y' "
        . "WHERE IdSubscription = " . $row['SubsId'];
    if (strlen($sections)) {
        $sql_query .= " AND " . $sections;
    }
    mysql_query($sql_query);
    $notified_index++;
}

if ($notified_index > 0) {
    print($notified_index . " user(s) notified\n");
}


/**
 * Reads reply address
 *
 * @return string
 */
function get_reply_address()
{
    $sql_query = "SELECT EMail FROM liveuser_users WHERE UName = 'admin'";
    if (!$result = mysql_query($sql_query)) {
        msg_error('Getting reply address');
        exit;
    }

    if (mysql_num_rows($result) <= 0) {
        msg_error('There is no reply address');
        exit;
    }

    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    mysql_free_result($result);

    return $row['EMail'];
} // fn get_reply_address


/**
 * @return boolean
 *      true on success, false on failure
 */
function send_email($p_message)
{
    if (!is_array($p_message) || empty($p_message)) {
        return false;
    }

    $to = implode(', ', $p_message['recipients']);
    $subject = $p_message['subject'];
    $message = $p_message['text'];
    $headers = "From: ".$p_message['reply']."\n" .
        'X-Mailer: PHP/' . phpversion() . "\n" .
        "MIME-Version: 1.0\n" .
        "Content-Type: text/plain; charset=utf-8\n" .
        "Content-Transfer-Encoding: 8bit\n\n";

    // sends the email message
    return mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers);
} // fn send_email


/**
 * @return object $tpl
 *      Smarty object
 */
function init_smarty()
{
    global $CAMPSITE_DIR;

    // includes smarty main class
    require_once("$CAMPSITE_DIR/include/smarty/Smarty.class.php");

    // instantiates smarty template system
    $tpl = new Smarty();

    // inits smarty configuration settings
    $tpl->left_delimiter = '{{';
    $tpl->right_delimiter = '}}';
    $tpl->force_compile = true;
    $tpl->config_dir = $CAMPSITE_DIR.'/include/smarty/configs';
    $tpl->template_dir = $CAMPSITE_DIR.'/templates/system_templates';
    $tpl->compile_dir = $CAMPSITE_DIR.'/templates_cache';

    return $tpl;
} // fn init_smarty


/**
 * @return boolean
 */
function db_server_connect()
{
    global $Campsite;

    $db_host = $Campsite['DATABASE_SERVER_ADDRESS']
        .':'.$Campsite['DATABASE_SERVER_PORT'];
    $db_user = $Campsite['DATABASE_USER'];
    $db_pass = $Campsite['DATABASE_PASSWORD'];
    $db_name = $Campsite['DATABASE_NAME'];
    $link = mysql_connect($db_host, $db_user, $db_pass);
    if (!$link) {
        return false;
    }

    mysql_select_db($db_name, $link);
    return mysql_query("SET NAMES 'utf8'");
} // fn db_server_connect


/**
 * @param string $p_msg
 */
function msg_error($p_msg)
{
    print('ERROR: ' . $p_msg);
} // fn msg_error

?>
