<?php //loadEmail.php
if(file_exists('../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}


$type = $_REQUEST['type'] ?? 'all';
$clientnumber = intval($_REQUEST['clientnumber']);

if (in_array($type, ['client', 'agent', 'broker'])) {
    $stmt = $GLOBALS['con']->prepare("SELECT `email` FROM `address_book` WHERE `clientnumber` = ? AND `auto` = '1' AND `type` = ? ORDER BY ABS(indexer) ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('is', $clientnumber, $type);
} elseif ($type === 'all') {
    $stmt = $GLOBALS['con']->prepare("SELECT `email` FROM `address_book` WHERE `clientnumber` = ? AND `auto` = '1' ORDER BY ABS(indexer) ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
} else {
    $stmt = $GLOBALS['con']->prepare("SELECT `email` FROM `address_book` WHERE `clientnumber` = ? AND `auto` = '1' AND `assignment_type` = ? ORDER BY ABS(indexer) ASC") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('is', $clientnumber, $type);
}

$stmt->execute();
$cr = $stmt->get_result();
$stmt->close();

$ret = [];
while($cd = mysqli_fetch_array($cr)){
    if (!empty($cd['email'])) {
        $ret[] = ['email' => $cd['email']];
    }
}

echo json_encode($ret);
?>