<?php
if (!class_exists('crm_users')) require_once("common_cadline_libraries/crm_users.class.php");

$code       = trim($_GET['code']);
$topicId    = 54;
$nManagerID = 36;

$query = "SELECT * FROM `" . JMLADATBAZIS . "`.`unsubscribe` WHERE code = ?";
Database::getInstance()->query($query, array('s', $code));
$exist = Database::getInstance()->fetchAssoc();

if (empty($exist)) {
    header("Location: /");
    exit();
} else {
    $query = "SELECT DISTINCT(nUserID) FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email = ?";
    Database::getInstance()->query($query, array('s', $exist['email']));
    $res = Database::getInstance()->fetchAssoc();

    foreach ($res as $sor => $user) {
        $nUserID = $user['nUserID'];

        //  u_history-ba beírás
        crm_users::AddUserHistory(array(
            'nUserID'   => $nUserID,
            'nTopicID'  => $topicId,
            'strInfo'   => $exist['email']
        ));

        $query = "SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID = ?";
        Database::getInstance()->query($query, array('i', $nUserID));
        $u = Database::getInstance()->fetchNext();

        //  userstatus felülírása, ha 99, vagy <=8
        if ((int)$u['nUserStatus'] == 99 || (int)$u['nUserStatus'] <= 8) {
            $query = "UPDATE `" . CRMADATBAZIS . "`.`users` SET nUserStatus = ? WHERE nUserID = ? LIMIT 1";
            Database::getInstance()->query($query, array('ii', -5, $nUserID));
            Database::getInstance()->insert(
                CRMADATBAZIS . ".`u_userstatus_history`",
                array(
                    'nUserID'       => $nUserID,
                    'val'           => -5,
                    'changeDate'    => date("Y-m-d H:i:s", time()),
                    'nManagerID'    => $nManagerID
                ),
                'iisi'
            );
        }
    }

    Database::getInstance()->update(CRMADATBAZIS . ".u_emails", array('newsletter' => 0), array('email' => $exist['email']), 'is');

    Database::getInstance()->update(JMLADATBAZIS . ".unsubscribe", array('deleted' => 1), array('code' => $code), 'is');

    header("Location: /index.php?option=com_content&view=article&id=958");
    exit();
}
