<?php

require_once 'classes/user.php';

function plugin_expiringcc_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Expiring Credit Card Notifier',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, notify customers with expiring cards at the end of the month.  When run it will E-mail customers with a credit card expiring that month and generate a ticket for credit cards expired in the previous month.<br><b>NOTE:</b> This service is intended to run only once per month.',
            'value'         => '0',
        ),
        'Generate Ticket Upon Expiration' => array(
            'type'          => 'yesno',
            'description'   => 'Generates a ticket in the customers account when their credit card expires.  Useful for allowing administrators to follow up on the expired credit card.',
            'value'         => '1',
        ),
        'E-mail Subject'     => array(
            'type'          => 'text',
            'description'   => 'Subject to be displayed on E-mail notifications.',
            'value'         => 'Billing Department - Expiring Credit Card Notice',
        ),
        'Run schedule - Minute'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '0',
            'helpid'        => '8',
        ),
        'Run schedule - Hour'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '0',
        ),
        'Run schedule - Day'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '1',
        ),
        'Run schedule - Month'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Day of the week'  => array(
            'type'          => 'text',
            'description'   => 'Enter number in range 0-7 (0 is Sunday) or a 3 letter shortcut (e.g. sun)',
            'value'         => '*',
        ),
    );

    return $variables;
}

function plugin_expiringcc_execute()
{
    global $gSettingsArray;

    require_once 'classes/troubletickets.php';
    require_once 'classes/troubleticket.php';
    require_once 'modules/support/fncSupportFunctions.php';

    $messages = array();
    $arrExpiredCC = _getExpiringCCUsers(true);
    $arrExpiringCC = _getExpiringCCUsers(false);

    /* Handle notifying customers whose credit cards will soon be expiring */
    foreach ($arrExpiringCC as $userid) {
        $objUser =& new User($userid);
        $objUser->populateCustomFields();
        $strMessage = $gSettingsArray['Expiring CC Template'];
        $strMessage = str_replace("[BILLINGEMAIL]", $gSettingsArray["Billing E-mail"], $strMessage);
        $strMessage = str_replace("[CLIENTAPPLICATIONURL]", $gSettingsArray["ClientExec URL"], $strMessage);
        $strMessage = str_replace("[COMPANYNAME]", $gSettingsArray["Company Name"], $strMessage);
        $strMessage = str_replace("[CLIENTNAME]", $objUser->getFullName(), $strMessage);
        $strMessage = str_replace("[CLIENTEMAIL]", $objUser->getEmail(), $strMessage);
        $strMessage = str_replace("[FORGOTPASSWORDURL]", $gSettingsArray["ClientExec URL"]."/index.php?fuse=".cLOGOFF."&action=".cGENERAL_SHOWFORGOTPASSWORDWINDOW, $strMessage);
        $strMessage = str_replace("[CCLASTFOUR]", $objUser->getCCLastFour(), $strMessage);
        $strMessage = str_replace("[CCEXPDATE]", $objUser->getCCMonth()."/".$objUser->getCCYear(), $strMessage);
        $strMessage = ReplaceCustomFields($strMessage,$userid);
        MailMessage($strMessage,$gSettingsArray["Billing E-mail"],$gSettingsArray["Billing Name"],$objUser->getId(),$bcc,$gSettingsArray['plugin_expiringcc_E-mail Subject'],3,0);
    }
    $messages[] = count($arrExpiringCC)." ".lang("customers notified of expiring credit cards");

    if ($gSettingsArray['plugin_expiringcc_Generate Ticket Upon Expiration']) {
        /* Handle generating tickets for expired credit cards */
        $cTickets = new TroubleTickets();
        if ($cTickets->GetTicketCount() == 0) {
            $ticketId = $GLOBALS['gSettingsArray']['Trouble Ticket Start Number'];
        } else {
            $ticketId = '';
        }
        $tTimeStamp = date('Y-m-d H-i-s');
        foreach ($arrExpiredCC as $userid) {
            $objUser =& new User($userid);
            $objUser->populateCustomFields();
            $subject = lang("Credit Card Expired")." - ".$objUser->getFullName();
            $message = lang("** This ticket has been generated automatically **\n\n%s's credit card on file ending with %s has expired on %s.", $objUser->getFullName(), $objUser->getCCLastFour(), $objUser->getCCMonth()."/".$objUser->getCCYear());

            $query = "INSERT INTO troubleticket (id, userid, subject, priority, datesubmitted, status, messagetype, assignedtoid) VALUES "
                        ."(?, ?, ?, '1', ?, '0', 'Billing Issues', '0')";
            $dataInsert = $GLOBALS['db']->query($query, $ticketId, $userid, $subject, $tTimeStamp);
            $newticket = $dataInsert->getInsertId();
            AddInitialLogForTicketID($newticket, $message, $tTimeStamp, $userid);
            $cTicket = new TroubleTicket($newticket);
            $cTicket->Populate();
            $cTicket->SetDateSubmitted($tTimeStamp);
            $cTicket->SetLastLogDateTime($tTimeStamp);
            $cTicket->Update();
            $cTicket->sendNotifications($objUser, 1, $subject, $message, $newticket);
        }
        $messages[] = count($arrExpiredCC)." ".lang("expired credit card ticket(s) generated");
    }

    return $messages;
}

