<?php

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

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

$app->checkToken();

//datatable filters
$globalSearch = $app->clearSQL($_POST['globalSearch']); // search field
$globalTags = $app->clearSQL($_POST['globalTags']); // id's of selected tags (1,2,3)
$globalLogic = $app->clearSQL($_POST['globalLogic']); // AND|OR
//modal params
$recipientsChecked = $app->clearSQL($_POST['recipientsArr']); // if checkoxes are checked (1,2,3)
$tagsLogic = $app->clearSQL($_POST['tagsLogic']); // add|remove
$newtags = $app->clearSQL($_POST['newtags']); // array

// checked rows and all ids in one variable
if ($recipientsChecked != '') {
    $recipientsArr = explode(',', $recipientsChecked);
    foreach ($recipientsArr as $recipientId) {
        if (count($newtags)) {
            if ($tagsLogic == 'add') {
                foreach ($newtags as $newTag) {
                    // insert new tags connection, duplicates will be ignored due to multi rows primary key
                    $sql = "
                        INSERT INTO ".PREF."_recipient_tag_conn (
                            id_recipient,
                            id_tag
                        ) VALUES (
                            :id_recipient,
                            :id_tag
                        )
                    ";
                    $stmt = $db->prepare($sql);
                    $stmt->bindParam(':id_recipient', $recipientId, PDO::PARAM_STR);    
                    $stmt->bindParam(':id_tag', $newTag, PDO::PARAM_STR);
                    $stmt->execute();
                }
            } else {
                foreach ($newtags as $newTag) {
                    // delete all recipients connections with current tag
                    $sql = "DELETE FROM ".PREF."_recipient_tag_conn WHERE id_recipient = :id_recipient AND id_tag = :id_tag ";
                    $stmt = $db->prepare($sql);
                    $stmt->bindParam(':id_recipient', $recipientId, PDO::PARAM_INT);
                    $stmt->bindParam(':id_tag', $newTag, PDO::PARAM_INT);
                    $stmt->execute();
                }
            }
        }
    }
}

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