<?php
session_start();
require_once 'config/database.php';
require_once 'classes/TaskManager.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$userId = $_SESSION['user_id'];
// Load database configuration
$dbConfig = require 'config/database.php';

// Create PDO instance
$pdo = new PDO(
    "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}",
    $dbConfig['username'],
    $dbConfig['password'],
    $dbConfig['options']
);
$taskManager = new TaskManager($pdo);

// Handle task completion via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_task']) && isset($_POST['task_id'])) {
    header('Content-Type: application/json');
    $taskId = (int)$_POST['task_id'];
    $result = $taskManager->completeTask($userId, $taskId);
    
    // Get updated progress
    $progress = $taskManager->getUserTaskProgress($userId);
    
    echo json_encode([
        'success' => $result,
        'progress' => [
            'completed' => $progress['completed'],
            'total' => $progress['total']
        ]
    ]);
    exit();
}

// Get tasks for the user
$tasks = [];
$completedCount = 0;
$totalTasks = 0;

try {
    $tasks = $taskManager->getDailyTasks($userId);
    $completedCount = $taskManager->getCompletedTasksToday($userId);
    $totalTasks = $taskManager->getTotalTasksToday($userId);
} catch (Exception $e) {
    $error = "Error loading tasks: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily Tasks - Vonaida</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <style>
        .task-card {
            transition: all 0.3s ease;
        }
        .task-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .progress-bar {
            transition: width 0.6s ease;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <header class="mb-8">
            <h1 class="text-3xl font-bold text-gray-800 mb-2">Daily Tasks</h1>
            <div class="flex items-center justify-between">
                <p class="text-gray-600">Complete your daily language practice</p>
                <a href="chat.php" class="text-blue-600 hover:underline">Back to Chat</a>
            </div>
        </header>

        <!-- Progress Bar -->
        <div class="bg-white rounded-lg shadow p-6 mb-8">
            <div class="flex justify-between mb-2">
                <span class="text-sm font-medium text-gray-700">Daily Progress</span>
                <span class="text-sm font-medium text-gray-700"><?= $completedCount ?> of <?= $totalTasks ?> completed</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-4">
                <div 
                    class="progress-bar bg-blue-600 h-4 rounded-full" 
                    style="width: <?= $totalTasks > 0 ? ($completedCount / $totalTasks) * 100 : 0 ?>%;"
                ></div>
            </div>
        </div>

        <!-- Tasks List -->
        <div class="grid md:grid-cols-2 gap-6">
            <?php if (!empty($tasks)): ?>
                <?php foreach ($tasks as $task): ?>
                    <div class="task-card bg-white rounded-lg shadow p-6 <?= $task['status'] === 'completed' ? 'opacity-75' : '' ?>">
                        <div class="flex justify-between items-start mb-4">
                            <h3 class="text-lg font-semibold text-gray-800">
                                <?= htmlspecialchars($task['category_name']) ?>
                                <?php if ($task['status'] === 'completed'): ?>
                                    <span class="ml-2 text-sm text-green-600">✓ Completed</span>
                                <?php endif; ?>
                            </h3>
                            <?php if ($task['status'] !== 'completed'): ?>
                                <button type="button" 
                                    onclick="completeTask(<?= $task['id'] ?>)" 
                                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors complete-task-btn"
                                    data-task-id="<?= $task['id'] ?>"
                                    <?= $task['status'] === 'completed' ? 'disabled' : '' ?>>
                                <?= $task['status'] === 'completed' ? 'Completed' : 'Mark as Complete' ?>
                            </button>
                            <?php endif; ?>
                        </div>
                        
                        <div class="mb-4 text-gray-700">
                            <p class="mb-2"><?= nl2br(htmlspecialchars($task['instruction_text'])) ?></p>
                            <?php if (!empty($task['tips_text'])): ?>
                                <div class="mt-3 p-3 bg-yellow-50 border-l-4 border-yellow-400">
                                    <p class="text-sm text-yellow-700">💡 <?= htmlspecialchars($task['tips_text']) ?></p>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if ($task['status'] !== 'completed'): ?>
                            <form method="POST" class="mt-4">
                                <input type="hidden" name="task_id" value="<?= $task['task_id'] ?>">
                                <button 
                                    type="submit" 
                                    name="complete_task" 
                                    class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition duration-200"
                                >
                                    Mark as Complete
                                </button>
                            </form>
                        <?php else: ?>
                            <div class="text-center mt-4 p-3 bg-green-50 text-green-700 rounded-md">
                                <p class="text-sm">✅ Completed at <?= date('g:i A', strtotime($task['completed_at'])) ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-span-2 text-center py-12">
                    <div class="inline-block p-4 bg-green-50 rounded-full mb-4">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                    </div>
                    <h3 class="text-xl font-semibold text-gray-800 mb-2">All Done for Today!</h3>
                    <p class="text-gray-600 mb-6">You've completed all your daily tasks. Come back tomorrow for more!</p>
                    <a href="chat.php" class="inline-block bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-6 rounded-md transition duration-200">
                        Go to Chat
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        async function completeTask(taskId) {
            const btn = document.querySelector(`button[data-task-id="${taskId}"]`);
            if (!btn) return;
            
            btn.disabled = true;
            const originalText = btn.textContent;
            btn.innerHTML = '<span class="animate-spin">🔄</span>';
            
            try {
                const response = await fetch('daily_tasks.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `complete_task=1&task_id=${taskId}`
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Update the UI
                    btn.textContent = 'Completed';
                    btn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
                    btn.classList.add('bg-green-500', 'cursor-default');
                    
                    // Update progress bar
                    const progress = result.progress;
                    const progressBar = document.getElementById('progress-bar');
                    const progressText = document.getElementById('progress-text');
                    const percentage = Math.round((progress.completed / progress.total) * 100);
                    
                    progressBar.style.width = `${percentage}%`;
                    progressText.textContent = `${progress.completed} of ${progress.total} tasks completed`;
                    
                    // Show success message
                    const message = document.createElement('div');
                    message.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg';
                    message.textContent = 'Task marked as completed!';
                    document.body.appendChild(message);
                    
                    // Remove message after 3 seconds
                    setTimeout(() => {
                        message.remove();
                    }, 3000);
                } else {
                    throw new Error('Failed to complete task');
                }
            } catch (error) {
                console.error('Error:', error);
                btn.textContent = 'Error. Try Again';
                btn.disabled = false;
                setTimeout(() => {
                    btn.textContent = originalText;
                }, 2000);
            }
        }
        
        // Add animation to progress bar
        document.addEventListener('DOMContentLoaded', function() {
            const progressBar = document.querySelector('.progress-bar');
            if (progressBar) {
                // Force reflow to trigger the animation
                void progressBar.offsetWidth;
                progressBar.style.width = progressBar.style.width;
            }
        });
    </script>
</body>
</html>
