<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Survey Tasks';
include 'side.php';

$tasksQuery = $conn->query("
    SELECT t.*, 
           (SELECT COUNT(*) FROM task_completions 
            WHERE task_id = t.id AND user_id = $userId 
            AND DATE(created_at) = CURDATE()) as completed_today
    FROM tasks t
    WHERE t.task_type = 'survey' AND t.is_active = 1
    ORDER BY t.created_at DESC
");

$todayCount = $conn->query("
    SELECT COUNT(*) as count 
    FROM task_completions 
    WHERE user_id = $userId 
    AND task_type = 'survey'
    AND DATE(created_at) = CURDATE()
")->fetch_assoc()['count'];

$totalEarnings = $conn->query("
    SELECT COALESCE(SUM(reward_earned), 0) as total
    FROM task_completions
    WHERE user_id = $userId AND task_type = 'survey'
")->fetch_assoc()['total'];
?>
<style>
.tasks-container { padding: 8px; max-width: 1400px; margin: 0 auto; }
.stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-bottom: 16px; }
.stat-card { background: linear-gradient(135deg, <?php echo $themeColor; ?> 0%, #764ba2 100%); border-radius: 12px; padding: 16px; position: relative; overflow: hidden; transition: all 0.3s ease; }
.stat-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(135deg, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0) 100%); }
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 12px 32px rgba(<?php echo $rgbColor; ?>, 0.3); }
.stat-content { position: relative; z-index: 1; }
.stat-label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: rgba(255, 255, 255, 0.9); margin-bottom: 8px; }
.stat-amount { font-size: 24px; font-weight: 900; color: white; }
.tasks-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; }
.task-card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 12px; padding: 16px; transition: all 0.3s ease; }
.task-card:hover { transform: translateY(-4px); box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1); border-color: <?php echo $themeColor; ?>; }
.task-header { display: flex; align-items: start; gap: 12px; margin-bottom: 12px; }
.task-icon { width: 48px; height: 48px; background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 24px; color: white; flex-shrink: 0; }
.task-info { flex: 1; }
.task-title { font-size: 16px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; }
.task-reward { font-size: 14px; font-weight: 700; color: #10b981; }
.task-description { font-size: 13px; color: var(--text-secondary); line-height: 1.5; margin-bottom: 12px; }
.task-meta { display: flex; gap: 12px; margin-bottom: 12px; font-size: 12px; color: var(--text-secondary); }
.task-meta-item { display: flex; align-items: center; gap: 4px; }
.btn-task { width: 100%; padding: 12px; background: linear-gradient(135deg, <?php echo $themeColor; ?> 0%, #ec4899 100%); color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 700; cursor: pointer; transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; }
.btn-task:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(<?php echo $rgbColor; ?>, 0.4); }
.btn-task:disabled { background: var(--darker-bg); color: var(--text-secondary); cursor: not-allowed; opacity: 0.6; }
.empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); }
.empty-state i { font-size: 64px; margin-bottom: 16px; opacity: 0.5; }
@media (max-width: 768px) {
    .tasks-container { padding: 6px; }
    .tasks-grid { grid-template-columns: 1fr; }
    .stats-row { grid-template-columns: 1fr; }
}
</style>

<div class="tasks-container">
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-content">
                <div class="stat-label">Available Surveys</div>
                <div class="stat-amount"><?php echo $tasksQuery->num_rows; ?></div>
            </div>
        </div>
        <div class="stat-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
            <div class="stat-content">
                <div class="stat-label">Completed Today</div>
                <div class="stat-amount"><?php echo $todayCount; ?></div>
            </div>
        </div>
        <div class="stat-card" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
            <div class="stat-content">
                <div class="stat-label">Total Earnings</div>
                <div class="stat-amount">KSH <?php echo number_format($totalEarnings, 2); ?></div>
            </div>
        </div>
    </div>
    
    <?php if ($tasksQuery->num_rows > 0): ?>
    <div class="tasks-grid">
        <?php while ($task = $tasksQuery->fetch_assoc()): ?>
        <div class="task-card">
            <div class="task-header">
                <div class="task-icon">
                    <i class="fas fa-poll"></i>
                </div>
                <div class="task-info">
                    <div class="task-title"><?php echo htmlspecialchars($task['title']); ?></div>
                    <div class="task-reward">
                        <i class="fas fa-coins"></i> KSH <?php echo number_format($task['reward_amount'], 2); ?>
                    </div>
                </div>
            </div>
            
            <?php if (!empty($task['instructions'])): ?>
            <div class="task-description">
                <?php echo nl2br(htmlspecialchars($task['instructions'])); ?>
            </div>
            <?php endif; ?>
            
            <div class="task-meta">
                <div class="task-meta-item">
                    <i class="fas fa-users"></i>
                    <span><?php echo $task['total_completions']; ?> completed</span>
                </div>
                <?php if ($task['daily_limit']): ?>
                <div class="task-meta-item">
                    <i class="fas fa-clock"></i>
                    <span>Limit: <?php echo $task['daily_limit']; ?>/day</span>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if ($task['completed_today'] > 0): ?>
                <button class="btn-task" disabled>
                    <i class="fas fa-check-circle"></i>
                    Completed Today
                </button>
            <?php else: ?>
                <a href="<?php echo htmlspecialchars($task['task_url']); ?>" target="_blank" class="btn-task" onclick="return markStarted(<?php echo $task['id']; ?>)">
                    <i class="fas fa-external-link-alt"></i>
                    Start Survey
                </a>
            <?php endif; ?>
        </div>
        <?php endwhile; ?>
    </div>
    <?php else: ?>
    <div class="empty-state">
        <i class="fas fa-poll"></i>
        <p><strong>No survey tasks available</strong></p>
        <p>Check back later for new surveys!</p>
    </div>
    <?php endif; ?>
</div>

<script>
function markStarted(taskId) {
    setTimeout(() => {
        if (confirm('Did you complete the survey? Click OK to claim your reward!')) {
            completeTask(taskId);
        }
    }, 10000); // After 10 seconds
    return true;
}

function completeTask(taskId) {
    fetch('/api/complete-task.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, task_type: 'survey' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ Task completed! KSH ' + data.reward + ' added to your Survey Wallet!');
            location.reload();
        } else {
            alert('❌ ' + data.message);
        }
    });
}
</script>

<?php include 'footer.php'; ?>