<?php

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

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

$app->checkToken();

$id = (int)$_POST['id'];

// get data of bulk verification
$stmt = $db->prepare("
    SELECT verify_id FROM  ".PREF."_verify_bulk WHERE id = ?
");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchAll();

// in case you want to check not existent data
if (! @$data = $row[0]){
    echo DATA_ERROR;
    exit();
}

// verifying id for curl
$verify_id = $data['verify_id'];

// link to check verified mails
$url = "https://api.thechecker.co/v2/verifications/".$verify_id."/json?api_key=".Settings::$thechecker;

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
curl_close($ch);

$json = json_decode($result, true);

// prepare message for admin
$message = '';

if (! isset($json['message'])) {

    // update recipient verify status
    foreach ($json as $status => $arr) {
        $message .= $status.":";
        $qty = 0;
        foreach ( $arr as $key1 => $arr2 ) {
            foreach ( $arr2 as $key2 => $email ) {
                
                $sql = "
                    UPDATE 
                        ".PREF."_recipient
                    SET 
                        verified = :status
                    WHERE 
                        email = :email
                ";
                $stmt = $db->prepare($sql);
                $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                $stmt->bindParam(':status', $status, PDO::PARAM_STR);
                $stmt->execute();
                $qty ++;
            }
        }
        $message .= $qty.", ";
    }
} else {
    $message = $json['message'];
}

// send message to admin
echo $message;

