<?php

defined('_MAILING') or die('Restricted access');

if (DEMO_MODE) {
    echo "ok";
    exit();
}

// get main data
$id_campaign    = isset($_GET['id_campaign']) ? (int)($_GET['id_campaign']) : (int)($_POST['id_campaign']);
$email_admin    = isset($_GET['email_admin']) ? $_GET['email_admin'] : $_POST['email_admin'];
$smtpid         = isset($_GET['smtpid']) ? (int)($_GET['smtpid']) : (int)($_POST['smtpid']);
$notify_admin   = isset($_GET['notify_admin']) ? (int)($_GET['notify_admin']) : (int)($_POST['notify_admin']);
$cron_token     = '';
$multi_smtp     = isset($_POST['multi_smtp']) ? $_POST['multi_smtp'] : '0';
$smtp_arr       = isset($_POST['smtp_arr']) ? $_POST['smtp_arr'] : false;

if (DEBUG) {
    $app->saveLog(" -------------------------------------------------------- ");
    $app->saveLog("DEGUB (id_campaign): ".$id_campaign);
    $app->saveLog("DEGUB (email_admin): ".$email_admin);
    $app->saveLog("DEGUB (smtpid): ".$smtpid);
    $app->saveLog("DEGUB (notify_admin): ".$notify_admin);
    $app->saveLog("DEGUB (cron_token): ".$cron_token);
    $app->saveLog("DEGUB (multi_smtp): ".$multi_smtp);
    $app->saveLog("DEGUB (smtp_arr): ".$smtp_arr." count(smtp_arr): ".count($smtp_arr));
    $app->saveLog(" -------------------------------------------------------- ");
}

// just in case
if ($id_campaign == 0) {
    die();
}

$cron   = isset($_GET['cron']) ? true : false;
$status = $cron ? '5' : '3';

// update campaign data (3 - during background sending, 5 - cron)
$sql = "
    UPDATE ".PREF."_campaign SET
        date_start = '".date("Y-m-d H:i:s", time())."',
        status = '".$status."'
    WHERE id = :id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id_campaign, PDO::PARAM_INT);
$stmt->execute();

// prepare sending params
$params['id_campaign'] = $id_campaign;
$params['smtpid'] = $smtpid;
$params['notify_admin'] = '0';
$params['email_admin'] = '';
$params['db'] = $db;
$params['cron'] = false;
$params['cron_token'] = $cron ? (isset($_GET['cron_token']) ? $_GET['cron_token'] : $_POST['cron_token']) : '';
$params['debug'] = DEBUG;
$params['multi_smtp'] = $multi_smtp;
    
// log background
$app->saveLog(" background started ");

if ($cron) {
    $app->sendEmail($params);
    // log background
    DEBUG && $app->saveLog(" DEGUB (id_campaign): ".$id_campaign);
} else {
    // check security
    $app->checkToken();
    // wait for 1 second
    usleep(1000000);

if (! $cron) {
    $app->closeConnection('ok', 200);
}

    $limitPerHour = 1;
    if ($multi_smtp == '1') {
        foreach ($smtp_arr as $smtpid) {
            $stmt = $db->prepare(" select * from ".PREF."_smtp where id=? ");
            $stmt->bindParam(1, $smtpid, PDO::PARAM_INT);
            $stmt->execute();
            $row = $stmt->fetchAll();
            $data = $row[0];
            $maxlimit = (int) $data['maxlimit'];
            $limitPerHour = $limitPerHour == 1 ? $maxlimit : ($maxlimit <= $limitPerHour ? $maxlimit : $limitPerHour);
        }
        // log background
        DEBUG && $app->saveLog(" DEGUB multi smtp enabled (limitPerHour): ".$limitPerHour);
        
    } else {
        $stmt = $db->prepare(" select * from ".PREF."_smtp where id=? ");
        $stmt->bindParam(1, $smtpid, PDO::PARAM_INT);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $data = $row[0];
        $limitPerHour = (int) $data['maxlimit'];
        
        // log background
        DEBUG && $app->saveLog(" DEGUB single smtp enabled (limitPerHour): ".$limitPerHour);
    }


    // BELOW BACKGROUND JOB/CODE
    $goBackground = false;
    do {
        try {
            // log background
            DEBUG && $app->saveLog(" DEGUB (goBackground): start ");
            
            if ($multi_smtp == '1') {
                 foreach ($smtp_arr as $smtpid) {
                    $params['smtpid'] = $smtpid;
                    $goBackground = $app->sendEmail($params);
                }
                $usleep = (int) (ceil((60 * 60 * 1000000) / (int)($limitPerHour)));
                // log background
                DEBUG && $app->saveLog(" DEGUB multi smtp rotation restart (usleep): ".$usleep." (limitPerHour): ".$limitPerHour);
                usleep( $usleep );
            } else {
                $goBackground = $app->sendEmail($params);
            }
            // log background
            DEBUG && $app->saveLog(" DEGUB (multi_smtp): ".$multi_smtp." (goBackground): ".$goBackground);
                
        } catch (Exception $e) {
            $err = error_get_last();
            $app->saveLog(" TYPE:".$err['type']." LINE:".$err['line']." MESSAGE:".$err['message']." FILE:".$err['file']);
        }
    } while ($goBackground);
}

// log background
DEBUG && $app->saveLog(" background finished ");



