<?php

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

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

$app->checkToken();

$search = $app->clearSQL($_POST['search']);
$tags = $app->clearSQL($_POST['tags']); // id's of selected tags
$logic = $app->clearSQL($_POST['logic']);


// 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 (
                r.person LIKE '%".$val."%' OR 
                r.email LIKE '%".$val."%' OR 
                r.comment LIKE '%".$val."%' OR 
                r.website LIKE '%".$val."%' OR
                r.f01 LIKE '%".$val."%' OR
                r.f02 LIKE '%".$val."%' OR
                r.f03 LIKE '%".$val."%' OR
                r.verified LIKE '%".$val."%'
            ) ";
    }
} else {
    $filtr = "";
}

if ($tags != '') {
    $logicFilter = '';
    if ($logic == 'OR') {
        $logicFilter = "  ";
    } else {
        $tagsArray = explode(',', $tags);
        $logicFilter = " group by rtc.id_recipient having count(rtc.id_recipient) = ".count($tagsArray);
    }
    $sql = "
        DELETE r FROM ".PREF."_recipient AS r WHERE id IN(
            SELECT id_recipient
            FROM ".PREF."_recipient_tag_conn AS rtc 
            WHERE rtc.id_tag IN(".$tags.")
            ".$logicFilter."
        ) ".$filtr."
    ";
    
    $db->query($sql);
    
    $sql = "
        DELETE rtc FROM ".PREF."_recipient_tag_conn as rtc 
            WHERE rtc.id_recipient NOT IN (SELECT id FROM ".PREF."_recipient)
    ";
    $db->query($sql);
} else {
    $sql = "
        DELETE rtc FROM ".PREF."_recipient_tag_conn AS rtc LEFT JOIN ".PREF."_recipient AS r ON rtc.id_recipient = r.id WHERE 1
        ".$filtr."
    ";
    $db->query($sql);
    
    $db->query('SET SQL_SAFE_UPDATES=0;');
    
    $sql = "
        DELETE r FROM ".PREF."_recipient as r where 1 
        ".$filtr."
    ";
    
    
    $db->query($sql);
}

header("Location: index.php?manage=recipient&action=list");