<?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 email campaign statistics
    $stats = [];
    
    // Total campaigns
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM email_campaigns");
    $stmt->execute();
    $stats['total'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Total emails sent
    $stmt = $pdo->prepare("SELECT COUNT(*) as sent FROM email_logs WHERE status = 'sent'");
    $stmt->execute();
    $stats['sent'] = $stmt->fetch(PDO::FETCH_ASSOC)['sent'];
    
    // Calculate open rate
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_sent,
            SUM(CASE WHEN opened = 1 THEN 1 ELSE 0 END) as total_opened
        FROM email_logs 
        WHERE status = 'sent'
    ");
    $stmt->execute();
    $openData = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats['open_rate'] = $openData['total_sent'] > 0 ? 
        round(($openData['total_opened'] / $openData['total_sent']) * 100, 1) : 0;
    
    // Calculate click rate
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_sent,
            SUM(CASE WHEN clicked = 1 THEN 1 ELSE 0 END) as total_clicked
        FROM email_logs 
        WHERE status = 'sent'
    ");
    $stmt->execute();
    $clickData = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats['click_rate'] = $clickData['total_sent'] > 0 ? 
        round(($clickData['total_clicked'] / $clickData['total_sent']) * 100, 1) : 0;
    
    // Recent campaigns (last 30 days)
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as recent 
        FROM email_campaigns 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stmt->execute();
    $stats['recent'] = $stmt->fetch(PDO::FETCH_ASSOC)['recent'];
    
    // Failed emails
    $stmt = $pdo->prepare("SELECT COUNT(*) as failed FROM email_logs WHERE status = 'failed'");
    $stmt->execute();
    $stats['failed'] = $stmt->fetch(PDO::FETCH_ASSOC)['failed'];
    
    // Campaigns by status
    $stmt = $pdo->prepare("
        SELECT status, COUNT(*) as count 
        FROM email_campaigns 
        GROUP BY status
    ");
    $stmt->execute();
    $statusData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['by_status'] = [];
    foreach ($statusData as $status) {
        $stats['by_status'][$status['status']] = $status['count'];
    }
    
    // Campaigns by type
    $stmt = $pdo->prepare("
        SELECT type, COUNT(*) as count 
        FROM email_campaigns 
        GROUP BY type
    ");
    $stmt->execute();
    $typeData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['by_type'] = [];
    foreach ($typeData as $type) {
        $stats['by_type'][$type['type']] = $type['count'];
    }
    
    // Monthly email volume (last 12 months)
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(sent_at, '%Y-%m') as month,
            COUNT(*) as count
        FROM email_logs 
        WHERE sent_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
        AND status = 'sent'
        GROUP BY DATE_FORMAT(sent_at, '%Y-%m')
        ORDER BY month ASC
    ");
    $stmt->execute();
    $monthlyData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['monthly_volume'] = $monthlyData;
    
    // Top performing campaigns
    $stmt = $pdo->prepare("
        SELECT 
            ec.name,
            ec.subject,
            COUNT(el.id) as sent_count,
            SUM(CASE WHEN el.opened = 1 THEN 1 ELSE 0 END) as open_count,
            SUM(CASE WHEN el.clicked = 1 THEN 1 ELSE 0 END) as click_count
        FROM email_campaigns ec
        LEFT JOIN email_logs el ON ec.id = el.campaign_id AND el.status = 'sent'
        WHERE ec.status = 'sent'
        AND ec.sent_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY ec.id
        HAVING sent_count > 0
        ORDER BY (open_count / sent_count) DESC
        LIMIT 5
    ");
    $stmt->execute();
    $topCampaigns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats['top_campaigns'] = $topCampaigns;
    
    echo json_encode([
        'success' => true,
        'stats' => $stats
    ]);
    
} catch (Exception $e) {
    error_log("Email Campaign Stats Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching statistics: ' . $e->getMessage()
    ]);
}
?>
