<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

// Initialize database connection
if (!isset($conn)) {
    $conn = getConnection();
}
if (!isset($conn)) {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
}

// Check admin authentication
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$adminId = $_SESSION['admin_id'];
$pageTitle = 'Task Submissions';

// Get filter status
$status = $_GET['status'] ?? 'pending';
$validStatuses = ['pending', 'approved', 'rejected'];
if (!in_array($status, $validStatuses)) {
    $status = 'pending';
}

// Get submissions with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Count total submissions
$countQuery = "
    SELECT COUNT(*) as total
    FROM task_completions tc
    WHERE tc.status = ?
";
$stmt = $conn->prepare($countQuery);
$stmt->bind_param("s", $status);
$stmt->execute();
$totalSubmissions = $stmt->get_result()->fetch_assoc()['total'];
$totalPages = ceil($totalSubmissions / $perPage);

// Get submissions
$query = "
    SELECT 
        tc.*,
        t.title as task_title,
        t.reward as task_reward,
        t.category as task_category,
        t.description as task_description,
        u.username,
        u.email,
        u.phone
    FROM task_completions tc
    JOIN tasks t ON tc.task_id = t.id
    JOIN users u ON tc.user_id = u.id
    WHERE tc.status = ?
    ORDER BY tc.completed_at DESC
    LIMIT ? OFFSET ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("sii", $status, $perPage, $offset);
$stmt->execute();
$submissions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get counts for badges
$pendingCount = $conn->query("SELECT COUNT(*) as count FROM task_completions WHERE status='pending'")->fetch_assoc()['count'];
$approvedCount = $conn->query("SELECT COUNT(*) as count FROM task_completions WHERE status='approved'")->fetch_assoc()['count'];
$rejectedCount = $conn->query("SELECT COUNT(*) as count FROM task_completions WHERE status='rejected'")->fetch_assoc()['count'];


include 'side.php';
?>

