<?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 campaign_rules_for_request($conn,$account_id){
  $target=$_POST['target_type']??'audience';
  if($target==='audience'){
    $aid=(int)($_POST['audience_id']??0);
    if(!$aid)return [];
    $q=$conn->query("SELECT rules_json FROM audience WHERE id=$aid AND account_id=$account_id LIMIT 1");
    return ($q&&$q->num_rows)?crm_decode_rules($q->fetch_assoc()['rules_json']??''):[];
  }
  return crm_rules_from_request();
}
function preview_html($res){$html='<div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Customer</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['phone']?:'—').'</td><td>'.htmlspecialchars($r['email']?:'—').'</td></tr>';} if(!$i)$html.='<tr><td colspan="3" class="text-center text-muted">No recipients</td></tr>'; return $html.'</tbody></table></div></div>';}
if($action==='preview'){requirePermission($conn,'campaigns','view');$rules=campaign_rules_for_request($conn,$account_id);$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'=>preview_html($rows)]);} 
if($action==='save'){ $id=(int)($_POST['id']??0);requirePermission($conn,'campaigns',$id?'edit':'add');$name=sanitize($conn,$_POST['name']??'');if(!$name)jsonResponse(false,'Campaign name required');$description=sanitize($conn,$_POST['description']??'');$status=(int)($_POST['status']??1);$tw=!empty($_POST['type_whatsapp'])?1:0;$te=!empty($_POST['type_email'])?1:0;$ts=!empty($_POST['type_sms'])?1:0;if(!$tw&&!$te&&!$ts)jsonResponse(false,'Choose at least one campaign type');$target=sanitize($conn,$_POST['target_type']??'audience');$audience_id=(int)($_POST['audience_id']??0);$rules=($target==='dynamic')?crm_rules_from_request():campaign_rules_for_request($conn,$account_id);$rules_json=sanitize($conn,json_encode($rules,JSON_UNESCAPED_UNICODE));$mw=sanitize($conn,$_POST['message_whatsapp']??'');$me=sanitize($conn,$_POST['message_email']??'');$ms=sanitize($conn,$_POST['message_sms']??'');$sub=sanitize($conn,$_POST['email_subject']??''); if($id){$conn->query("UPDATE campaign SET name='$name',description='$description',status=$status,type_whatsapp=$tw,type_email=$te,type_sms=$ts,target_type='$target',audience_id=$audience_id,rules_json='$rules_json',message_whatsapp='$mw',message_email='$me',message_sms='$ms',email_subject='$sub' WHERE id=$id AND account_id=$account_id");}else{$conn->query("INSERT INTO campaign (name,description,status,account_id,added_by,type_whatsapp,type_email,type_sms,target_type,audience_id,rules_json,message_whatsapp,message_email,message_sms,email_subject,date_created) VALUES ('$name','$description',$status,$account_id,$user_id,$tw,$te,$ts,'$target',$audience_id,'$rules_json','$mw','$me','$ms','$sub',NOW())");$id=$conn->insert_id;} jsonResponse(true,'Campaign saved',['id'=>$id]);}
if($action==='send'){requirePermission($conn,'campaigns','edit');$id=(int)($_POST['id']??($json['id']??0));$q=$conn->query("SELECT * FROM campaign WHERE id=$id AND account_id=$account_id LIMIT 1");if(!$q||!$q->num_rows)jsonResponse(false,'Campaign not found');$camp=$q->fetch_assoc();$rules=crm_decode_rules($camp['rules_json']??'');$rows=crm_get_customers_by_rules($conn,$account_id,$rules,10000,0);$sent=0;while($rows&&$c=$rows->fetch_assoc()){foreach(['whatsapp'=>'type_whatsapp','email'=>'type_email','sms'=>'type_sms'] as $type=>$col){if(!empty($camp[$col])){$cid=(int)$c['id'];$conn->query("INSERT INTO campaign_logs (campaign_id,customer_id,type,status,response,sent_at) VALUES ($id,$cid,'$type','pending','Ready to send from campaign page',NOW())");$sent++;}}}jsonResponse(true,'Campaign prepared',['sent'=>$sent]);}
if($action==='delete'){requirePermission($conn,'campaigns','delete');$id=(int)($_POST['id']??($json['id']??0));$conn->query("DELETE FROM campaign WHERE id=$id AND account_id=$account_id");jsonResponse(true,'Campaign deleted');}
jsonResponse(false,'Invalid action');
?>
