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

try {
    // Get user progress
    $stmt = $pdo->prepare("SELECT * FROM user_progress WHERE user_id = ?");
    $stmt->execute([$user['id']]);
    $progressData = $stmt->fetch();
    
    // If no progress record exists, create one
    if (!$progressData) {
        $progressId = generateUUID();
        $stmt = $pdo->prepare("INSERT INTO user_progress (id, user_id) VALUES (?, ?)");
        $stmt->execute([$progressId, $user['id']]);
        
        $stmt = $pdo->prepare("SELECT * FROM user_progress WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        $progressData = $stmt->fetch();
    }
    
    // Get user profile
    $stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
    $stmt->execute([$user['id']]);
    $userProfile = $stmt->fetch();
    
    // 1. Get total subscribers (real count from DB)
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM subscribers WHERE user_id = ? AND subscribed = 1");
    $stmt->execute([$user['id']]);
    $totalSubscribers = (int)$stmt->fetch()['count'];

    // 2. Get active campaigns (real count from unique email types in last 30 days)
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT email_type) as count FROM mail_activity WHERE user_id = ? AND created_at >= datetime('now', '-30 days')");
    $stmt->execute([$user['id']]);
    $activeCampaigns = (int)$stmt->fetch()['count'];

    // 3. Revenue from orders (already calculating in user progress but let's be explicit)
    $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);

    // 4. Calculate Growth (Revenue growth compared to previous 30 days)
    $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);
    $growth = round((($revCurrent - $revPrevious) / max($revPrevious, 1)) * 100, 1);

    // Prepare response data
    $responseData = [
        'user' => [
            'id' => $user['id'],
            'email' => $user['email'],
            'username' => $userProfile['username'] ?? explode('@', $user['email'])[0],
            'firstName' => $userProfile['first_name'] ?? '',
            'lastName' => $userProfile['last_name'] ?? '',
            'referralCount' => $progressData['referral_count'] ?? 0,
            'referralEarnings' => (float)($progressData['referral_earnings'] ?? 0)
        ],
        'totalMails' => (int)($progressData['mails_sent'] ?? 0),
        'currentRank' => $progressData['current_rank'] ?? 'Bronze',
        'progressPercentage' => (int)($progressData['progress_percentage'] ?? 0),
        'overview' => [
            'total_subscribers' => $totalSubscribers,
            'active_campaigns' => $activeCampaigns,
            'total_emails_sent' => (int)($progressData['mails_sent'] ?? 0),
            'open_rate' => 0, // Need tracking implementation for real data
            'click_rate' => 0,
            'conversion_rate' => 0,
            'revenue' => $revenue,
            'growth' => $growth
        ],
        'campaigns' => [], // Potential future table
        'subscribers' => [
            'total' => $totalSubscribers,
            'segments' => [
                ['name' => 'Active', 'count' => $totalSubscribers, 'percentage' => 100],
                ['name' => 'New', 'count' => 0, 'percentage' => 0]
            ]
        ],
        'recentReferrals' => []
    ];
    
    // Fetch recent referrals
    $stmt = $pdo->prepare("
        SELECT referred_name as name, created_at as date, status, reward 
        FROM referrals 
        WHERE referrer_id = ? 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    $stmt->execute([$user['id']]);
    $responseData['recentReferrals'] = $stmt->fetchAll();
    
    // Format dates for display
    foreach ($responseData['recentReferrals'] as &$ref) {
        $ref['date'] = date('M d, Y', strtotime($ref['date']));
        $ref['reward'] = (float)$ref['reward'];
    }
    
    jsonResponse($responseData, 200);
} catch (Exception $e) {
    errorResponse('Error fetching dashboard data: ' . $e->getMessage(), 500);
}
?>