<section class="bg-white shadow rounded-lg p-6 max-w-screen-4xl mx-auto space-y-6">
    <h2 class="text-lg font-semibold text-gray-700 mb-4">Task Insights</h2>

<?php
$subtasks = isset($subtasks) ? $subtasks : afb_get_subtask_children($parent_task_gid);

// Ensure $subtasks is always an array
if (!is_array($subtasks)) {
    $subtasks = [];
}

$total_subtasks = count($subtasks);
$completed = 0;
$overdue = 0;
$assignee_counts = [];

foreach ($subtasks as $t) {
    if (!empty($t['completed'])) {
        $completed++;
    }

    if (
        empty($t['completed']) &&
        !empty($t['due_on']) &&
        strtotime($t['due_on']) < time()
    ) {
        $overdue++;
    }

    // Check if assignee array is set properly
    $assignee_name = isset($t['assignee']['name']) ? $t['assignee']['name'] : 'Unassigned';
    if (!isset($assignee_counts[$assignee_name])) {
        $assignee_counts[$assignee_name] = 0;
    }
    $assignee_counts[$assignee_name]++;
}

$percent_complete = $total_subtasks ? round(($completed / $total_subtasks) * 100) : 0;
arsort($assignee_counts);
$top_assignee = !empty($assignee_counts) ? key($assignee_counts) : '–';
?>


    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-blue-50 p-4 rounded shadow">
            <h3 class="text-sm font-medium text-gray-600">Total Subtasks</h3>
            <p class="text-2xl font-bold text-blue-600"><?php echo $total_subtasks; ?></p>
        </div>

        <div class="bg-green-50 p-4 rounded shadow">
            <h3 class="text-sm font-medium text-gray-600">Percent Complete</h3>
            <p class="text-2xl font-bold text-green-600"><?php echo $percent_complete; ?>%</p>
        </div>

        <div class="bg-red-50 p-4 rounded shadow">
            <h3 class="text-sm font-medium text-gray-600">Overdue Subtasks</h3>
            <p class="text-2xl font-bold text-red-600"><?php echo $overdue; ?></p>
        </div>

        <div class="bg-purple-50 p-4 rounded shadow">
            <h3 class="text-sm font-medium text-gray-600">Top Assignee</h3>
            <p class="text-lg font-semibold text-purple-600"><?php echo esc_html($top_assignee); ?></p>
        </div>
    </div>

<div class="p-4 border rounded bg-gray-50">
    <h3 class="font-medium text-sm text-gray-600 mb-2">Completion Progress</h3>
    <div class="w-full bg-gray-200 rounded-full h-3">
        <div class="bg-green-500 h-3 rounded-full" style="width: <?= $percent_complete ?>%;"></div>
    </div>
    <p class="mt-1 text-xs text-gray-500"><?= $percent_complete ?>% complete (<?= $completed ?>/<?= $total_subtasks ?> subtasks)</p>
</div>


<script>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('completionChart').getContext('2d');
    const completed = <?= $completed ?>;
    const remaining = <?= $total_subtasks - $completed ?>;

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Completed', 'Remaining'],
            datasets: [{
                data: [completed, remaining],
                backgroundColor: ['#34D399', '#E5E7EB'], // green + light gray
                borderWidth: 1
            }]
        },
        options: {
            plugins: {
                legend: { display: true },
            },
            cutout: '60%',
        }
    });
});
</script>


    <div class="p-4 border rounded bg-gray-50">
        <h3 class="font-medium text-sm text-gray-600 mb-2">AI Task Summary</h3>
        <p class="text-sm text-gray-600 italic">
            "This request relates to <?php echo esc_html(isset($primary_project) ? $primary_project : '–'); ?> and contains <?php echo $total_subtasks; ?> subtasks. Assigned to <?php echo esc_html(isset($assignee) ? $assignee : 'Unassigned'); ?>."
        </p>
    </div>

    <div class="p-4 border rounded bg-gray-50">
        <h3 class="font-medium text-sm text-gray-600 mb-2">Response SLA</h3>
        <ul class="text-sm text-gray-600 space-y-1">
            <li><strong>Submitted:</strong> <?php echo !empty($created_at) ? esc_html(date('M j, Y g:i A', strtotime($created_at))) : '–'; ?></li>
            <li><strong>First comment:</strong>
                <?php echo !empty($comments[0]['created_at']) ? esc_html(date('M j, Y g:i A', strtotime($comments[0]['created_at']))) : '–'; ?>
            </li>
            <li><strong>Response Time:</strong>
                <?php
                if (!empty($comments[0]['created_at']) && !empty($created_at)) {
                    $first_comment_time = strtotime($comments[0]['created_at']);
                    $response_seconds = $first_comment_time - strtotime($created_at);
                    $response_hours = round($response_seconds / 3600, 1);
                    echo $response_hours . ' hours';
                } else {
                    echo 'No response yet';
                }
                ?>
            </li>
        </ul>
    </div>
</section>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
