<?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();
}

try {
    // Get filters and pagination
    $page = (int)($_GET['page'] ?? 1);
    $limit = (int)($_GET['limit'] ?? 25);
    $offset = ($page - 1) * $limit;
    $status = $_GET['status'] ?? '';
    $type = $_GET['type'] ?? '';
    
    // Build query
    $query = "SELECT 
                ec.*,
                a.username as created_by_name,
                (SELECT COUNT(*) FROM email_campaign_recipients ecr WHERE ecr.campaign_id = ec.id) as recipient_count,
                (SELECT COUNT(*) FROM email_logs el WHERE el.campaign_id = ec.id AND el.status = 'sent') as sent_count,
                (SELECT COUNT(*) FROM email_logs el WHERE el.campaign_id = ec.id AND el.opened = 1) as open_count,
                (SELECT COUNT(*) FROM email_logs el WHERE el.campaign_id = ec.id AND el.clicked = 1) as click_count
              FROM email_campaigns ec
              LEFT JOIN admins a ON ec.created_by = a.id
              WHERE 1=1";
    
    $params = [];
    
    // Apply filters
    if (!empty($status)) {
        $query .= " AND ec.status = ?";
        $params[] = $status;
    }
    
    if (!empty($type)) {
        $query .= " AND ec.type = ?";
        $params[] = $type;
    }
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM ($query) as countQuery";
    $countStmt = $pdo->prepare($countQuery);
    $countStmt->execute($params);
    $totalRecords = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Add pagination
    $query .= " ORDER BY ec.created_at DESC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;
    
    // Execute main query
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $campaigns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process campaigns data
    $processedCampaigns = [];
    foreach ($campaigns as $campaign) {
        $openRate = $campaign['sent_count'] > 0 ? 
            round(($campaign['open_count'] / $campaign['sent_count']) * 100, 1) : 0;
        $clickRate = $campaign['sent_count'] > 0 ? 
            round(($campaign['click_count'] / $campaign['sent_count']) * 100, 1) : 0;
        
        $processedCampaigns[] = [
            'id' => $campaign['id'],
            'name' => $campaign['name'],
            'subject' => $campaign['subject'],
            'type' => $campaign['type'],
            'status' => $campaign['status'],
            'recipient_count' => $campaign['recipient_count'],
            'sent_count' => $campaign['sent_count'],
            'open_count' => $campaign['open_count'],
            'click_count' => $campaign['click_count'],
            'open_rate' => $openRate,
            'click_rate' => $clickRate,
            'scheduled_at' => $campaign['scheduled_at'],
            'sent_at' => $campaign['sent_at'],
            'created_at' => $campaign['created_at'],
            'created_by' => $campaign['created_by_name']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'campaigns' => $processedCampaigns,
        'pagination' => [
            'current_page' => $page,
            'per_page' => $limit,
            'total' => $totalRecords,
            'pages' => ceil($totalRecords / $limit)
        ]
    ]);
    
} catch (Exception $e) {
    error_log("Email Campaigns Fetch Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching campaigns: ' . $e->getMessage()
    ]);
}
?>
