<?php
session_start();

// Check authentication
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'] ?? '');

// ============================================
// Helper Functions
// ============================================

/**
 * Get campaign rules from request
 */
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");
        
        if ($q && $q->num_rows) {
            return crm_decode_rules($q->fetch_assoc()['rules_json'] ?? '');
        }
        
        return [];
    }
    
    return crm_rules_from_request();
}

/**
 * Generate preview HTML for recipients
 */
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>';
}

/**
 * Log communication to database
 */
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()
    )");
}

/**
 * Log campaign sending to database
 */
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()
    )");
}

/**
 * Send SMS via API
 */
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);
    
    if (!$err && $code < 400) {
        return ['success' => true, 'message' => 'SMS sent', 'response' => $resp];
    }
    
    return ['success' => false, 'message' => $err ?: 'SMS failed', 'response' => $resp];
}

/**
 * Send Email via PHPMailer (Gmail SMTP)
 */
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';
        
        // Check for custom account email
        $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()];
    }
}

/**
 * Send WhatsApp message via external API
 */
function camp_send_whatsapp($phone, $message)
{
    global $conn;
    $account_id = (int) $_SESSION['account_id'];
    
    // Get client 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'];
    
    // Format phone number
    $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';
    
            $token    = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJmN2M5YTFhMjU1OWRiMWIzYzNhZTQzZWQiLCJ0eXBlIjoidXNlciIsImlhdCI6MTc4MDU3MjY2MX0.4t7g1F4e4k5b0Tu1vjQQu-8Sh2EuT8dR45jR5mimHFs';
    
    // Create campaign
    $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'];
    }
    
    // Add contact
    $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];
    }
    
    // Start campaign
    $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);
    
    if ($code === 200 || $code === 201) {
        return ['success' => true, 'message' => 'WhatsApp sent', 'campaignId' => $cid];
    }
    
    return ['success' => false, 'message' => 'WhatsApp start failed', 'response' => $start];
}

// ============================================
// API Actions
// ============================================

/**
 * Action: preview - Show recipients preview
 */
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)
    ]);
}

/**
 * Action: save - Save campaign (create or update)
 */
if ($action === 'save') {
    $id = (int) ($_POST['id'] ?? 0);
    requirePermission($conn, 'campaigns', $id ? 'edit' : 'add');
    
    // Validate campaign name
    $name = sanitize($conn, $_POST['name'] ?? '');
    if (!$name) {
        jsonResponse(false, 'Campaign name required');
    }
    
    // Sanitize inputs
    $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;
    
    // Validate at least one type selected
    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);
    
    // Build rules
    $rules = ($target === 'dynamic') 
        ? crm_rules_from_request() 
        : campaign_rules_for_request($conn, $account_id);
    
    $rules_json = sanitize($conn, json_encode($rules, JSON_UNESCAPED_UNICODE));
    
    // Message content
    $mw = sanitize($conn, $_POST['message_whatsapp'] ?? '');
    $me = sanitize($conn, $_POST['message_email'] ?? '');
    $ms = sanitize($conn, $_POST['message_sms'] ?? '');
    $sub = sanitize($conn, $_POST['email_subject'] ?? '');
    
    // Update or Insert
    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]);
}

/**
 * Action: send - Execute campaign sending
 */
if ($action === 'send') {
    requirePermission($conn, 'campaigns', 'edit');
    
    $id = (int) ($_POST['id'] ?? ($json['id'] ?? 0));
    
    // Get campaign data
    $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()) {
        $types = [
            'whatsapp' => 'type_whatsapp',
            'email' => 'type_email',
            'sms' => 'type_sms'
        ];
        
        foreach ($types as $type => $col) {
            if (empty($camp[$col])) {
                continue;
            }
            
            // Get message content
            $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'];
            
            // Send message
            $res = match($type) {
                'whatsapp' => camp_send_whatsapp($to, $msg),
                'email' => camp_send_email($to, $subject, $msg),
                'sms' => camp_send_sms($to, $msg),
                default => ['success' => false, 'message' => 'Unknown type']
            };
            
            // Log results
            camp_log_comm((int) $c['id'], $type, $to, $subject, $msg, $res);
            camp_log_campaign($id, (int) $c['id'], $type, $res);
            
            if (!empty($res['success'])) {
                $sent++;
            } else {
                $failed++;
            }
        }
    }
    
    jsonResponse(true, 'Campaign sending completed', [
        'sent' => $sent,
        'failed' => $failed
    ]);
}

/**
 * Action: delete - Delete campaign
 */
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');
}

// If no action matched
jsonResponse(false, 'Invalid action');
?>