<?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, $CURRENT_CAMPAIGN_ID;
    
    $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'];
    $cid = (int)($CURRENT_CAMPAIGN_ID ?? 0);
    if (columnExists($conn,'communications','campaign_id')) {
        $conn->query("INSERT INTO communications (account_id, user_id, customer_id, campaign_id, source_type, message_type_id, recipient, sender, subject, message, status, response, date_created) VALUES ($account_id, $user_id, $customer_id, $cid, 'campaign', $typeId, '$to', '$sender', '$subject', '$message', '$status', '$response', NOW())");
    } else {
        $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 = $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_app_base_url(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') == 443);
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
    $rootDir = preg_replace('#/handlers$#', '', $scriptDir);
    return $scheme . '://' . $host . rtrim($rootDir, '/');
}

function camp_handle_media_upload($existing = '') {
    if (!isset($_FILES['media']) || empty($_FILES['media']['name'])) {
        return $existing;
    }
    if ($_FILES['media']['error'] !== UPLOAD_ERR_OK) {
        jsonResponse(false, 'Image upload failed');
    }
    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($_FILES['media']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt)) {
        jsonResponse(false, 'Invalid image type. Allowed: JPG, PNG, GIF, WEBP');
    }
    if ($_FILES['media']['size'] > 5 * 1024 * 1024) {
        jsonResponse(false, 'Image is too large. Max 5MB');
    }
    $uploadDir = getUserUploadPath();
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $userId = intval($_SESSION['user_id'] ?? 0);
    $fileName = 'campaign_' . $userId . '_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
    $target = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . $fileName;
    if (!move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
        jsonResponse(false, 'Could not save uploaded image');
    }
    return camp_app_base_url() . '/uploads/user_' . $userId . '/' . rawurlencode($fileName);
}

/**
 * Send WhatsApp message via external API
 */
function camp_send_whatsapp($phone, $message, $mediaUrl = '')
{
    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 = CRM_WHATSAPP_NODE_URL;
    $token = CRM_WHATSAPP_TOKEN;
    
    // Create campaign
    $ch = curl_init($nodeUrl . '/api/campaigns');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(array_filter([
            'name' => 'crm_campaign_' . time() . '_' . mt_rand(1000, 9999),
            'message' => $message,
            'clientId' => $clientId,
            'mediaUrl' => $mediaUrl ?: null,
            'mediaType' => $mediaUrl ? 'image' : null,
        ], function($value) { return $value !== null && $value !== ''; })),
        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);
    
    // Campaign must have a real audience before saving.
    if ($target === 'audience' && $audience_id <= 0) {
        jsonResponse(false, 'Select an audience before saving campaign');
    }
    if ($target === 'dynamic') {
        $hasRule = false;
        foreach ($rules as $rk => $rv) {
            if (is_array($rv) && count($rv)) { $hasRule = true; break; }
            if (!is_array($rv) && $rv !== '' && $rv !== null) { $hasRule = true; break; }
        }
        if (!$hasRule) jsonResponse(false, 'Choose at least one dynamic filter/customer before saving campaign');
    }
    $cntRowsPre = crm_get_customers_by_rules($conn, $account_id, $rules, 1, 0);
    $customer_count_pre = crm_count_customers_by_rules($conn, $account_id, $rules);
    if ($customer_count_pre <= 0) {
        jsonResponse(false, 'This campaign has no customers. Create/select an audience with customers first.');
    }

    $rules_json = sanitize($conn, json_encode($rules, JSON_UNESCAPED_UNICODE));
    
    // Message content
    $mw = sanitize($conn, $_POST['message_whatsapp'] ?? '');
    $me = $conn->real_escape_string($_POST['message_email'] ?? '');
    $ms = sanitize($conn, $_POST['message_sms'] ?? '');
    $sub = sanitize($conn, $_POST['email_subject'] ?? '');
    $existing_media = '';
    if ($id && columnExists($conn, 'campaign', 'media_url')) {
        $mq = $conn->query("SELECT media_url FROM campaign WHERE id=$id AND account_id=$account_id LIMIT 1");
        if ($mq && $mq->num_rows) $existing_media = $mq->fetch_assoc()['media_url'] ?? '';
    }
    $media_url_raw = camp_handle_media_upload($existing_media);
    $media_url = sanitize($conn, $media_url_raw);
    $mediaSqlUpdate = columnExists($conn, 'campaign', 'media_url') ? ", media_url = '$media_url', media_type = 'image'" : '';
    
    // 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'
            $mediaSqlUpdate
            WHERE id = $id AND account_id = $account_id");
    } else {
        if (columnExists($conn, 'campaign', 'media_url')) {
            $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, media_url, media_type, date_created
            ) VALUES (
                '$name', '$description', $status, $account_id, $user_id,
                $tw, $te, $ts,
                '$target', $audience_id, '$rules_json',
                '$mw', '$me', '$ms', '$sub', '$media_url', 'image', NOW()
            )");
        } 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;
    }
    
    if ($target === 'audience' && $audience_id > 0 && tableExists($conn,'audience_customers')) {
        $cntQ=$conn->query("SELECT COUNT(*) cnt FROM audience_customers ac INNER JOIN customers c ON c.id=ac.customer_id WHERE ac.audience_id=$audience_id AND c.account_id=$account_id");
        $customer_count=$cntQ?(int)$cntQ->fetch_assoc()['cnt']:0;
    } else {
        $cntRows = crm_get_customers_by_rules($conn, $account_id, crm_decode_rules($rules_json), 10000, 0);
        $customer_count = $cntRows ? (int)$cntRows->num_rows : 0;
    }
    if (columnExists($conn,'campaign','customer_count')) $conn->query("UPDATE campaign SET customer_count=$customer_count WHERE id=$id AND account_id=$account_id");
    jsonResponse(true, 'Campaign saved', ['id' => $id, 'customer_count'=>$customer_count]);
}

/**
 * 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();
    if (columnExists($conn,'campaign','is_sent') && (int)($camp['is_sent'] ?? 0)===1) jsonResponse(false,'This campaign was already sent');
    $rules = crm_decode_rules($camp['rules_json'] ?? '');
    $rows = crm_get_customers_by_rules($conn, $account_id, $rules, 10000, 0);
    
    $sent = 0;
    $failed = 0;
    $CURRENT_CAMPAIGN_ID = $id;
    
    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, $camp['media_url'] ?? ''),
                '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++;
            }
        }
    }
    
    if (columnExists($conn,'campaign','is_sent')) $conn->query("UPDATE campaign SET is_sent=1, sent_at=NOW(), sent_by=$user_id WHERE id=$id AND account_id=$account_id");
    if (columnExists($conn,'campaign','customer_count')) $conn->query("UPDATE campaign SET customer_count=$sent+$failed WHERE id=$id AND account_id=$account_id");
    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');
?>