<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../mail/MailService.php';

// This script is intended to be run via Cron
// It checks if today is Monday and if the report has already been sent.

$today = date('Y-m-d');
$day_of_week = date('N'); // 1 (for Monday) through 7 (for Sunday)

if ($day_of_week != 1) {
    // Not Monday, skip
    exit("Today is not Monday. Skip.\n");
}

$db = db();
$task_name = 'weekly_report';

// Check if already sent today
$stmt = $db->prepare("SELECT last_run FROM automation_logs WHERE task_name = ? AND DATE(last_run) = ?");
$stmt->execute([$task_name, $today]);
if ($stmt->fetch()) {
    exit("Report already sent today ($today). Skip.\n");
}

echo "Generating weekly report for $today...\n";

// Reuse logic from weekly_report.php (simplified for automation)
// 1. Get stats for the last 7 days
$stats_query = "
    SELECT 
        COUNT(*) as total_requests,
        SUM(CASE WHEN source = 'whatsapp' THEN 1 ELSE 0 END) as whatsapp_requests,
        SUM(CASE WHEN source != 'whatsapp' OR source IS NULL THEN 1 ELSE 0 END) as web_requests
    FROM song_requests 
    WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
";
$totals = $db->query($stats_query)->fetch();

// 2. Top 10 Requesters
$top_requesters = $db->query("
    SELECT requester, COUNT(*) as count 
    FROM song_requests 
    WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
    AND requester IS NOT NULL AND requester != '' AND requester != 'Anónimo'
    GROUP BY requester 
    ORDER BY count DESC 
    LIMIT 10
")->fetchAll();

// 3. Top 10 Songs (by requests)
$top_songs_requested = $db->query("
    SELECT artist, song, COUNT(*) as count 
    FROM song_requests 
    WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY artist, song 
    ORDER BY count DESC 
    LIMIT 10
")->fetchAll();

// 4. Top 10 Songs (by likes)
$top_songs_liked = $db->query("
    SELECT song_title, likes_count 
    FROM song_likes 
    WHERE last_liked_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ORDER BY likes_count DESC 
    LIMIT 10
")->fetchAll();

// 5. Top 10 Chat Interactors
$top_chatters = $db->query("
    SELECT username, COUNT(*) as count 
    FROM messages 
    WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
    AND username IS NOT NULL AND username != '' AND username != 'Anónimo'
    GROUP BY username 
    ORDER BY count DESC 
    LIMIT 10
")->fetchAll();

// 6. Award Fan Points to Top 3 Chatters (Locking to prevent double rewards)
$rewards = [50, 30, 20];
$rewarded_users = [];
$today = date('Y-m-d');

$stmt_lock = $db->prepare("SELECT last_run FROM automation_logs WHERE task_name = 'weekly_report_rewards' AND DATE(last_run) = ?");
$stmt_lock->execute([$today]);

if (!$stmt_lock->fetch()) {
    require_once __DIR__ . '/../includes/points_helper.php';
    foreach ($top_chatters as $i => $c) {
        if ($i >= 3) break;
        $username = $c['username'];
        $points_to_add = $rewards[$i];
        
        awardPoints($username, $points_to_add);
        $rewarded_users[$username] = $points_to_add;
    }

    // Bot message to chat
    if (!empty($rewarded_users)) {
        $bot_msg = "🏆 ¡Atención comunidad! El Top 3 de interactores de esta semana ha sido premiado:\n\n";
        $medals = ["🥇", "🥈", "🥉"];
        $idx = 0;
        foreach ($rewarded_users as $user => $pts) {
            $bot_msg .= "{$medals[$idx]} $user: +$pts Fan Points\n";
            $idx++;
        }
        $bot_msg .= "\n¡Sigue participando en el chat para ganar el próximo lunes! 📻✨";
        
        $db->prepare("INSERT INTO messages (username, ip_address, message, type) VALUES (?, ?, ?, ?)")
           ->execute(['Lili Bot 🤖', '127.0.0.1', $bot_msg, 'text']);
    }

    $db->prepare("INSERT INTO automation_logs (task_name, last_run) VALUES ('weekly_report_rewards', NOW()) ON DUPLICATE KEY UPDATE last_run = NOW()")->execute();
} else {
    // If already rewarded today, we still want to show it in the email being generated
    foreach ($top_chatters as $i => $c) {
        if ($i >= 3) break;
        $rewarded_users[$c['username']] = $rewards[$i];
    }
}

$report_date = date('d/m/Y');
$week_start = date('d/m/Y', strtotime('-7 days'));

$html_content = "
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'Helvetica', Arial, sans-serif; color: #333; line-height: 1.6; }
        .container { max-width: 800px; margin: 0 auto; padding: 20px; border: 1px solid #eee; }
        .header { text-align: center; border-bottom: 2px solid #00e676; padding-bottom: 20px; margin-bottom: 30px; }
        h1 { color: #00e676; margin-bottom: 5px; }
        .subtitle { color: #666; font-size: 0.9rem; }
        .grid { display: flex; gap: 20px; margin-bottom: 30px; }
        .stat-card { flex: 1; background: #f9f9f9; padding: 15px; border-radius: 10px; text-align: center; border: 1px solid #eee; }
        .stat-card h3 { margin: 0; font-size: 0.8rem; color: #888; text-transform: uppercase; }
        .stat-card .value { font-size: 1.8rem; font-weight: bold; color: #00e676; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
        th { background: #f4f4f4; text-align: left; padding: 10px; border-bottom: 2px solid #ddd; }
        td { padding: 10px; border-bottom: 1px solid #eee; }
        .crown { color: #ffca28; }
        .reward-badge { background: #fff9c4; color: #f57f17; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; border: 1px solid #fbc02d; }
        .footer { text-align: center; font-size: 0.8rem; color: #999; margin-top: 40px; border-top: 1px solid #eee; padding-top: 20px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>Reporte Semanal Automático - Lili Records Radio</h1>
            <p class='subtitle'>Periodo: $week_start al $report_date</p>
        </div>

        <div class='grid'>
            <div class='stat-card'>
                <h3>Total Peticiones</h3>
                <div class='value'>{$totals['total_requests']}</div>
            </div>
            <div class='stat-card'>
                <h3>Vía WhatsApp</h3>
                <div class='value'>{$totals['whatsapp_requests']}</div>
            </div>
            <div class='stat-card'>
                <h3>Vía Web</h3>
                <div class='value'>{$totals['web_requests']}</div>
            </div>
        </div>

        <h2>🏆 Top 10 Oyentes de la Semana</h2>
        <table>
            <thead>
                <tr><th>#</th><th>Oyente</th><th>Peticiones</th></tr>
            </thead>
            <tbody>";
foreach ($top_requesters as $i => $r) {
    $crown = ($i === 0) ? "<span class='crown'>👑</span> " : "";
    $html_content .= "<tr><td>" . ($i + 1) . "</td><td>$crown" . htmlspecialchars($r['requester']) . "</td><td><b>" . $r['count'] . "</b></td></tr>";
}
$html_content .= "</tbody></table>

        <h2>💬 Top 10 Interactores del Chat</h2>
        <table>
            <thead>
                <tr><th>#</th><th>Usuario</th><th>Mensajes</th><th>Recompensa</th></tr>
            </thead>
            <tbody>";
foreach ($top_chatters as $i => $c) {
    $emoji = ($i === 0) ? "👑 " : "💬 ";
    $reward_html = "";
    if (isset($rewarded_users[$c['username']])) {
        $reward_html = "<span class='reward-badge'>+{$rewarded_users[$c['username']]} Fan Points</span>";
    }
    $html_content .= "<tr><td>" . ($i + 1) . "</td><td>$emoji" . htmlspecialchars($c['username']) . "</td><td><b>" . $c['count'] . "</b></td><td>$reward_html</td></tr>";
}
$html_content .= "</tbody></table>

        <h2>🎵 Top Canciones (Más Pedidas)</h2>
        <table>
            <thead><tr><th>Canción</th><th>Artista</th><th>Veces</th></tr></thead>
            <tbody>";
foreach ($top_songs_requested as $s) {
    $html_content .= "<tr><td>" . htmlspecialchars($s['song']) . "</td><td>" . htmlspecialchars($s['artist']) . "</td><td><b>" . $s['count'] . "</b></td></tr>";
}
$html_content .= "</tbody></table>

        <h2>⭐ Top Canciones (Más Likes)</h2>
        <table>
            <thead><tr><th>Canción</th><th>Likes</th></tr></thead>
            <tbody>";
foreach ($top_songs_liked as $s) {
    $html_content .= "<tr><td>" . htmlspecialchars($s['song_title']) . "</td><td><span style='color: #ff4081;'>❤</span> " . $s['likes_count'] . "</td></tr>";
}
$html_content .= "</tbody></table>

        <div class='footer'>
            Este reporte fue enviado automáticamente por el sistema.<br>
            © " . date('Y') . " Lili Records.
        </div>
    </div>
</body>
</html>";

$subject = "📊 [AUTO] Reporte Semanal - Lili Records Radio ($report_date)";
$res = MailService::sendMail(null, $subject, $html_content);

if (!empty($res['success'])) {
    echo "Report sent successfully.\n";
    // Log the run
    $stmt = $db->prepare("INSERT INTO automation_logs (task_name, last_run) VALUES (?, NOW()) ON DUPLICATE KEY UPDATE last_run = NOW()");
    $stmt->execute([$task_name]);
} else {
    echo "Failed to send report: " . ($res['error'] ?? 'Unknown error') . "\n";
}
