<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Grant Admin Unrestricted Privileges: Allow admin to view anyone's analytics
$userId = $user['id'];
if (isAdmin($user['id']) && isset($_GET['userId'])) {
    $userId = $_GET['userId'];
}

// Only active users can see analytics (optional, maybe check subscription)
// if (!$user['active_subscription']) { ... }

try {
    // 1. Total Mails Sent
    $stmt = $pdo->prepare("SELECT mails_sent FROM user_progress WHERE user_id = ?");
    $stmt->execute([$user['id']]);
    $progress = $stmt->fetch();
    $totalMails = $progress ? $progress['mails_sent'] : 0;
    
    if (!$progress) {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM mail_activity WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        $totalMails = $stmt->fetch()['count'];
    }

    // 2. Real Revenue Calculation (from paid orders)
    $stmt = $pdo->prepare("SELECT SUM(total_amount) as total FROM orders WHERE user_id = ? AND payment_status = 'paid'");
    $stmt->execute([$user['id']]);
    $revenue = (float)($stmt->fetch()['total'] ?? 0);

    // 3. Active Clients (Users who sent mail in last 30 days)
    $stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT recipient_email) as count 
        FROM mail_activity 
        WHERE user_id = ? AND created_at >= datetime('now', '-30 days')
    ");
    $stmt->execute([$user['id']]);
    $activeClients = (int)($stmt->fetch()['count'] ?? 0);

    // 4. Growth Calculations (Comparing last 30 days with 30-60 days ago)
    // Revenue Growth
    $stmt = $pdo->prepare("SELECT SUM(total_amount) as total FROM orders WHERE user_id = ? AND payment_status = 'paid' AND created_at >= datetime('now', '-30 days')");
    $stmt->execute([$user['id']]);
    $revCurrent = (float)($stmt->fetch()['total'] ?? 0);
    
    $stmt = $pdo->prepare("SELECT SUM(total_amount) as total FROM orders WHERE user_id = ? AND payment_status = 'paid' AND created_at BETWEEN datetime('now', '-60 days') AND datetime('now', '-30 days')");
    $stmt->execute([$user['id']]);
    $revPrevious = (float)($stmt->fetch()['total'] ?? 1); // Avoid div by zero
    $revenueGrowth = round((($revCurrent - $revPrevious) / max($revPrevious, 1)) * 100, 1);

    // Activity Growth
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM mail_activity WHERE user_id = ? AND created_at >= datetime('now', '-30 days')");
    $stmt->execute([$user['id']]);
    $mailCurrent = (int)($stmt->fetch()['count'] ?? 0);
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM mail_activity WHERE user_id = ? AND created_at BETWEEN datetime('now', '-60 days') AND datetime('now', '-30 days')");
    $stmt->execute([$user['id']]);
    $mailPrevious = (int)($stmt->fetch()['count'] ?? 1);
    $mailGrowth = round((($mailCurrent - $mailPrevious) / max($mailPrevious, 1)) * 100, 1);

    // 5. User Activity (Last 7 Days)
    $dailyActivity = [];
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM mail_activity WHERE user_id = ? AND date(created_at) = ?");
        $stmt->execute([$user['id'], $date]);
        $count = $stmt->fetch()['count'];
        $dailyActivity[] = [
            'date' => date('D', strtotime($date)),
            'count' => (int)$count
        ];
    }

    // 6. Recent Activity
    $stmt = $pdo->prepare("SELECT * FROM mail_activity WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
    $stmt->execute([$user['id']]);
    $recentActivity = $stmt->fetchAll();

    $formattedActivity = [];
    foreach ($recentActivity as $activity) {
        $details = json_decode($activity['details'], true);
        $formattedActivity[] = [
            'id' => $activity['id'],
            'type' => ucfirst($activity['email_type']),
            'recipient' => $activity['recipient_email'],
            'status' => $activity['status'],
            'date' => $activity['created_at'],
            'amount' => isset($details['data']['amount']) ? $details['data']['amount'] : null
        ];
    }

    jsonResponse([
        'overview' => [
            'total_mails' => $totalMails,
            'revenue' => $revenue,
            'active_clients' => $activeClients,
            'revenue_growth' => $revenueGrowth,
            'mail_growth' => $mailGrowth,
            'open_rate' => 0,
            'click_rate' => 0
        ],
        'chart_data' => $dailyActivity,
        'recent_activity' => $formattedActivity
    ]);

} catch (Exception $e) {
    errorResponse('Error fetching analytics: ' . $e->getMessage(), 500);
}
?>