function plugin_expiringcc_output()
{
    global $tpl;
    global $gSettingsArray;

    $tpl->define(array('expiringcc_table' => 'views/admin/expiringcc_table.tpl'));
    $tpl->define_dynamic('expiringcc', 'expiringcc_table');
    $rowclass="odd";

    $arrExpiring = _getExpiringCCUsers(false);
    $arrExpired = _getExpiringCCUsers(true);

    foreach ($arrExpiring as $userid) {
        $user =& new User($userid);
        $user->populateCustomFields();

        $tpl->setkey(array(
            'trClass'                 => $rowclass,
            'expiringcc_customer'     => $user->getFullName(),
            'expiringcc_customerid'   => $user->getId(),
            'expiringcc_last4'        => $user->getCCLastFour(),
        ));

        //alternate row color
        if ($rowclass=="odd") $rowclass="even";
        else $rowclass="odd";

        $tpl->subst('trash', '.expiringcc');
    }

    if (count($arrExpiring) == 0) {
        $tpl->setkey('NOEXPIRING', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".lang('There are no expiring credit cards this month')."</td></tr>");
    } else {
        $tpl->setkey('NOEXPIRING', '');
    }

    foreach ($arrExpired as $userid) {
        $user =& new User($userid);
        $user->populateCustomFields();

        $tpl->setkey(array(
            'trClass'                => $rowclass,
            'expiredcc_customer'     => $user->getFullName(),
            'expiredcc_customerid'   => $user->getId(),
            'expiredcc_last4'        => $user->getCCLastFour(),
        ));

        //alternate row color
        if ($rowclass=="odd") $rowclass="even";
        else $rowclass="odd";

        $tpl->subst('trash', '.expiredcc');
    }

    if (count($arrExpired) == 0) {
        $tpl->setkey('NOEXPIRED', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".lang('There are no credit cards that expired last month.')."</td></tr>");
    } else {
        $tpl->setkey('NOEXPIRED', '');
    }

    $tpl->parse('output', 'expiringcc_table');

    return $tpl->fetch('output');
}

function plugin_expiringcc_dashboard()
{
    return lang("Number of credit cards expiring this month: %d<br>Number of credit cards expired last month: %d", _getExpiringCCUsers(false), _getExpiringCCUsers(true));
}

/**
 * Gets users with credit cards that are expiring this month or last month.
 * @param boolean $expired If true get users that expired last month, otherwise get expiring this month
 * @return array an array of user ids
 */
function _getExpiringCCUsers($expired = false) {

    if ($expired) {
        // Get the month and year for last month
        if (date("n") == 1) {
            $month = 12;
            $year = date("Y") - 1;
        } else {
            $month = date("n") - 1;
            $year = date("Y");
        }
    } else {
        $month = date("n");
        $year = date("Y");
    }

    $arrIds = array();

    $query = "SELECT `id` FROM `users` "
            ."WHERE `ccmonth`=? "
            ."AND `ccyear`=? "
            ."AND `status`='1' "
            ."AND `passphrased`='1' "
            ."AND (`data1` != '' OR `data3` != '') "
            ."AND `data2` != '' "
            ."AND `groupid`='1'";
    $result = $GLOBALS['db']->query($query, $month, $year);
    while ($row = $result->fetch()) {
        $arrIds[] = $row['id'];
    }
    return $arrIds;
}
?>
