<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>(function_exists('crmTranslateMessage') ? crmTranslateMessage('Unauthorized') : 'Unauthorized')])); }
require_once '../connect.php';
require_once '../lib/audience_rules.php';
$account_id=(int)$_SESSION['account_id']; $user_id=(int)$_SESSION['user_id'];
$raw=file_get_contents('php://input'); $json=$raw?json_decode($raw,true):[]; if (is_array($json)) crmDecodeIdsInArray($json); crmDecodeIdsInArray($_POST);
$action=$_POST['action'] ?? ($json['action'] ?? '');
if ($action === 'update') $action = 'refresh';

function audience_preview_html($res){
    $html='<div class="card" style="margin-top:10px"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Customer</th><th>Business</th><th>Phone</th><th>Email</th></tr></thead><tbody>';
    $i=0; while($res && $r=$res->fetch_assoc()){ $i++; $html.='<tr><td>'.htmlspecialchars($r['customer_name']).'</td><td>'.htmlspecialchars($r['business_name']?:'—').'</td><td>'.htmlspecialchars($r['phone']?:'—').'</td><td>'.htmlspecialchars($r['email']?:'—').'</td></tr>'; }
    if(!$i) $html.='<tr><td colspan="4" class="text-center text-muted">No customers found</td></tr>';
    return $html.'</tbody></table></div></div>';
}

if ($action === 'preview') {
    requirePermission($conn,'audience','view');
    $rules=crm_rules_from_request();
    $count=crm_count_customers_by_rules($conn,$account_id,$rules);
    $rows=crm_get_customers_by_rules($conn,$account_id,$rules,30,0);
    jsonResponse(true,'',['count'=>$count,'html'=>audience_preview_html($rows)]);
}

if ($action === 'save') {
    $id=crmId($_POST['id'] ?? 0);
    requirePermission($conn,'audience',$id?'edit':'add');
    $name=sanitize($conn,$_POST['name'] ?? '');
    $description=sanitize($conn,$_POST['description'] ?? '');
    $statuss=(int)($_POST['statuss'] ?? 1);
    if(!$name) jsonResponse(false,'Audience name required');
    $rules=crm_rules_from_request();
    $rules_json=sanitize($conn,json_encode($rules, JSON_UNESCAPED_UNICODE));
    if($id){
        $conn->query("UPDATE audience SET name='$name', description='$description', statuss=$statuss, rules_json='$rules_json' WHERE id=$id AND account_id=$account_id");
    } else {
        $conn->query("INSERT INTO audience (name,description,statuss,account_id,added_by,rules_json,date_created) VALUES ('$name','$description',$statuss,$account_id,$user_id,'$rules_json',NOW())");
        $id=$conn->insert_id;
    }
    $count=crm_refresh_audience_customers($conn,$account_id,$id,$rules);
    $return_to = $_POST['return_to'] ?? 'index.php?page=audience';
    jsonResponse(true,'Audience saved',['id'=>crmEncodeId($id),'count'=>$count,'redirect'=>$return_to]);
}


if ($action === 'preview_update' || $action === 'add_new') {
    requirePermission($conn,'audience','edit');
    $id=(int)($_POST['id'] ?? ($json['id'] ?? 0));
    $q=$conn->query("SELECT rules_json FROM audience WHERE id=$id AND account_id=$account_id LIMIT 1");
    if(!$q||!$q->num_rows) jsonResponse(false,'Audience not found');
    $rules=crm_decode_rules($q->fetch_assoc()['rules_json'] ?? '');
    $matched=crm_get_customers_by_rules($conn,$account_id,$rules,10000,0);
    $new=0; $ids=[];
    while($matched && $c=$matched->fetch_assoc()){
        $cid=(int)$c['id'];
        $ex=$conn->query("SELECT id FROM audience_customers WHERE audience_id=$id AND customer_id=$cid LIMIT 1");
        if(!$ex || !$ex->num_rows){ $new++; $ids[]=$cid; }
    }
    if($action==='preview_update') jsonResponse(true,'',['new_count'=>$new]);
    $added=0;
    foreach($ids as $cid){
        if($conn->query("INSERT INTO audience_customers (audience_id,customer_id,date_created,created_at,updated_at) VALUES ($id,$cid,NOW(),NOW(),NOW())")) $added++;
    }
    jsonResponse(true,'Audience updated',['added'=>$added]);
}

if ($action === 'refresh') {
    requirePermission($conn,'audience','edit');
    $id=(int)($_POST['id'] ?? ($json['id'] ?? 0));
    $q=$conn->query("SELECT rules_json FROM audience WHERE id=$id AND account_id=$account_id LIMIT 1");
    if(!$q||!$q->num_rows) jsonResponse(false,'Audience not found');
    $rules=crm_decode_rules($q->fetch_assoc()['rules_json'] ?? '');
    $count=crm_refresh_audience_customers($conn,$account_id,$id,$rules);
    jsonResponse(true,'Audience refreshed',['count'=>$count]);
}

if ($action === 'delete') {
    requirePermission($conn,'audience','delete');
    $id=(int)($_POST['id'] ?? ($json['id'] ?? 0));
    $conn->query("DELETE ac FROM audience_customers ac INNER JOIN audience a ON a.id=ac.audience_id WHERE ac.audience_id=$id AND a.account_id=$account_id");
    $conn->query("DELETE FROM audience WHERE id=$id AND account_id=$account_id");
    jsonResponse(true,'Audience deleted');
}

jsonResponse(false,'Invalid action');
?>
