<?php
require_once '../../config.php';
require_once '../../auth/check_auth.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    // Get campaign data
    $name = $_POST['name'] ?? '';
    $type = $_POST['type'] ?? 'newsletter';
    $description = $_POST['description'] ?? '';
    $subject = $_POST['subject'] ?? '';
    $content = $_POST['content'] ?? '';
    $recipients = $_POST['recipients'] ?? [];
    $schedule_type = $_POST['schedule_type'] ?? 'now';
    $schedule_date = $_POST['schedule_date'] ?? null;
    $schedule_time = $_POST['schedule_time'] ?? null;
    
    // Validate required fields
    if (empty($name) || empty($subject) || empty($content) || empty($recipients)) {
        echo json_encode(['success' => false, 'message' => 'Required fields are missing']);
        exit();
    }
    
    // Prepare scheduled datetime
    $scheduled_at = null;
    if ($schedule_type === 'later' && $schedule_date && $schedule_time) {
        $scheduled_at = $schedule_date . ' ' . $schedule_time . ':00';
    }
    
    // Create campaign
    $stmt = $pdo->prepare("
        INSERT INTO email_campaigns (
            name, type, description, subject, content, status, 
            scheduled_at, created_by, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $status = ($schedule_type === 'now') ? 'sending' : 'scheduled';
    
    $stmt->execute([
        $name, $type, $description, $subject, $content, $status,
        $scheduled_at, $_SESSION['admin_id']
    ]);
    
    $campaign_id = $pdo->lastInsertId();
    
    // Get recipients list
    $recipients_list = [];
    foreach ($recipients as $recipient_type) {
        $recipients_query = getRecipientsQuery($recipient_type);
        if ($recipients_query) {
            $stmt = $pdo->prepare($recipients_query);
            $stmt->execute();
            $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $recipients_list = array_merge($recipients_list, $members);
        }
    }
    
    // Remove duplicates
    $unique_recipients = [];
    $seen_emails = [];
    foreach ($recipients_list as $recipient) {
        if (!in_array($recipient['email'], $seen_emails)) {
            $unique_recipients[] = $recipient;
            $seen_emails[] = $recipient['email'];
        }
    }
    
    // Store campaign recipients
    foreach ($unique_recipients as $recipient) {
        $stmt = $pdo->prepare("
            INSERT INTO email_campaign_recipients (campaign_id, member_id, email, name)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([
            $campaign_id,
            $recipient['id'],
            $recipient['email'],
            $recipient['name']
        ]);
    }
    
    if ($schedule_type === 'now') {
        // Send immediately
        $sent_count = sendCampaignEmails($campaign_id, $unique_recipients, $subject, $content);
        
        // Update campaign status
        $stmt = $pdo->prepare("
            UPDATE email_campaigns 
            SET status = 'sent', sent_at = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$campaign_id]);
        
        $message = "Campaign sent successfully to {$sent_count} recipients";
    } else {
        $message = "Campaign scheduled successfully for {$scheduled_at}";
    }
    
    // Log activity
    logActivity(
        $_SESSION['admin_id'],
        'email_campaign_created',
        "Created email campaign: {$name}",
        ['campaign_id' => $campaign_id, 'recipients' => count($unique_recipients)]
    );
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'campaign_id' => $campaign_id,
        'recipients_count' => count($unique_recipients)
    ]);
    
} catch (Exception $e) {
    error_log("Email Campaign Send Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error sending campaign: ' . $e->getMessage()
    ]);
}

function getRecipientsQuery($type) {
    switch ($type) {
        case 'all':
            return "SELECT id, CONCAT(first_name, ' ', last_name) as name, email FROM members WHERE status = 'active' AND email IS NOT NULL AND email != ''";
        case 'individual':
            return "SELECT id, CONCAT(first_name, ' ', last_name) as name, email FROM members WHERE status = 'active' AND membership_type = 'individual' AND email IS NOT NULL AND email != ''";
        case 'family':
            return "SELECT id, CONCAT(first_name, ' ', last_name) as name, email FROM members WHERE status = 'active' AND membership_type = 'family' AND email IS NOT NULL AND email != ''";
        case 'expiring':
            return "SELECT id, CONCAT(first_name, ' ', last_name) as name, email FROM members WHERE status = 'active' AND membership_expiry BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) AND email IS NOT NULL AND email != ''";
        default:
            return null;
    }
}

function sendCampaignEmails($campaign_id, $recipients, $subject, $content) {
    global $pdo;
    
    $sent_count = 0;
    
    foreach ($recipients as $recipient) {
        try {
            // Process template variables
            $processed_content = processTemplateVariables($content, $recipient);
            $processed_subject = processTemplateVariables($subject, $recipient);
            
            // Send email (using PHP mail function - in production, use a proper email service)
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: KSO Chandigarh <noreply@ksochandigarh.org>" . "\r\n";
            
            $email_sent = mail($recipient['email'], $processed_subject, $processed_content, $headers);
            
            // Log email attempt
            $stmt = $pdo->prepare("
                INSERT INTO email_logs (
                    campaign_id, member_id, email, subject, content, 
                    status, sent_at, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            
            $status = $email_sent ? 'sent' : 'failed';
            $stmt->execute([
                $campaign_id,
                $recipient['id'],
                $recipient['email'],
                $processed_subject,
                $processed_content,
                $status
            ]);
            
            if ($email_sent) {
                $sent_count++;
            }
            
        } catch (Exception $e) {
            error_log("Email send error for {$recipient['email']}: " . $e->getMessage());
            
            // Log failed email
            $stmt = $pdo->prepare("
                INSERT INTO email_logs (
                    campaign_id, member_id, email, subject, content, 
                    status, error_message, created_at
                ) VALUES (?, ?, ?, ?, ?, 'failed', ?, NOW())
            ");
            
            $stmt->execute([
                $campaign_id,
                $recipient['id'],
                $recipient['email'],
                $subject,
                $content,
                $e->getMessage()
            ]);
        }
    }
    
    return $sent_count;
}

function processTemplateVariables($content, $recipient) {
    $variables = [
        '{{member_name}}' => $recipient['name'],
        '{{member_id}}' => $recipient['id'],
        '{{organization}}' => 'Kashmiri Students Organization Chandigarh',
        '{{current_date}}' => date('F j, Y'),
        '{{membership_status}}' => 'Active',
        '{{expiry_date}}' => date('F j, Y', strtotime('+1 year'))
    ];
    
    return str_replace(array_keys($variables), array_values($variables), $content);
}

function logActivity($admin_id, $action, $description, $details = []) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO activity_logs (admin_id, action, description, details, created_at)
            VALUES (?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $admin_id,
            $action,
            $description,
            json_encode($details)
        ]);
    } catch (Exception $e) {
        error_log("Activity Log Error: " . $e->getMessage());
    }
}
?>
