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

require_once 'admin_protect.php';
requirePermission('manage_content');

$conn = getConnection();

// Handle task actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch($action) {
        case 'add':
            $title = sanitize($_POST['title']);
            $description = sanitize($_POST['description']);
            $instructions = sanitize($_POST['instructions']);
            $taskType = sanitize($_POST['task_type']);
            $verificationType = sanitize($_POST['verification_type']);
            $taskUrl = sanitize($_POST['task_url'] ?? '');
            $proofRequired = sanitize($_POST['proof_required'] ?? 'none');
            $proofInstructions = sanitize($_POST['proof_instructions'] ?? '');
            $quizQuestion = sanitize($_POST['quiz_question'] ?? '');
            $quizAnswer = sanitize($_POST['quiz_answer'] ?? '');
            $reward = floatval($_POST['reward']);
            $dailyLimit = intval($_POST['daily_limit_per_user']);
            $totalLimit = !empty($_POST['total_limit']) ? intval($_POST['total_limit']) : null;
            $minDuration = intval($_POST['min_duration_seconds'] ?? 0);
            $difficulty = sanitize($_POST['difficulty']);
            $category = sanitize($_POST['category']);
            $featured = isset($_POST['featured']) ? 1 : 0;
            $showInSidebar = isset($_POST['show_in_sidebar']) ? 1 : 0;
            
            $stmt = $conn->prepare("INSERT INTO tasks (title, description, instructions, task_type, verification_type, task_url, proof_required, proof_instructions, quiz_question, quiz_answer, reward, daily_limit_per_user, total_limit, min_duration_seconds, difficulty, category, featured, show_in_sidebar) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssssssdiiissii", $title, $description, $instructions, $taskType, $verificationType, $taskUrl, $proofRequired, $proofInstructions, $quizQuestion, $quizAnswer, $reward, $dailyLimit, $totalLimit, $minDuration, $difficulty, $category, $featured, $showInSidebar);
            
            if ($stmt->execute()) {
                setFlash('success', 'Task added successfully!');
            } else {
                setFlash('error', 'Failed to add task.');
            }
            redirect('tasks.php');
            break;
            
        case 'edit':
            $taskId = intval($_POST['task_id']);
            $title = sanitize($_POST['title']);
            $description = sanitize($_POST['description']);
            $instructions = sanitize($_POST['instructions']);
            $taskUrl = sanitize($_POST['task_url'] ?? '');
            $reward = floatval($_POST['reward']);
            $status = sanitize($_POST['status']);
            $featured = isset($_POST['featured']) ? 1 : 0;
            $showInSidebar = isset($_POST['show_in_sidebar']) ? 1 : 0;
            
            $stmt = $conn->prepare("UPDATE tasks SET title=?, description=?, instructions=?, task_url=?, reward=?, status=?, featured=?, show_in_sidebar=? WHERE id=?");
            $stmt->bind_param("ssssdsiis", $title, $description, $instructions, $taskUrl, $reward, $status, $featured, $showInSidebar, $taskId);
            
            if ($stmt->execute()) {
                setFlash('success', 'Task updated successfully!');
            } else {
                setFlash('error', 'Failed to update task.');
            }
            redirect('tasks.php');
            break;
            
        case 'delete':
            $taskId = intval($_POST['task_id']);
            $conn->query("DELETE FROM tasks WHERE id=$taskId");
            setFlash('success', 'Task deleted successfully!');
            redirect('tasks.php');
            break;
            
        case 'toggle_status':
            $taskId = intval($_POST['task_id']);
            $task = $conn->query("SELECT status FROM tasks WHERE id=$taskId")->fetch_assoc();
            $newStatus = $task['status'] === 'active' ? 'inactive' : 'active';
            $conn->query("UPDATE tasks SET status='$newStatus' WHERE id=$taskId");
            setFlash('success', 'Task status updated!');
            redirect('tasks.php');
            break;
    }
}

