<?php // loadEmail.php
require_once __DIR__ . '/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../' . $tenant . '/config.php')) {
    require_once('../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();

if (!headers_sent()) {
    header('Content-Type: application/json; charset=utf-8');
}

$type = enrep_request_enum('type', ['all', 'billing', 'delivery', 'renewal', 'client', 'agent', 'broker'], 'all');
$clientnumber = enrep_request_int('clientnumber');
$site = enrep_request_int('site');

if ($clientnumber <= 0) {
    echo json_encode([]);
    exit();
}

function ab_normalise_assignment_type($raw): array {
    $default = ['billing' => 0, 'delivery' => 0, 'renewal' => 0];

    if ($raw === null) return $default;
    $raw = trim((string)$raw);
    if ($raw === '') return $default;

    if ($raw[0] === '{' || $raw[0] === '[') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            $out = $default;

            $isList = (array_keys($decoded) === range(0, count($decoded) - 1));
            if ($isList) {
                foreach ($decoded as $v) {
                    $k = strtolower(trim((string)$v));
                    if (array_key_exists($k, $out)) $out[$k] = 1;
                }
            } else {
                foreach ($out as $k => $v) {
                    if (isset($decoded[$k])) $out[$k] = (int)!!$decoded[$k];
                }
            }
            return $out;
        }
    }

    $legacy = strtolower($raw);
    if ($legacy === 'all') return ['billing' => 1, 'delivery' => 1, 'renewal' => 1];
    if (array_key_exists($legacy, $default)) {
        $default[$legacy] = 1;
        return $default;
    }

    return $default;
}

function role_is_set(array $roles): bool {
    return (!empty($roles['billing']) || !empty($roles['delivery']) || !empty($roles['renewal']));
}

function address_book_truthy_flag($value): bool {
    $value = strtolower(trim((string)$value));
    return in_array($value, ['1', 'true', 'yes', 'y', 'on', 'delivery', 'all'], true);
}

function address_book_delivery_role_is_set(array $row): bool {
    $roles = ab_normalise_assignment_type($row['assignment_type'] ?? '');
    if (!empty($roles['delivery'])) {
        return true;
    }

    foreach (['delivery', 'delivery_email', 'report_delivery', 'send_delivery'] as $legacyColumn) {
        if (array_key_exists($legacyColumn, $row) && address_book_truthy_flag($row[$legacyColumn])) {
            return true;
        }
    }

    return false;
}

function address_book_site_matches($raw, int $site): bool {
    $raw = trim((string)$raw);
    if ($raw === '' || strtolower($raw) === 'all') return true;
    if ($site <= 0) return false;

    $sites = [];
    if ($raw[0] === '[') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            $sites = array_map('intval', $decoded);
        }
    } else {
        $sites = array_map('intval', preg_split('/\s*,\s*/', $raw));
    }

    return in_array($site, $sites, true);
}

/**
 * renewOptions JSON destination:
 * notice  => renewals destination key (0 client, 1 agent, 2 broker)
 * inotice => billing destination key  (0 client, 1 agent, 2 broker)
 *
 * notice mapping:
 * 0 => clientdetails.pri_contact_email
 * 1 => agents.email
 * 2 => brokers.email
 *
 * inotice mapping:
 * 0 => clientdetails.billing_email
 * 1 => agents.billing_email
 * 2 => brokers.billing_email
 */
