<?php

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

if (DEMO_MODE) {
    header("Location: index.php?manage=campaign&action=waiting");
    exit();
}

$app->checkToken();

/**
 * get new campaign data
 */
$name = $app->clearSQL($_POST['name']);
$search = $app->clearSQL($_POST['search']);
$id_template = (int)($_POST['id_template']);
$id_sender = (int)($_POST['id_sender']);
$recipient_qty = (int)($_POST['recipient_qty']);
$status = '0';
$tags = $app->clearSQL($_POST['tags']);
$logic = $app->clearSQL($_POST['logic']);


/**
 * insert new campaign to db
 */
$sql = "
    INSERT INTO ".PREF."_campaign  (
        name, 
        recipient_qty,  
        id_template,  
        id_sender,
        status
    ) VALUES (
        :name,
        :recipient_qty,
        :id_template,
        :id_sender,
        :status
    )
";
$stmt = $db->prepare($sql);              
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':recipient_qty', $recipient_qty, PDO::PARAM_STR);
$stmt->bindParam(':id_template', $id_template, PDO::PARAM_STR);
$stmt->bindParam(':id_sender', $id_sender, PDO::PARAM_STR);
$stmt->bindParam(':status', $status, PDO::PARAM_STR);
$stmt->execute(); 


/**
 * get id of inserted campaign
 */
$id_campaign = $db->lastInsertId();


/**
 * prepare filter for sql for recipients id based on posted search field
 */
if ($search != '') {
    $filtr = '';
    $fraza_array = explode(" ", $search);
    foreach ($fraza_array as $val) {
        $filtr .= " AND (person LIKE '%".$val."%' OR email LIKE '%".$val."%' OR comment LIKE '%".$val."%' OR website LIKE '%".$val."%' OR tag LIKE '%".$val."%') ";
    }
} else {
    $filtr = "";
}

/**
 * get all selected recipients id
 */
if ($tags != '') {
    $logicFilter = '';
    if ($logic == 'OR') {
        $logicFilter = " AND rtc.id_tag in (".$tags.") ";
    } else {
        $tagsArray = explode(',', $tags);
        $logicFilter = " group by rtc.id_recipient having count(rtc.id_recipient) = ".count($tagsArray);
    }
    $sql = "
        INSERT INTO ".PREF."_campaign_rec_conn
            (id_recipient, id_campaign)
        SELECT 
            distinct(rtc.id_recipient) as id,
            ".$id_campaign."
        FROM 
            ".PREF."_recipient_tag_conn as rtc 
            left join ".PREF."_recipient as r on r.id=rtc.id_recipient 
        WHERE 1
            AND rtc.id_tag in (".$tags.")
            ".$filtr."
            ".$logicFilter."
        
    ";
} else {
    $sql = "
        INSERT INTO ".PREF."_campaign_rec_conn
            (id_campaign, id_recipient)
        SELECT 
            ".$id_campaign.",
            id 
        FROM 
            ".PREF."_recipient as r 
        WHERE 1 
            ".$filtr."
    ";
}
$result = $db->query($sql);

// just in case
$sql = "
    DELETE FROM ".PREF."_campaign_rec_conn
    WHERE 
        id_recipient IS null
        OR id_recipient = 0
";
$result = $db->query($sql);

header("Location: index.php?manage=campaign&action=waiting");
