<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'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):[];
$action=$_POST['action'] ?? ($json['action'] ?? '');

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=(int)($_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);
    jsonResponse(true,'Audience saved',['id'=>$id,'count'=>$count]);
}

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');
?>