function get_notice_email_for_client(int $clientnumber, string $mode): string {
    if ($clientnumber <= 0) return '';

    $stmt = $GLOBALS['con']->prepare("
        SELECT `pri_contact_email`, `billing_email`, `agent_number`, `broker_number`, `renewOptions`
        FROM `clientdetails`
        WHERE `clientnumber` = ?
        LIMIT 1
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    if (!$rs || $rs->num_rows === 0) return '';
    $cd = mysqli_fetch_assoc($rs);

    $opts = [];
    if (!empty($cd['renewOptions'])) {
        $decoded = json_decode($cd['renewOptions'], true);
        if (is_array($decoded)) $opts = $decoded;
    }

    $key = null;
    if ($mode === 'billing') $key = $opts['inotice'] ?? null;
    if ($mode === 'renewal') $key = $opts['notice'] ?? null;

    $key = is_numeric($key) ? (int)$key : null;

    // Client
    if ($key === null || $key === 0) {
        return $mode === 'renewal'
            ? (string)($cd['pri_contact_email'] ?? '')
            : (string)($cd['billing_email'] ?? '');
    }

    // Agent
    if ($key === 1) {
        $agentNo = (int)($cd['agent_number'] ?? 0);
        if ($agentNo > 0) {
            $stmt2 = $GLOBALS['con']->prepare("
                SELECT `email`, `billing_email`
                FROM `agents`
                WHERE `agent_number` = ?
                LIMIT 1
            ") or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i', $agentNo);
            $stmt2->execute();
            $rs2 = $stmt2->get_result();
            $stmt2->close();

            if ($rs2 && $rs2->num_rows > 0) {
                $ad = mysqli_fetch_assoc($rs2);
                return $mode === 'renewal'
                    ? (string)($ad['email'] ?? '')
                    : (string)($ad['billing_email'] ?? '');
            }
        }
        return '';
    }

    // Broker
    if ($key === 2) {
        $brokerNo = (int)($cd['broker_number'] ?? 0);
        if ($brokerNo > 0) {
            $stmt2 = $GLOBALS['con']->prepare("
                SELECT `email`, `billing_email`
                FROM `brokers`
                WHERE `broker_number` = ?
                LIMIT 1
            ") or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i', $brokerNo);
            $stmt2->execute();
            $rs2 = $stmt2->get_result();
            $stmt2->close();

            if ($rs2 && $rs2->num_rows > 0) {
                $bd = mysqli_fetch_assoc($rs2);
                return $mode === 'renewal'
                    ? (string)($bd['email'] ?? '')
                    : (string)($bd['billing_email'] ?? '');
            }
        }
        return '';
    }

    return '';
}

$typeLc = strtolower((string)$type);

/**
 * DELIVERY (SPECIAL):
 * - ONLY use address_book entries explicitly marked delivery.
 * - If none exist, fall back to the client's primary email (clientdetails.primary_email if present, else pri_contact_email).
 * - No renewOptions / agent / broker routing for delivery.
 */
if ($typeLc === 'delivery') {
    $stmt = $GLOBALS['con']->prepare("
        SELECT *
        FROM `address_book`
        WHERE `clientnumber` = ? AND `auto` = 1
        ORDER BY ABS(indexer) ASC
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $cr = $stmt->get_result();
    $stmt->close();

    $ret = [];
    while ($r = mysqli_fetch_assoc($cr)) {
        $email = (string)($r['email'] ?? '');
        if ($email === '') continue;
        if (!address_book_site_matches($r['site_numbers'] ?? '', $site)) continue;

        if (address_book_delivery_role_is_set($r)) $ret[] = ['email' => $email];
    }

    // De-dupe (case-insensitive) while preserving order
    $seen = [];
    $final = [];
    foreach ($ret as $row) {
        $e = strtolower(trim((string)($row['email'] ?? '')));
        if ($e === '' || isset($seen[$e])) continue;
        $seen[$e] = true;
        $final[] = ['email' => $row['email']];
    }

    if (!empty($final)) {
        echo json_encode($final);
        exit();
    }

    // Fallback: client primary/main email using established clientdetails columns.
    $stmt = $GLOBALS['con']->prepare("
        SELECT `pri_contact_email`, `email`
        FROM `clientdetails`
        WHERE `clientnumber` = ?
        LIMIT 1
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    $fallback = '';
    if ($rs && $rs->num_rows > 0) {
        $cd = mysqli_fetch_assoc($rs);
        $fallback = trim((string)($cd['pri_contact_email'] ?? ''));
        if ($fallback === '') $fallback = trim((string)($cd['email'] ?? ''));
    }

    echo $fallback !== '' ? json_encode([['email' => $fallback]]) : json_encode([]);
    exit();
}

/**
 * MODE 1: billing/renewal ONLY
 * - Try to resolve renewOptions inotice/notice.
 * - If we get a valid email, return it immediately (do NOT fall back to address_book).
 * - If not, continue into address_book method (MODE 2).
 */
$preferredEmail = '';
if ($typeLc === 'billing' || $typeLc === 'renewal') {
    $pref = trim(get_notice_email_for_client($clientnumber, $typeLc));
    if ($pref !== '') {
        $preferredEmail = $pref;
    }
}

/**
 * MODE 2: address_book auto emails (existing behaviour)
 */
$stmt = $GLOBALS['con']->prepare("
    SELECT *
    FROM `address_book`
    WHERE `clientnumber` = ? AND `auto` = 1
    ORDER BY ABS(indexer) ASC
") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $clientnumber);
$stmt->execute();
$cr = $stmt->get_result();
$stmt->close();

$rows = [];
while ($r = mysqli_fetch_assoc($cr)) {
    if (!empty($r['email']) && address_book_site_matches($r['site_numbers'] ?? '', $site)) $rows[] = $r;
}

$ret = [];
if ($preferredEmail !== '') {
    $ret[] = ['email' => $preferredEmail];
}

// If there is only one auto entry and it has no assignment set, use it for all uses.
if ($preferredEmail === '' && count($rows) === 1) {
    $only = $rows[0];
    $roles = ab_normalise_assignment_type($only['assignment_type'] ?? '');
    if (!role_is_set($roles)) {
        echo json_encode([['email' => (string)$only['email']]]);
        exit();
    }
}

foreach ($rows as $r) {
    $email = (string)$r['email'];
    if ($email === '') continue;

    if ($typeLc === 'all') {
        $ret[] = ['email' => $email];
        continue;
    }

    if (in_array($typeLc, ['client', 'agent', 'broker'], true)) {
        if (strtolower((string)$r['type']) === $typeLc) $ret[] = ['email' => $email];
        continue;
    }

    $roles = ab_normalise_assignment_type($r['assignment_type'] ?? '');
    if (!empty($roles[$typeLc])) $ret[] = ['email' => $email];
}

// De-dupe (case-insensitive) while preserving order
$seen = [];
$final = [];
foreach ($ret as $row) {
    $e = strtolower(trim((string)($row['email'] ?? '')));
    if ($e === '' || isset($seen[$e])) continue;
    $seen[$e] = true;
    $final[] = ['email' => $row['email']];
}

echo json_encode($final);
