<?php

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

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

$app->checkToken();

$fraza = $_POST['ver_search'];
$tags = $app->clearSQL($_POST['ver_tags']);
$logic = $app->clearSQL($_POST['ver_logic']);
$ver_qty = (int)($_POST['ver_qty']);

if ($fraza != ''){
    $filtr = '';
    $fraza_array = explode(" ", $fraza);
    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 = "";
}

// get data of recipients
if ($tags != '') {
    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 = "
            select 
                email
            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 = "
        select 
            email
        from 
            ".PREF."_recipient as r
        where 1 
            ".$filtr."
    ";
}

$result = $db->query($sql);
$mailsArr = array();
foreach ($result as $row) {
    $mailsArr[] = $row['email'];
}

$data = '{"emails":'.json_encode($mailsArr).'}';

$url = "https://api.thechecker.co/v2/verifications?api_key=".Settings::$thechecker;

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER,
           array(
                'cache-control:no-cache',
                'Content-Type:application/json',
                'Content-Length: ' . strlen($data)
                )
           );
$result = curl_exec($ch);
curl_close($ch);

//print_r($result);

$json = json_decode($result, true);

if (isset($json['message'])) {
    echo $json['message'];
    exit();
}
//echo "ID json:".$json['id'];
//echo " ver_qty:".$ver_qty;


// print_r($json);

$sql = "
    INSERT INTO ".PREF."_verify_bulk (
        verify_id,
        verify_qty
    ) VALUES (
        :verify_id,
        :verify_qty
    )
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':verify_id', $json['id'], PDO::PARAM_STR);
$stmt->bindParam(':verify_qty', $ver_qty, PDO::PARAM_INT);
$stmt->execute();

echo B_VER_SENT;

