<?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';
$autoload = __DIR__ . '/mailer/vendor/autoload.php';
if (file_exists($autoload)) require_once $autoload;
$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>';}
function camp_log_comm($customer_id,$type,$to,$subject,$message,$result){global $conn;$status=!empty($result['success'])?'sent':'failed';$response=$conn->real_escape_string($result['message']??($result['response']??''));$typeId=$type==='email'?1:($type==='sms'?2:3);$sender=$type==='email'?'Email CRM':($type==='sms'?'Amctag':'WhatsApp CRM');$sender=$conn->real_escape_string($sender);$subject=$conn->real_escape_string($subject);$message=$conn->real_escape_string($message);$to=$conn->real_escape_string($to);$account_id=(int)$_SESSION['account_id'];$user_id=(int)$_SESSION['user_id'];$conn->query("INSERT INTO communications (account_id,user_id,customer_id,message_type_id,recipient,sender,subject,message,status,response,date_created) VALUES ($account_id,$user_id,$customer_id,$typeId,'$to','$sender','$subject','$message','$status','$response',NOW())");}
function camp_log_campaign($campaign_id,$customer_id,$type,$result){global $conn;$status=!empty($result['success'])?'sent':'failed';$resp=$conn->real_escape_string($result['message']??($result['response']??''));$conn->query("INSERT INTO campaign_logs (campaign_id,customer_id,type,status,response,sent_at) VALUES ($campaign_id,$customer_id,'$type','$status','$resp',NOW())");}
function camp_send_sms($phone,$message){$phone=preg_replace('/[^0-9]/','',$phone); if(!$phone)return ['success'=>false,'message'=>'Missing phone']; $url='https://sms.unosms.net/api.php?user='.urlencode('abed_mahfouz@hotmail.com').'&pass='.urlencode('uwscqq').'&to='.urlencode($phone).'&from=Amctag&msg='.urlencode($message); $ch=curl_init($url); curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>20,CURLOPT_SSL_VERIFYPEER=>false]); $resp=curl_exec($ch); $err=curl_error($ch); $code=curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); return (!$err&&$code<400)?['success'=>true,'message'=>'SMS sent','response'=>$resp]:['success'=>false,'message'=>$err?:'SMS failed','response'=>$resp];}
function camp_send_email($to,$subject,$message){if(!$to)return ['success'=>false,'message'=>'Missing email']; if(!class_exists('PHPMailer\\PHPMailer\\PHPMailer'))return ['success'=>false,'message'=>'Mailer library not found']; $mail=new PHPMailer\PHPMailer\PHPMailer(true); try{$mail->isSMTP();$mail->Host='smtp.gmail.com';$mail->SMTPAuth=true;$from='monzermahfouz54321m@gmail.com';$account_id=(int)$_SESSION['account_id'];global $conn;if(tableExists($conn,'accounts_email')){$em=$conn->query("SELECT email FROM accounts_email WHERE account_id=$account_id ORDER BY is_default DESC,id DESC LIMIT 1");if($em&&$em->num_rows)$from=$em->fetch_assoc()['email'];}$mail->Username='monzermahfouz54321m@gmail.com';$mail->Password='qxsx gwuz eies yiqi';$mail->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;$mail->Port=587;$mail->setFrom($from,'CRM System');$mail->addAddress($to);$mail->isHTML(true);$mail->Subject=$subject;$mail->Body=nl2br($message);$mail->AltBody=strip_tags($message);$mail->send();return ['success'=>true,'message'=>'Email sent'];}catch(Throwable $e){return ['success'=>false,'message'=>$mail->ErrorInfo?:$e->getMessage()];}}
function camp_send_whatsapp($phone,$message){global $conn;$account_id=(int)$_SESSION['account_id'];$r=$conn->query("SELECT client_id FROM contact_phone WHERE account_id=$account_id LIMIT 1");if(!$r||!$r->num_rows)return ['success'=>false,'message'=>'WhatsApp client not found'];$clientId=$r->fetch_assoc()['client_id'];$phone=preg_replace('/[^0-9]/','',$phone);if(substr($phone,0,1)==='0')$phone=substr($phone,1);if(substr($phone,0,3)!=='961')$phone='961'.$phone;$nodeUrl='https://amctag-whats.38f0fz.easypanel.host';$token='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI3MzFiMTlhNDdlZDg2MjUxZDg2YjYyYTYiLCJ0eXBlIjoidXNlciIsImlhdCI6MTc3OTE3NzE1Nn0.NaszEOLCnWT59oXBCdi7WKwXT-QbZWpFF3G_64fsTDs';$ch=curl_init($nodeUrl.'/api/campaigns');curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(['name'=>'crm_campaign_'.time().'_'.mt_rand(1000,9999),'message'=>$message,'clientId'=>$clientId]),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$token],CURLOPT_TIMEOUT=>30,CURLOPT_SSL_VERIFYPEER=>false]);$create=curl_exec($ch);$code=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);if($code!==200&&$code!==201)return ['success'=>false,'message'=>'WhatsApp campaign create failed','response'=>$create];$data=json_decode($create,true);$cid=$data['campaign']['_id']??$data['campaign']['id']??null;if(!$cid)return ['success'=>false,'message'=>'No WhatsApp campaign ID returned'];$ch=curl_init($nodeUrl."/api/contacts/$cid/add");curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(['phone'=>$phone,'name'=>'Customer']),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$token],CURLOPT_TIMEOUT=>30,CURLOPT_SSL_VERIFYPEER=>false]);$add=curl_exec($ch);$code=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);if($code!==200&&$code!==201)return ['success'=>false,'message'=>'WhatsApp contact add failed','response'=>$add];$ch=curl_init($nodeUrl."/api/campaigns/$cid/start");curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode([]),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$token],CURLOPT_TIMEOUT=>30,CURLOPT_SSL_VERIFYPEER=>false]);$start=curl_exec($ch);$code=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);return ($code===200||$code===201)?['success'=>true,'message'=>'WhatsApp sent','campaignId'=>$cid]:['success'=>false,'message'=>'WhatsApp start failed','response'=>$start];}
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;$failed=0;while($rows&&$c=$rows->fetch_assoc()){foreach(['whatsapp'=>'type_whatsapp','email'=>'type_email','sms'=>'type_sms'] as $type=>$col){if(empty($camp[$col]))continue;$msg=$type==='whatsapp'?$camp['message_whatsapp']:($type==='email'?$camp['message_email']:$camp['message_sms']);$subject=$type==='email'?($camp['email_subject']?:$camp['name']):'';$to=$type==='email'?$c['email']:$c['phone'];$res=$type==='whatsapp'?camp_send_whatsapp($to,$msg):($type==='email'?camp_send_email($to,$subject,$msg):camp_send_sms($to,$msg));camp_log_comm((int)$c['id'],$type,$to,$subject,$msg,$res);camp_log_campaign($id,(int)$c['id'],$type,$res);!empty($res['success'])?$sent++:$failed++;}}jsonResponse(true,'Campaign sending completed',['sent'=>$sent,'failed'=>$failed]);}
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');
?>
