<?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'] ?? []),
        'customer_ids' => crm_array_int($_POST['customer_ids'] ?? []),
        'source_ids'   => crm_array_int($_POST['source_ids'] ?? []),
    ];
}
function crm_decode_rules($json) { $rules=json_decode($json ?? '', true); return is_array($rules)?$rules:[]; }
function crm_customer_filter_sql($conn, $account_id, $rules) {
    $account_id=(int)$account_id; $rules=is_array($rules)?$rules:[];
    $baseWhere=["c.account_id = $account_id"];
    if (columnExists($conn,'customers','datetime_deleted')) $baseWhere[] = "c.datetime_deleted IS NULL";
    $joins=[];
    $filterWhere=[];
    $country_ids=crm_array_int($rules['country_ids']??[]);
    if($country_ids)$filterWhere[]='c.country_id IN ('.implode(',',$country_ids).')';
    $priority=crm_array_int($rules['priority']??[]);
    if($priority)$filterWhere[]='c.priority IN ('.implode(',',$priority).')';
    $source_ids=crm_array_int($rules['source_ids']??[]);
    if($source_ids && columnExists($conn,'customers','source_id')) $filterWhere[]='c.source_id IN ('.implode(',',$source_ids).')';
    $label_ids=crm_array_int($rules['label_ids']??[]);
    if($label_ids){
        $joins[]="INNER JOIN customer_lable_customers clc_filter ON clc_filter.account_id=$account_id AND clc_filter.customer_id=c.id AND clc_filter.lable_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;
    }
    $manual=crm_array_int($rules['customer_ids']??[]);
    if($manual){
        $manualSql='c.id IN ('.implode(',',$manual).')';
        $filterSql=$filterWhere?('('.implode(' AND ',$filterWhere).')'):'0=1';
        $baseWhere[]="($manualSql OR $filterSql)";
    } elseif($filterWhere) {
        $baseWhere[]=implode(' AND ',$filterWhere);
    }
    return [implode("\n",$joins), implode(' AND ',$baseWhere)];
}
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_audience_new_customer_ids($conn,$account_id,$audience_id,$rules){
    $account_id=(int)$account_id; $audience_id=(int)$audience_id;
    [$joins,$where]=crm_customer_filter_sql($conn,$account_id,$rules);
    $res=$conn->query("SELECT DISTINCT c.id FROM customers c $joins WHERE $where AND c.id NOT IN (SELECT customer_id FROM audience_customers WHERE audience_id=$audience_id)");
    $ids=[]; if($res){ while($r=$res->fetch_assoc()) $ids[]=(int)$r['id']; }
    return $ids;
}
function crm_add_new_audience_customers($conn,$account_id,$audience_id,$rules){
    $ids=crm_audience_new_customer_ids($conn,$account_id,$audience_id,$rules);
    foreach($ids as $cid){ $cid=(int)$cid; $conn->query("INSERT INTO audience_customers (audience_id,customer_id,date_created,created_at,updated_at) VALUES ($audience_id,$cid,NOW(),NOW(),NOW()) ON DUPLICATE KEY UPDATE updated_at=updated_at"); }
    return count($ids);
}

function crm_refresh_audience_customers($conn,$account_id,$audience_id,$rules){
    $account_id=(int)$account_id; $audience_id=(int)$audience_id;
    [$joins,$where]=crm_customer_filter_sql($conn,$account_id,$rules);
    $res=$conn->query("SELECT DISTINCT c.id FROM customers c $joins WHERE $where");
    $current=[];
    if($res){ while($r=$res->fetch_assoc()) $current[]=(int)$r['id']; }
    if(!$current){
        $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");
        return 0;
    }
    $ids=implode(',', $current);
    $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 AND ac.customer_id NOT IN ($ids)");
    foreach($current as $cid){
        $cid=(int)$cid;
        $conn->query("INSERT INTO audience_customers (audience_id,customer_id,date_created,created_at,updated_at) VALUES ($audience_id,$cid,NOW(),NOW(),NOW()) ON DUPLICATE KEY UPDATE updated_at=NOW()");
        if($conn->errno){
            $conn->query("INSERT IGNORE INTO audience_customers (audience_id,customer_id,date_created) VALUES ($audience_id,$cid,NOW())");
        }
    }
    return count($current);
}
?>