<style>
    .dashboard-container {
        padding: 20px;
    }
    
    .page-header {
        margin-bottom: 30px;
    }
    
    .page-title {
        font-size: 28px;
        font-weight: 900;
        color: var(--text-primary);
        margin-bottom: 6px;
    }
    
    .page-subtitle {
        color: var(--text-secondary);
        font-size: 14px;
    }
    
    .status-tabs {
        display: flex;
        gap: 12px;
        margin-bottom: 30px;
        flex-wrap: wrap;
    }
    
    .status-tab {
        padding: 12px 24px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        color: var(--text-secondary);
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .status-tab:hover {
        background: var(--darker-bg);
        color: var(--text-primary);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .status-tab.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-color: transparent;
    }
    
    .badge {
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }
    
    .badge-count {
        background: rgba(239, 68, 68, 0.9);
        color: white;
        font-size: 11px;
        font-weight: 700;
        padding: 2px 8px;
        border-radius: 12px;
        min-width: 20px;
        text-align: center;
    }
    
    .status-tab.active .badge-count {
        background: rgba(255, 255, 255, 0.3);
    }
    
    .badge-pending {
        background: rgba(245, 158, 11, 0.15);
        color: #f59e0b;
    }
    
    .badge-approved {
        background: rgba(16, 185, 129, 0.15);
        color: #10b981;
    }
    
    .badge-rejected {
        background: rgba(239, 68, 68, 0.15);
        color: #ef4444;
    }
    
    .submissions-grid {
        display: grid;
        gap: 20px;
    }
    
    .submission-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 20px;
        transition: all 0.3s;
    }
    
    .submission-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        border-color: #667eea;
    }
    
    .submission-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;
        gap: 16px;
    }
    
    .submission-info {
        flex: 1;
    }
    
    .task-title {
        font-size: 16px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .task-meta {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        font-size: 12px;
        color: var(--text-secondary);
    }
    
    .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
    }
    
    .meta-item i {
        color: #667eea;
    }
    
    .reward-badge {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
        padding: 8px 16px;
        border-radius: 8px;
        font-size: 15px;
        font-weight: 700;
        white-space: nowrap;
        flex-shrink: 0;
    }
    
    .user-info {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        background: var(--darker-bg);
        border-radius: 8px;
        margin-bottom: 16px;
    }
    
    .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 700;
        font-size: 16px;
        flex-shrink: 0;
    }
    
    .user-details {
        flex: 1;
    }
    
    .user-name {
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
    }
    
    .user-contact {
        font-size: 12px;
        color: var(--text-secondary);
        margin-top: 2px;
    }
    
    .proof-section {
        margin-bottom: 16px;
    }
    
    .proof-label {
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        color: var(--text-secondary);
        margin-bottom: 8px;
    }
    
    .proof-text {
        background: var(--darker-bg);
        padding: 12px;
        border-radius: 8px;
        font-size: 13px;
        color: var(--text-primary);
        line-height: 1.6;
        margin-bottom: 12px;
    }
    
    .proof-screenshot {
        width: 100%;
        max-width: 300px;
        border-radius: 8px;
        border: 1px solid var(--border-color);
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .proof-screenshot:hover {
        transform: scale(1.02);
        border-color: #667eea;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
    
    .no-screenshot {
        padding: 20px;
        text-align: center;
        background: var(--darker-bg);
        border-radius: 8px;
        color: var(--text-secondary);
        font-size: 13px;
    }
    
    .submission-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 16px;
        border-top: 1px solid var(--border-color);
        gap: 12px;
        flex-wrap: wrap;
    }
    
    .submission-date {
        font-size: 12px;
        color: var(--text-secondary);
    }
    
    .action-buttons {
        display: flex;
        gap: 8px;
    }
    
    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        text-decoration: none;
    }
    
    .btn-sm {
        padding: 6px 12px;
        font-size: 12px;
    }
    
    .btn-approve {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
    }
    
    .btn-approve:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    }
    
    .btn-reject {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: white;
    }
    
    .btn-reject:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.7);
        z-index: 10000;
        align-items: center;
        justify-content: center;
    }
    
    .modal.show {
        display: flex;
    }
    
    .modal-content {
        background: var(--card-bg);
        border-radius: 12px;
        padding: 24px;
        max-width: 500px;
        width: 90%;
        max-height: 90vh;
        overflow-y: auto;
        animation: modalSlideIn 0.3s ease-out;
    }
    
    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    
    .modal-title {
        font-size: 18px;
        font-weight: 700;
        color: var(--text-primary);
    }
    
    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 0;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        transition: all 0.3s;
    }
    
    .modal-close:hover {
        background: var(--darker-bg);
        color: var(--text-primary);
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 8px;
    }
    
    .form-control {
        width: 100%;
        padding: 10px;
        border: 1px solid var(--border-color);
        border-radius: 6px;
        font-size: 13px;
        background: var(--darker-bg);
        color: var(--text-primary);
        resize: vertical;
        min-height: 100px;
    }
    
    .form-control:focus {
        outline: none;
        border-color: #667eea;
    }
    
    .modal-actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;
    }
    
    .btn-cancel {
        background: var(--darker-bg);
        color: var(--text-primary);
        border: 1px solid var(--border-color);
    }
    
    .btn-cancel:hover {
        background: var(--border-color);
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: var(--text-secondary);
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
    }
    
    .empty-state i {
        font-size: 64px;
        opacity: 0.3;
        margin-bottom: 16px;
        color: #667eea;
    }
    
    .empty-state h3 {
        font-size: 18px;
        font-weight: 700;
        margin-bottom: 8px;
        color: var(--text-primary);
    }
    
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
        margin-top: 30px;
    }
    
    .page-btn {
        padding: 8px 14px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        color: var(--text-primary);
        text-decoration: none;
    }
    
    .page-btn:hover {
        background: #667eea;
        color: white;
        border-color: #667eea;
        transform: translateY(-2px);
    }
    
    .page-btn.active {
        background: #667eea;
        color: white;
        border-color: #667eea;
    }
    
    .page-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    .rejection-reason {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.3);
        padding: 12px;
        border-radius: 8px;
        margin-top: 12px;
    }
    
    .rejection-label {
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        color: #ef4444;
        margin-bottom: 6px;
    }
    
    .rejection-text {
        font-size: 13px;
        color: var(--text-primary);
    }
    
    .loading {
        pointer-events: none;
        opacity: 0.6;
    }
    
    .btn-approve.loading::after,
    .btn-reject.loading::after {
        content: '';
        width: 12px;
        height: 12px;
        border: 2px solid white;
        border-top-color: transparent;
        border-radius: 50%;
        animation: spin 0.6s linear infinite;
        margin-left: 6px;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    
    @media (max-width: 768px) {
        .dashboard-container {
            padding: 12px;
        }
        
        .submission-header {
            flex-direction: column;
        }
        
        .reward-badge {
            align-self: flex-start;
        }
        
        .submission-footer {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .action-buttons {
            width: 100%;
        }
        
        .btn {
            flex: 1;
        }
    }
</style>

<div class="dashboard-container">
    <!-- Page Header -->
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-clipboard-list"></i> Task Submissions
        </h1>
        <p class="page-subtitle">Review and approve user task submissions</p>
    </div>
    
    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="?status=pending" class="status-tab <?php echo $status === 'pending' ? 'active' : ''; ?>">
            <i class="fas fa-clock"></i> Pending
            <?php if ($pendingCount > 0): ?>
                <span class="badge-count"><?php echo $pendingCount; ?></span>
            <?php endif; ?>
        </a>
        <a href="?status=approved" class="status-tab <?php echo $status === 'approved' ? 'active' : ''; ?>">
            <i class="fas fa-check-circle"></i> Approved
            <?php if ($approvedCount > 0): ?>
                <span class="badge-count"><?php echo $approvedCount; ?></span>
            <?php endif; ?>
        </a>
        <a href="?status=rejected" class="status-tab <?php echo $status === 'rejected' ? 'active' : ''; ?>">
            <i class="fas fa-times-circle"></i> Rejected
            <?php if ($rejectedCount > 0): ?>
                <span class="badge-count"><?php echo $rejectedCount; ?></span>
            <?php endif; ?>
        </a>
    </div>

    <?php if (empty($submissions)): ?>
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <h3>No <?php echo ucfirst($status); ?> Submissions</h3>
            <p>There are currently no <?php echo $status; ?> task submissions.</p>
        </div>
    <?php else: ?>
        <div class="submissions-grid">
            <?php foreach ($submissions as $submission): 
                $proofData = json_decode($submission['proof_data'], true);
                $proofText = $proofData['text'] ?? '';
                $proofScreenshot = $proofData['screenshot'] ?? '';
            ?>
                <div class="submission-card" data-id="<?php echo $submission['id']; ?>">
                    <div class="submission-header">
                        <div class="submission-info">
                            <div class="task-title">
                                <i class="fas fa-tasks"></i>
                                <?php echo htmlspecialchars($submission['task_title']); ?>
                            </div>
                            <div class="task-meta">
                                <span class="meta-item">
                                    <i class="fas fa-tag"></i>
                                    <?php echo htmlspecialchars($submission['task_category']); ?>
                                </span>
                                <span class="meta-item">
                                    <i class="fas fa-clock"></i>
                                    <?php echo date('M j, Y g:i A', strtotime($submission['completed_at'])); ?>
                                </span>
                            </div>
                        </div>
                        <div class="reward-badge">
                            KSH <?php echo number_format($submission['task_reward'], 2); ?>
                        </div>
                    </div>

                    <div class="user-info">
                        <div class="user-avatar">
                            <?php echo strtoupper(substr($submission['username'], 0, 1)); ?>
                        </div>
                        <div class="user-details">
                            <div class="user-name"><?php echo htmlspecialchars($submission['username']); ?></div>
                            <div class="user-contact">
                                <?php echo htmlspecialchars($submission['email']); ?> • 
                                <?php echo htmlspecialchars($submission['phone']); ?>
                            </div>
                        </div>
                    </div>

                    <div class="proof-section">
                        <?php if (!empty($proofText)): ?>
                            <div class="proof-label">Proof Text:</div>
                            <div class="proof-text"><?php echo nl2br(htmlspecialchars($proofText)); ?></div>
                        <?php endif; ?>

                        <?php if (!empty($proofScreenshot)): ?>
                            <div class="proof-label">Screenshot:</div>
                            <img src="../<?php echo htmlspecialchars($proofScreenshot); ?>" 
                                 alt="Proof Screenshot" 
                                 class="proof-screenshot"
                                 onclick="window.open('../<?php echo htmlspecialchars($proofScreenshot); ?>', '_blank')">
                        <?php else: ?>
                            <div class="no-screenshot">
                                <i class="fas fa-image"></i> No screenshot provided
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if ($status === 'rejected' && !empty($submission['rejection_reason'])): ?>
                        <div class="rejection-reason">
                            <div class="rejection-label">Rejection Reason:</div>
                            <div class="rejection-text"><?php echo htmlspecialchars($submission['rejection_reason']); ?></div>
                        </div>
                    <?php endif; ?>

                    <div class="submission-footer">
                        <div class="submission-date">
                            <i class="fas fa-calendar"></i> Submitted: <?php echo timeAgo($submission['completed_at']); ?>
                            <?php if ($submission['reviewed_at']): ?>
                                <br><i class="fas fa-check"></i> Reviewed: <?php echo timeAgo($submission['reviewed_at']); ?>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($status === 'pending'): ?>
                            <div class="action-buttons">
                                <button class="btn btn-approve" onclick="approveSubmission(<?php echo $submission['id']; ?>, <?php echo $submission['task_id']; ?>, <?php echo $submission['user_id']; ?>, <?php echo $submission['task_reward']; ?>, '<?php echo addslashes($submission['task_category']); ?>')">
                                    <i class="fas fa-check"></i> Approve
                                </button>
                                <button class="btn btn-reject" onclick="openRejectModal(<?php echo $submission['id']; ?>)">
                                    <i class="fas fa-times"></i> Reject
                                </button>
                            </div>
                        <?php elseif ($status === 'approved'): ?>
                            <span class="badge badge-approved">
                                <i class="fas fa-check-circle"></i> Approved
                            </span>
                        <?php else: ?>
                            <span class="badge badge-rejected">
                                <i class="fas fa-times-circle"></i> Rejected
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?status=<?php echo $status; ?>&page=<?php echo $page - 1; ?>" class="page-btn">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                        <a href="?status=<?php echo $status; ?>&page=<?php echo $i; ?>" 
                           class="page-btn <?php echo $i == $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                        <span class="page-btn" style="pointer-events: none;">...</span>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <a href="?status=<?php echo $status; ?>&page=<?php echo $page + 1; ?>" class="page-btn">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Rejection Modal -->
<div id="rejectModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Reject Submission</h3>
            <button class="modal-close" onclick="closeRejectModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="rejectForm">
            <input type="hidden" id="rejectSubmissionId" name="submission_id">
            <div class="form-group">
                <label class="form-label">Rejection Reason *</label>
                <textarea class="form-control" 
                          id="rejectionReason" 
                          name="rejection_reason" 
                          placeholder="Please provide a clear reason for rejection..."
                          required></textarea>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-cancel" onclick="closeRejectModal()">Cancel</button>
                <button type="submit" class="btn btn-reject">
                    <i class="fas fa-times"></i> Confirm Rejection
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function approveSubmission(submissionId, taskId, userId, reward, category) {
    if (!confirm('Are you sure you want to approve this submission?')) {
        return;
    }

    const btn = event.target.closest('.btn-approve');
    btn.classList.add('loading');
    btn.disabled = true;

    fetch('ajax/approve_task.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            submission_id: submissionId,
            task_id: taskId,
            user_id: userId,
            reward: reward,
            category: category
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Task approved successfully!');
            location.reload();
        } else {
            alert(data.message || 'Failed to approve task');
            btn.classList.remove('loading');
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred');
        btn.classList.remove('loading');
        btn.disabled = false;
    });
}

function openRejectModal(submissionId) {
    document.getElementById('rejectSubmissionId').value = submissionId;
    document.getElementById('rejectionReason').value = '';
    document.getElementById('rejectModal').classList.add('show');
}

function closeRejectModal() {
    document.getElementById('rejectModal').classList.remove('show');
}

document.getElementById('rejectForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const submissionId = document.getElementById('rejectSubmissionId').value;
    const reason = document.getElementById('rejectionReason').value;
    
    const btn = e.target.querySelector('.btn-reject');
    btn.classList.add('loading');
    btn.disabled = true;

    fetch('ajax/reject_task.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            submission_id: submissionId,
            rejection_reason: reason
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Task rejected successfully');
            location.reload();
        } else {
            alert(data.message || 'Failed to reject task');
            btn.classList.remove('loading');
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred');
        btn.classList.remove('loading');
        btn.disabled = false;
    });
});

// Close modal on outside click
document.getElementById('rejectModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeRejectModal();
    }
});
</script>

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