<?php
function crm_array_int($v) {
    if (!is_array($v)) return [];
    $out = [];
    foreach ($v as $x) { $x = (int)$x; if ($x > 0) $out[] = $x; }
    return array_values(array_unique($out));
}

function crm_rules_from_request() {
    return [
        'country_ids' => crm_array_int($_POST['country_ids'] ?? []),
        'priority'    => crm_array_int($_POST['priority'] ?? []),
        'label_ids'   => crm_array_int($_POST['label_ids'] ?? []),
        'has_leads'   => !empty($_POST['has_leads']) ? 1 : 0,
        'item_ids'    => crm_array_int($_POST['item_ids'] ?? []),
    ];
}

function crm_customer_filter_sql($conn, $account_id, $rules) {
    $account_id = (int)$account_id;
    $rules = is_array($rules) ? $rules : [];
    $where = ["c.account_id = $account_id"];
    $joins = [];

    $country_ids = crm_array_int($rules['country_ids'] ?? []);
    if ($country_ids) $where[] = 'c.country_id IN (' . implode(',', $country_ids) . ')';

    $priority = crm_array_int($rules['priority'] ?? []);
    if ($priority) $where[] = 'c.priority IN (' . implode(',', $priority) . ')';

    $label_ids = crm_array_int($rules['label_ids'] ?? []);
    if ($label_ids) {
        $joins[] = "INNER JOIN entity_labels el_filter ON el_filter.account_id=$account_id AND el_filter.entity_type='customer' AND el_filter.entity_id=c.id AND el_filter.label_id IN (" . implode(',', $label_ids) . ")";
    }

    $has_leads = !empty($rules['has_leads']);
    $item_ids = crm_array_int($rules['item_ids'] ?? []);
    if ($has_leads || $item_ids) {
        $leadJoin = "INNER JOIN leads l_filter ON l_filter.customer_id=c.id AND l_filter.account_id=$account_id AND l_filter.datetime_deleted IS NULL";
        if ($item_ids) $leadJoin .= " AND l_filter.item_id IN (" . implode(',', $item_ids) . ")";
        $joins[] = $leadJoin;
    }

    return [implode("\n", $joins), implode(' AND ', $where)];
}

function crm_count_customers_by_rules($conn, $account_id, $rules) {
    [$joins, $where] = crm_customer_filter_sql($conn, $account_id, $rules);
    $q = $conn->query("SELECT COUNT(DISTINCT c.id) cnt FROM customers c $joins WHERE $where");
    return $q ? (int)$q->fetch_assoc()['cnt'] : 0;
}

function crm_get_customers_by_rules($conn, $account_id, $rules, $limit = 200, $offset = 0) {
    $limit = max(1, (int)$limit); $offset = max(0, (int)$offset);
    [$joins, $where] = crm_customer_filter_sql($conn, $account_id, $rules);
    return $conn->query("SELECT DISTINCT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority, co.name country_name
        FROM customers c
        LEFT JOIN countries co ON co.id=c.country_id
        $joins
        WHERE $where
        ORDER BY c.customer_name ASC
        LIMIT $offset, $limit");
}

function crm_refresh_audience_customers($conn, $account_id, $audience_id, $rules) {
    $account_id = (int)$account_id; $audience_id = (int)$audience_id;
    $conn->query("DELETE ac FROM audience_customers ac INNER JOIN audience a ON a.id=ac.audience_id WHERE ac.audience_id=$audience_id AND a.account_id=$account_id");
    [$joins, $where] = crm_customer_filter_sql($conn, $account_id, $rules);
    $conn->query("INSERT INTO audience_customers (audience_id, customer_id, date_created)
        SELECT $audience_id, x.id, NOW()
        FROM (SELECT DISTINCT c.id FROM customers c $joins WHERE $where) x");
    return crm_count_customers_by_rules($conn, $account_id, $rules);
}

function crm_decode_rules($json) {
    $rules = json_decode($json ?? '', true);
    return is_array($rules) ? $rules : [];
}
?>