// Handle GET actions
if (isset($_GET['delete'])) {
    $taskId = intval($_GET['delete']);
    $conn->query("DELETE FROM tasks WHERE id=$taskId");
    setFlash('success', 'Task deleted!');
    redirect('tasks.php');
}

// Get tasks with statistics
$tasks = $conn->query("
    SELECT t.*, 
           COUNT(DISTINCT CASE WHEN tc.status='pending' THEN tc.id END) as pending_count,
           COUNT(DISTINCT CASE WHEN tc.status='approved' THEN tc.id END) as approved_count
    FROM tasks t
    LEFT JOIN task_completions tc ON t.id = tc.task_id
    GROUP BY t.id
    ORDER BY t.created_at DESC
");

// Get categories for dropdown
$categories = $conn->query("SELECT name FROM task_categories WHERE status='active' ORDER BY name");
?>

<style>
    .task-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        transition: all 0.3s;
    }
    
    .task-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        transform: translateY(-2px);
    }
    
    .task-header {
        display: flex;
        justify-content: space-between;
        align-items: start;
        margin-bottom: 12px;
    }
    
    .task-title {
        font-size: 18px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 6px;
    }
    
    .task-meta {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        margin: 12px 0;
    }
    
    .task-badge {
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }
    
    .badge-active {
        background: rgba(16, 185, 129, 0.15);
        color: #10b981;
    }
    
    .badge-inactive {
        background: rgba(107, 114, 128, 0.15);
        color: #6b7280;
    }
    
    .badge-pending {
        background: rgba(245, 158, 11, 0.15);
        color: #f59e0b;
    }
    
    .badge-featured {
        background: rgba(236, 72, 153, 0.15);
        color: #ec4899;
    }
    
    .badge-sidebar {
        background: rgba(59, 130, 246, 0.15);
        color: #3b82f6;
    }
    
    .task-actions {
        display: flex;
        gap: 8px;
    }
    
    .btn-sm {
        padding: 6px 12px;
        font-size: 12px;
        border-radius: 6px;
    }
    
    .add-task-btn {
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        color: white;
        border: none;
        border-radius: 50%;
        font-size: 24px;
        cursor: pointer;
        box-shadow: 0 4px 12px rgba(var(--theme-rgb), 0.4);
        z-index: 1000;
        transition: all 0.3s;
    }
    
    .add-task-btn:hover {
        transform: scale(1.1);
        box-shadow: 0 6px 20px rgba(var(--theme-rgb), 0.6);
    }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.7);
        backdrop-filter: blur(4px);
        z-index: 10000;
        overflow-y: auto;
        padding: 20px;
    }
    
    .modal.active {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .modal-content {
        background: var(--card-bg);
        border-radius: 16px;
        padding: 30px;
        max-width: 800px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
    }
    
    .form-section {
        margin-bottom: 24px;
        padding-bottom: 24px;
        border-bottom: 1px solid var(--border-color);
    }
    
    .form-section:last-child {
        border-bottom: none;
    }
    
    .section-title {
        font-size: 16px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-group.full-width {
        grid-column: 1 / -1;
    }
    
    .form-label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: var(--text-secondary);
        margin-bottom: 6px;
    }
    
    .form-control {
        width: 100%;
        padding: 10px 12px;
        font-size: 14px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--darker-bg);
        color: var(--text-primary);
    }
    
    .form-control:focus {
        outline: none;
        border-color: var(--theme-color);
    }
    
    textarea.form-control {
        min-height: 100px;
        resize: vertical;
    }
    
    .checkbox-wrapper {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .help-text {
        font-size: 12px;
        color: var(--text-secondary);
        margin-top: 4px;
    }
</style>

<!-- Page Header -->
<div class="page-header">
    <h1 class="page-title">
        <i class="fas fa-tasks"></i> Manage Tasks
    </h1>
    <p class="page-subtitle">Create and manage tasks for users to complete and earn rewards</p>
</div>

<!-- Statistics -->
<div class="stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px;">
    <?php
    $stats = $conn->query("
        SELECT 
            COUNT(*) as total_tasks,
            SUM(CASE WHEN t.status='active' THEN 1 ELSE 0 END) as active_tasks,
            SUM(t.completed_count) as total_completions,
            COALESCE(SUM(CASE WHEN tc.status='pending' THEN 1 ELSE 0 END), 0) as pending_review,
            SUM(CASE WHEN t.show_in_sidebar=1 THEN 1 ELSE 0 END) as sidebar_tasks
        FROM tasks t
        LEFT JOIN task_completions tc ON t.id = tc.task_id
    ")->fetch_assoc();
    ?>
    
    <div class="stat-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <i class="fas fa-tasks"></i>
        </div>
        <div class="stat-label">Total Tasks</div>
        <div class="stat-value"><?php echo $stats['total_tasks']; ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-label">Active Tasks</div>
        <div class="stat-value"><?php echo $stats['active_tasks']; ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">
            <i class="fas fa-chart-line"></i>
        </div>
        <div class="stat-label">Total Completions</div>
        <div class="stat-value"><?php echo number_format($stats['total_completions']); ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-label">Pending Review</div>
        <div class="stat-value"><?php echo $stats['pending_review']; ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
            <i class="fas fa-bars"></i>
        </div>
        <div class="stat-label">In Sidebar</div>
        <div class="stat-value"><?php echo $stats['sidebar_tasks']; ?></div>
    </div>
</div>

<!-- Tasks List -->
<div class="tasks-list">
    <?php if ($tasks->num_rows > 0): ?>
        <?php while ($task = $tasks->fetch_assoc()): ?>
            <div class="task-card">
                <div class="task-header">
                    <div>
                        <div class="task-title">
                            <?php if ($task['featured']): ?><i class="fas fa-star" style="color: #f59e0b;"></i><?php endif; ?>
                            <?php if ($task['show_in_sidebar']): ?><i class="fas fa-bars" style="color: #3b82f6;"></i><?php endif; ?>
                            <?php echo htmlspecialchars($task['title']); ?>
                        </div>
                        <p style="color: var(--text-secondary); font-size: 14px; margin: 4px 0;">
                            <?php echo htmlspecialchars(substr($task['description'], 0, 100)); ?>
                            <?php if (strlen($task['description']) > 100): ?>...<?php endif; ?>
                        </p>
                        <?php if ($task['task_url']): ?>
                            <p style="color: var(--text-secondary); font-size: 12px; margin: 4px 0; font-family: monospace;">
                                <i class="fas fa-link"></i> <?php echo htmlspecialchars($task['task_url']); ?>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="task-actions">
                        <button class="btn btn-sm btn-primary" onclick="viewTask(<?php echo $task['id']; ?>)">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="editTask(<?php echo htmlspecialchars(json_encode($task)); ?>)">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteTask(<?php echo $task['id']; ?>)">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                
                <div class="task-meta">
                    <span class="task-badge badge-<?php echo $task['status']; ?>">
                        <?php echo $task['status']; ?>
                    </span>
                    <span class="task-badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
                        <i class="fas fa-coins"></i> Ksh <?php echo number_format($task['reward'], 2); ?>
                    </span>
                    <span class="task-badge" style="background: rgba(139, 92, 246, 0.15); color: #8b5cf6;">
                        <i class="fas fa-check"></i> <?php echo $task['completed_count']; ?> completions
                    </span>
                    <?php if ($task['pending_count'] > 0): ?>
                        <span class="task-badge badge-pending">
                            <i class="fas fa-clock"></i> <?php echo $task['pending_count']; ?> pending
                        </span>
                    <?php endif; ?>
                    <span class="task-badge" style="background: rgba(16, 185, 129, 0.15); color: #10b981;">
                        <i class="fas fa-tag"></i> <?php echo ucfirst($task['task_type']); ?>
                    </span>
                    <span class="task-badge" style="background: rgba(236, 72, 153, 0.15); color: #ec4899;">
                        <i class="fas fa-shield-alt"></i> <?php echo ucfirst(str_replace('_', ' ', $task['verification_type'])); ?>
                    </span>
                    <?php if ($task['show_in_sidebar']): ?>
                        <span class="task-badge badge-sidebar">
                            <i class="fas fa-bars"></i> In Sidebar
                        </span>
                    <?php endif; ?>
                </div>
                
                <div style="margin-top: 12px; display: flex; gap: 12px; font-size: 12px; color: var(--text-secondary);">
                    <span><i class="fas fa-redo"></i> <?php echo $task['daily_limit_per_user']; ?>x per day</span>
                    <span><i class="fas fa-signal"></i> <?php echo ucfirst($task['difficulty']); ?></span>
                    <?php if ($task['min_duration_seconds'] > 0): ?>
                        <span><i class="fas fa-clock"></i> <?php echo $task['min_duration_seconds']; ?>s min</span>
                    <?php endif; ?>
                </div>
            </div>
        <?php endwhile; ?>
    <?php else: ?>
        <div style="text-align: center; padding: 60px 20px; color: var(--text-secondary);">
            <i class="fas fa-tasks" style="font-size: 64px; opacity: 0.3; margin-bottom: 20px;"></i>
            <h3>No tasks yet</h3>
            <p>Click the + button to create your first task</p>
        </div>
    <?php endif; ?>
</div>

<!-- Add Task Button -->
<button class="add-task-btn" onclick="openAddModal()">
    <i class="fas fa-plus"></i>
</button>

<!-- ADD TASK MODAL -->
<div class="modal" id="addModal">
    <div class="modal-content">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
            <h2 style="margin: 0;"><i class="fas fa-plus-circle"></i> Add New Task</h2>
            <button onclick="closeAddModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; color: var(--text-secondary);">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form method="POST" id="addTaskForm">
            <input type="hidden" name="action" value="add">
            
            <!-- Basic Information -->
            <div class="form-section">
                <div class="section-title">
                    <i class="fas fa-info-circle"></i> Basic Information
                </div>
                
                <div class="form-group full-width">
                    <label class="form-label">Task Title *</label>
                    <input type="text" name="title" class="form-control" required placeholder="e.g., Follow us on Instagram">
                </div>
                
                <div class="form-group full-width">
                    <label class="form-label">Description *</label>
                    <textarea name="description" class="form-control" required placeholder="Brief description of what the task involves"></textarea>
                    <div class="help-text">This will be shown to users</div>
                </div>
                
                <div class="form-group full-width">
                    <label class="form-label">Step-by-Step Instructions *</label>
                    <textarea name="instructions" class="form-control" required placeholder="1. Go to our page&#10;2. Click follow&#10;3. Take a screenshot&#10;4. Submit here"></textarea>
                    <div class="help-text">Write each step on a new line</div>
                </div>
            </div>
            
            <!-- Task Settings -->
            <div class="form-section">
                <div class="section-title">
                    <i class="fas fa-cog"></i> Task Settings
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Task Type *</label>
                        <select name="task_type" class="form-control" required>
                            <option value="social_follow">Social Media Follow</option>
                            <option value="link_visit">Visit Link</option>
                            <option value="app_install">App Install</option>
                            <option value="survey">Complete Survey</option>
                            <option value="signup">Sign Up</option>
                            <option value="video_watch">Watch Video</option>
                            <option value="article_read">Read Article</option>
                            <option value="quiz">Answer Quiz</option>
                            <option value="custom">Custom Task</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Verification Method *</label>
                        <select name="verification_type" class="form-control" required onchange="updateVerificationFields(this.value)">
                            <option value="manual">Manual Review</option>
                            <option value="proof_required">Requires Proof</option>
                            <option value="quiz">Quiz Question</option>
                            <option value="auto">Auto-Approve</option>
                        </select>
                        <div class="help-text">How submissions will be verified</div>
                    </div>
                    
                    <div class="form-group full-width">
                        <label class="form-label">Task URL / Link</label>
                        <input type="url" name="task_url" class="form-control" placeholder="https://example.com">
                        <div class="help-text">Link users need to visit (Instagram, website, survey, etc.)</div>
                    </div>
                </div>
            </div>
            
            <!-- Proof Requirements -->
            <div class="form-section" id="proofSection">
                <div class="section-title">
                    <i class="fas fa-file-upload"></i> Proof Requirements
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">What Proof is Needed?</label>
                        <select name="proof_required" class="form-control">
                            <option value="none">No Proof Needed</option>
                            <option value="screenshot">Screenshot</option>
                            <option value="text">Text/Username/Code</option>
                            <option value="link">Link/URL</option>
                        </select>
                    </div>
                    
                    <div class="form-group full-width">
                        <label class="form-label">Proof Instructions</label>
                        <input type="text" name="proof_instructions" class="form-control" placeholder="e.g., Submit your Instagram username">
                    </div>
                </div>
            </div>
            
            <!-- Quiz Questions -->
            <div class="form-section" id="quizSection" style="display: none;">
                <div class="section-title">
                    <i class="fas fa-question-circle"></i> Quiz Question
                </div>
                
                <div class="form-group full-width">
                    <label class="form-label">Question</label>
                    <input type="text" name="quiz_question" class="form-control" placeholder="What color is our logo?">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Correct Answer</label>
                    <input type="text" name="quiz_answer" class="form-control" placeholder="blue">
                    <div class="help-text">User's answer must match this exactly (case-insensitive)</div>
                </div>
            </div>
            
            <!-- Rewards & Limits -->
            <div class="form-section">
                <div class="section-title">
                    <i class="fas fa-coins"></i> Rewards & Limits
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Reward Amount (KSH) *</label>
                        <input type="number" step="0.01" name="reward" class="form-control" required placeholder="10.00">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Times Per Day Per User *</label>
                        <input type="number" name="daily_limit_per_user" class="form-control" required value="1" min="1">
                        <div class="help-text">How many times each user can do this daily</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Total Limit (Optional)</label>
                        <input type="number" name="total_limit" class="form-control" placeholder="Leave empty for unlimited">
                        <div class="help-text">Total number of completions allowed across all users</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Min Time (Seconds)</label>
                        <input type="number" name="min_duration_seconds" class="form-control" value="0" min="0">
                        <div class="help-text">Minimum time user must spend</div>
                    </div>
                </div>
            </div>
            
            <!-- Additional Options -->
            <div class="form-section">
                <div class="section-title">
                    <i class="fas fa-sliders-h"></i> Additional Options
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Difficulty *</label>
                        <select name="difficulty" class="form-control" required>
                            <option value="easy">Easy</option>
                            <option value="medium">Medium</option>
                            <option value="hard">Hard</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Category</label>
                        <select name="category" class="form-control">
                            <?php 
                            $categories->data_seek(0);
                            while ($cat = $categories->fetch_assoc()): 
                            ?>
                                <option value="<?php echo htmlspecialchars($cat['name']); ?>">
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="form-group full-width">
                        <div class="checkbox-wrapper">
                            <input type="checkbox" name="featured" id="featured" value="1">
                            <label for="featured" style="margin: 0; cursor: pointer;">
                                <i class="fas fa-star"></i> Featured Task (Show prominently)
                            </label>
                        </div>
                    </div>
                    
                    <div class="form-group full-width">
                        <div class="checkbox-wrapper">
                            <input type="checkbox" name="show_in_sidebar" id="showInSidebar" value="1">
                            <label for="showInSidebar" style="margin: 0; cursor: pointer;">
                                <i class="fas fa-bars"></i> Show in Sidebar Menu (Quick access for users)
                            </label>
                        </div>
                        <div class="help-text">Users will see this task in their sidebar for quick access</div>
                    </div>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px;">
                <i class="fas fa-plus"></i> Create Task
            </button>
        </form>
    </div>
</div>

<!-- EDIT TASK MODAL -->
<div class="modal" id="editModal">
    <div class="modal-content">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
            <h2 style="margin: 0;"><i class="fas fa-edit"></i> Edit Task</h2>
            <button onclick="closeEditModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; color: var(--text-secondary);">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form method="POST" id="editTaskForm">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="task_id" id="editTaskId">
            
            <div class="form-group">
                <label class="form-label">Task Title *</label>
                <input type="text" name="title" id="editTitle" class="form-control" required>
            </div>
            
            <div class="form-group">
                <label class="form-label">Description *</label>
                <textarea name="description" id="editDescription" class="form-control" required></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label">Instructions *</label>
                <textarea name="instructions" id="editInstructions" class="form-control" required></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label">Task URL / Link</label>
                <input type="url" name="task_url" id="editTaskUrl" class="form-control">
                <div class="help-text">Link users need to visit</div>
            </div>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Reward (KSH) *</label>
                    <input type="number" step="0.01" name="reward" id="editReward" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Status *</label>
                    <select name="status" id="editStatus" class="form-control" required>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                        <option value="completed">Completed</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <div class="checkbox-wrapper">
                    <input type="checkbox" name="featured" id="editFeatured" value="1">
                    <label for="editFeatured" style="margin: 0; cursor: pointer;">
                        <i class="fas fa-star"></i> Featured Task
                    </label>
                </div>
            </div>
            
            <div class="form-group">
                <div class="checkbox-wrapper">
                    <input type="checkbox" name="show_in_sidebar" id="editShowInSidebar" value="1">
                    <label for="editShowInSidebar" style="margin: 0; cursor: pointer;">
                        <i class="fas fa-bars"></i> Show in Sidebar
                    </label>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px;">
                <i class="fas fa-save"></i> Update Task
            </button>
        </form>
    </div>
</div>

<script>
function openAddModal() {
    document.getElementById('addModal').classList.add('active');
}

function closeAddModal() {
    document.getElementById('addModal').classList.remove('active');
    document.getElementById('addTaskForm').reset();
}

function editTask(task) {
    document.getElementById('editTaskId').value = task.id;
    document.getElementById('editTitle').value = task.title;
    document.getElementById('editDescription').value = task.description;
    document.getElementById('editInstructions').value = task.instructions;
    document.getElementById('editTaskUrl').value = task.task_url || '';
    document.getElementById('editReward').value = task.reward;
    document.getElementById('editStatus').value = task.status;
    document.getElementById('editFeatured').checked = task.featured == 1;
    document.getElementById('editShowInSidebar').checked = task.show_in_sidebar == 1;
    
    document.getElementById('editModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
}

function deleteTask(taskId) {
    if (confirm('Delete this task? All submissions will also be deleted. This cannot be undone!')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="task_id" value="${taskId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

function viewTask(taskId) {
    window.location.href = 'task_submissions.php?task_id=' + taskId;
}

function updateVerificationFields(type) {
    const proofSection = document.getElementById('proofSection');
    const quizSection = document.getElementById('quizSection');
    
    if (type === 'proof_required') {
        proofSection.style.display = 'block';
        quizSection.style.display = 'none';
    } else if (type === 'quiz') {
        proofSection.style.display = 'none';
        quizSection.style.display = 'block';
    } else {
        proofSection.style.display = 'none';
        quizSection.style.display = 'none';
    }
}

// Close modals on outside click
document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
        }
    });
});
</script>

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