<?php $__env->startSection('content'); ?>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Header -->
    <div class="mb-6 flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">👤 <?php echo e($user->name); ?>'s Performance</h1>
            <p class="text-gray-600 dark:text-gray-400"><?php echo e($year); ?> Performance Dashboard</p>
        </div>
        <div>
            <a href="<?php echo e(route('forecasting.seller-kpi.index')); ?>" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-md">
                Back to All Sellers
            </a>
        </div>
    </div>

    <?php echo $__env->make('forecasting.partials.navigation', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <!-- YTD Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Sales (YTD)</div>
            <div class="text-2xl font-bold text-gray-800 dark:text-white">
                RM <?php echo e(number_format($ytdStats['total_sales'], 2)); ?>

            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Orders (YTD)</div>
            <div class="text-2xl font-bold text-gray-800 dark:text-white">
                <?php echo e(number_format($ytdStats['total_orders'])); ?>

            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-600 dark:text-gray-400 mb-1">Avg Achievement</div>
            <div class="text-2xl font-bold <?php echo e($ytdStats['avg_achievement'] >= 100 ? 'text-green-600' : 'text-orange-600'); ?>">
                <?php echo e(number_format($ytdStats['avg_achievement'], 1)); ?>%
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-600 dark:text-gray-400 mb-1">Avg Order Value</div>
            <div class="text-2xl font-bold text-gray-800 dark:text-white">
                RM <?php echo e(number_format($ytdStats['avg_aov'], 2)); ?>

            </div>
        </div>
    </div>

    <!-- Best/Worst Months -->
    <?php if($ytdStats['best_month'] || $ytdStats['worst_month']): ?>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <?php if($ytdStats['best_month']): ?>
        <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
            <div class="text-sm font-medium text-green-800 dark:text-green-400 mb-2">Best Month</div>
            <div class="text-lg font-bold text-green-900 dark:text-green-300">
                <?php echo e($ytdStats['best_month']->month_name); ?>: RM <?php echo e(number_format($ytdStats['best_month']->actual_sales, 2)); ?>

            </div>
        </div>
        <?php endif; ?>

        <?php if($ytdStats['worst_month']): ?>
        <div class="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4">
            <div class="text-sm font-medium text-orange-800 dark:text-orange-400 mb-2">Needs Improvement</div>
            <div class="text-lg font-bold text-orange-900 dark:text-orange-300">
                <?php echo e($ytdStats['worst_month']->month_name); ?>: RM <?php echo e(number_format($ytdStats['worst_month']->actual_sales, 2)); ?>

            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Sales Breakdown by Channel -->
    <?php if($salesBreakdown): ?>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-xl font-bold text-gray-800 dark:text-white mb-4">Sales Breakdown by Channel (<?php echo e($year); ?>)</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <!-- Orders (Checkout/Sales Pages/Webstore) -->
            <div class="border border-blue-200 dark:border-blue-800 rounded-lg p-4 bg-blue-50 dark:bg-blue-900/20">
                <div class="text-sm text-blue-800 dark:text-blue-400 mb-1"><?php echo e($salesBreakdown['orders']['label']); ?></div>
                <div class="text-2xl font-bold text-blue-900 dark:text-blue-300">
                    RM <?php echo e(number_format($salesBreakdown['orders']['total'], 2)); ?>

                </div>
                <div class="text-xs text-blue-700 dark:text-blue-400 mt-1">
                    <?php echo e(number_format($salesBreakdown['orders']['count'])); ?> orders
                </div>
            </div>

            <!-- TikTok Shop -->
            <div class="border border-purple-200 dark:border-purple-800 rounded-lg p-4 bg-purple-50 dark:bg-purple-900/20">
                <div class="text-sm text-purple-800 dark:text-purple-400 mb-1"><?php echo e($salesBreakdown['tiktok']['label']); ?></div>
                <div class="text-2xl font-bold text-purple-900 dark:text-purple-300">
                    RM <?php echo e(number_format($salesBreakdown['tiktok']['total'], 2)); ?>

                </div>
                <div class="text-xs text-purple-700 dark:text-purple-400 mt-1">
                    <?php echo e(number_format($salesBreakdown['tiktok']['count'])); ?> orders
                </div>
            </div>

            <!-- Total -->
            <div class="border border-green-200 dark:border-green-800 rounded-lg p-4 bg-green-50 dark:bg-green-900/20">
                <div class="text-sm text-green-800 dark:text-green-400 mb-1">Total (All Channels)</div>
                <div class="text-2xl font-bold text-green-900 dark:text-green-300">
                    RM <?php echo e(number_format($salesBreakdown['grand_total'], 2)); ?>

                </div>
                <div class="text-xs text-green-700 dark:text-green-400 mt-1">
                    <?php echo e(number_format($salesBreakdown['orders']['count'] + $salesBreakdown['tiktok']['count'])); ?> orders
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ========== MANAGER DASHBOARD SECTIONS ========== -->
    <?php if($user->isManager() && $teamYtdSummary): ?>

    <!-- Team YTD Summary Cards -->
    <div class="bg-gradient-to-r from-purple-500 to-purple-700 rounded-lg shadow-lg p-6 mb-6 text-white">
        <h2 class="text-xl font-bold mb-4">Team Overview (<?php echo e($year); ?> YTD)</h2>
        <p class="text-sm text-purple-100 mb-4">
            <strong>Note:</strong> Team sales shown below are for reference only and NOT included in your personal KPI above.
        </p>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="bg-white/10 backdrop-blur rounded-lg p-4">
                <div class="text-sm text-purple-100 mb-1">Team Total Sales</div>
                <div class="text-2xl font-bold">
                    RM <?php echo e(number_format($teamYtdSummary['total_sales'], 2)); ?>

                </div>
            </div>

            <div class="bg-white/10 backdrop-blur rounded-lg p-4">
                <div class="text-sm text-purple-100 mb-1">Team Total Orders</div>
                <div class="text-2xl font-bold">
                    <?php echo e(number_format($teamYtdSummary['total_orders'])); ?>

                </div>
            </div>

            <div class="bg-white/10 backdrop-blur rounded-lg p-4">
                <div class="text-sm text-purple-100 mb-1">Team Size</div>
                <div class="text-2xl font-bold">
                    <?php echo e($teamYtdSummary['team_size']); ?> Members
                </div>
            </div>

            <div class="bg-white/10 backdrop-blur rounded-lg p-4">
                <div class="text-sm text-purple-100 mb-1">Top Performer</div>
                <div class="text-lg font-bold">
                    <?php echo e($teamYtdSummary['top_performer']['name'] ?? 'N/A'); ?>

                </div>
                <?php if($teamYtdSummary['top_performer']): ?>
                <div class="text-xs text-purple-200">
                    RM <?php echo e(number_format($teamYtdSummary['top_performer']['total'], 2)); ?>

                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Monthly Team Performance Table -->
    <?php if($teamMonthlyPerformance && count($teamMonthlyPerformance) > 0): ?>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-xl font-bold text-gray-800 dark:text-white mb-4">Monthly Team Performance</h2>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Month</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Orders/Webstore</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">TikTok Shop</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Total Sales</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Orders</th>
                        <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Action</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    <?php $__currentLoopData = $teamMonthlyPerformance; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $monthData): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                            <?php echo e($monthData['month_name']); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-blue-600 dark:text-blue-400">
                            RM <?php echo e(number_format($monthData['orders_sales'], 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-purple-600 dark:text-purple-400">
                            RM <?php echo e(number_format($monthData['tiktok_sales'], 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right font-semibold text-gray-900 dark:text-white">
                            RM <?php echo e(number_format($monthData['total_sales'], 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            <?php echo e(number_format($monthData['total_orders'])); ?>

                        </td>
                        <td class="px-4 py-3 text-center">
                            <a href="<?php echo e(route('forecasting.seller-kpi.show', ['userId' => $user->id, 'year' => $year, 'month' => $monthData['month']])); ?>"
                               class="text-blue-600 hover:text-blue-800 text-sm <?php echo e($selectedMonth == $monthData['month'] ? 'font-bold underline' : ''); ?>">
                                View Details
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <tr class="bg-gray-100 dark:bg-gray-700 font-bold">
                        <td class="px-4 py-3 text-sm text-gray-900 dark:text-white">YTD Total</td>
                        <td class="px-4 py-3 text-sm text-right text-blue-700 dark:text-blue-300">
                            RM <?php echo e(number_format(collect($teamMonthlyPerformance)->sum('orders_sales'), 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-purple-700 dark:text-purple-300">
                            RM <?php echo e(number_format(collect($teamMonthlyPerformance)->sum('tiktok_sales'), 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-900 dark:text-white">
                            RM <?php echo e(number_format(collect($teamMonthlyPerformance)->sum('total_sales'), 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            <?php echo e(number_format(collect($teamMonthlyPerformance)->sum('total_orders'))); ?>

                        </td>
                        <td class="px-4 py-3"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- Team Member Breakdown for Selected Month -->
    <?php if($teamBreakdownByMonth && count($teamBreakdownByMonth) > 0): ?>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-bold text-gray-800 dark:text-white">
                Team Breakdown - <?php echo e(date('F', mktime(0, 0, 0, $selectedMonth, 1))); ?> <?php echo e($year); ?>

            </h2>
            <form method="GET" action="<?php echo e(route('forecasting.seller-kpi.show', $user->id)); ?>" class="flex gap-2 items-center">
                <input type="hidden" name="year" value="<?php echo e($year); ?>">
                <label class="text-sm text-gray-600 dark:text-gray-400">Select Month:</label>
                <select name="month" onchange="this.form.submit()" class="form-select rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm">
                    <?php $__currentLoopData = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m => $monthName): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($m + 1); ?>" <?php echo e($selectedMonth == ($m + 1) ? 'selected' : ''); ?>><?php echo e($monthName); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </form>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Team Member</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Orders/Webstore</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">TikTok Shop</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Total</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Orders Count</th>
                        <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">% of Team</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    <?php
                        $monthTeamTotal = collect($teamBreakdownByMonth)->sum('total');
                    ?>
                    <?php $__currentLoopData = $teamBreakdownByMonth; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $member): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                            <?php echo e($member['name']); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-blue-600 dark:text-blue-400">
                            RM <?php echo e(number_format($member['orders_total'], 2)); ?>

                            <div class="text-xs text-gray-500">(<?php echo e($member['orders_count']); ?> orders)</div>
                        </td>
                        <td class="px-4 py-3 text-sm text-right text-purple-600 dark:text-purple-400">
                            RM <?php echo e(number_format($member['tiktok_total'], 2)); ?>

                            <div class="text-xs text-gray-500">(<?php echo e($member['tiktok_count']); ?> orders)</div>
                        </td>
                        <td class="px-4 py-3 text-sm text-right font-semibold text-gray-900 dark:text-white">
                            RM <?php echo e(number_format($member['total'], 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            <?php echo e($member['total_orders']); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            <?php echo e($monthTeamTotal > 0 ? number_format(($member['total'] / $monthTeamTotal) * 100, 1) : 0); ?>%
                        </td>
                    </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <tr class="bg-gray-100 dark:bg-gray-700 font-bold">
                        <td class="px-4 py-3 text-sm text-gray-900 dark:text-white">Month Total</td>
                        <td class="px-4 py-3 text-sm text-right text-blue-700 dark:text-blue-300">
                            RM <?php echo e(number_format(collect($teamBreakdownByMonth)->sum('orders_total'), 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-purple-700 dark:text-purple-300">
                            RM <?php echo e(number_format(collect($teamBreakdownByMonth)->sum('tiktok_total'), 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-900 dark:text-white">
                            RM <?php echo e(number_format($monthTeamTotal, 2)); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            <?php echo e(collect($teamBreakdownByMonth)->sum('total_orders')); ?>

                        </td>
                        <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                            100%
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php endif; ?>
    <!-- ========== END MANAGER DASHBOARD SECTIONS ========== -->

    <!-- Monthly Performance Chart -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-bold text-gray-800 dark:text-white">Monthly Performance - <?php echo e($year); ?></h2>
            <button onclick="generateForecast()" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md text-sm flex items-center gap-2">
                <img src="<?php echo e(asset('images/chatbot-aicon.png')); ?>" alt="AI" class="w-5 h-5">
                Forecast (AI)
            </button>
        </div>
        <canvas id="performanceChart" height="80"></canvas>
    </div>

    <!-- Monthly Breakdown Table -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden mb-6">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h2 class="text-xl font-bold text-gray-800 dark:text-white">Monthly Breakdown</h2>
            <div class="flex gap-2">
                <button id="editModeBtn" onclick="toggleEditMode()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-md flex items-center gap-2 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                    </svg>
                    Edit Past Data
                </button>
                <button id="saveBtn" onclick="saveChanges()" class="hidden px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm rounded-md flex items-center gap-2 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                    </svg>
                    Save
                </button>
                <button id="cancelBtn" onclick="cancelEdit()" class="hidden px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white text-sm rounded-md transition-colors">
                    Cancel
                </button>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Month</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Target</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Actual</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Forecast</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Achievement</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Grade</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Orders</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    <?php $__currentLoopData = $forecasts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $forecast): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                                <?php echo e($forecast->month_name); ?>

                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                                RM <?php echo e(number_format($forecast->target_sales, 2)); ?>

                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-semibold text-gray-900 dark:text-white">
                                <span class="view-mode">RM <?php echo e(number_format($forecast->actual_sales, 2)); ?></span>
                                <input type="number"
                                       class="edit-mode hidden w-full px-2 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                       data-forecast-id="<?php echo e($forecast->id); ?>"
                                       data-field="actual_sales"
                                       data-original="<?php echo e($forecast->actual_sales); ?>"
                                       value="<?php echo e($forecast->actual_sales); ?>"
                                       step="0.01">
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-purple-600 dark:text-purple-400">
                                <?php if($forecast->forecast_sales): ?>
                                    RM <?php echo e(number_format($forecast->forecast_sales, 2)); ?>

                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-semibold <?php echo e($forecast->achievement_percentage >= 100 ? 'text-green-600' : 'text-orange-600'); ?>">
                                <?php echo e(number_format($forecast->achievement_percentage, 1)); ?>%
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <?php
                                    $gradeColors = [
                                        'A' => 'bg-green-100 text-green-800',
                                        'B' => 'bg-blue-100 text-blue-800',
                                        'C' => 'bg-yellow-100 text-yellow-800',
                                        'D' => 'bg-orange-100 text-orange-800',
                                        'F' => 'bg-red-100 text-red-800',
                                    ];
                                ?>
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo e($gradeColors[$forecast->performance_grade] ?? 'bg-gray-100 text-gray-800'); ?>">
                                    <?php echo e($forecast->performance_grade); ?>

                                </span>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                                <span class="view-mode"><?php echo e(number_format($forecast->orders_count)); ?></span>
                                <input type="number"
                                       class="edit-mode hidden w-full px-2 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                       data-forecast-id="<?php echo e($forecast->id); ?>"
                                       data-field="orders_count"
                                       data-original="<?php echo e($forecast->orders_count); ?>"
                                       value="<?php echo e($forecast->orders_count); ?>"
                                       step="1">
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Recent Orders -->
    <?php if($recentOrders->count() > 0): ?>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
            <h2 class="text-xl font-bold text-gray-800 dark:text-white">Recent Orders</h2>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Order ID</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Date</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Amount</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Status</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    <?php $__currentLoopData = $recentOrders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $order): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                                #<?php echo e($order->id); ?>

                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                                <?php echo e($order->created_at->format('M d, Y')); ?>

                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-semibold text-gray-900 dark:text-white">
                                RM <?php echo e(number_format($order->total_price, 2)); ?>

                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm">
                                <span class="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs">
                                    <?php echo e($order->status); ?>

                                </span>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>

<script>
// Performance Chart
const ctx = document.getElementById('performanceChart').getContext('2d');

const chartData = {
    labels: <?php echo json_encode($forecasts->pluck('month_name')); ?>,
    datasets: [
        {
            label: 'Target',
            data: <?php echo json_encode($forecasts->pluck('target_sales')); ?>,
            borderColor: 'rgb(156, 163, 175)',
            backgroundColor: 'rgba(156, 163, 175, 0.1)',
            borderDash: [5, 5],
            tension: 0.4
        },
        {
            label: 'Actual Sales',
            data: <?php echo json_encode($forecasts->pluck('actual_sales')); ?>,
            borderColor: 'rgb(59, 130, 246)',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.4
        },
        {
            label: 'AI Forecast',
            data: <?php echo json_encode($forecasts->pluck('forecast_sales')); ?>,
            borderColor: 'rgb(168, 85, 247)',
            backgroundColor: 'rgba(168, 85, 247, 0.1)',
            borderDash: [3, 3],
            tension: 0.4
        }
    ]
};

new Chart(ctx, {
    type: 'line',
    data: chartData,
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                position: 'top',
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        let label = context.dataset.label || '';
                        if (label) {
                            label += ': ';
                        }
                        if (context.parsed.y !== null) {
                            label += 'RM ' + context.parsed.y.toLocaleString('en-MY', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        }
                        return label;
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return 'RM ' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

// Generate Forecast
function generateForecast() {
    if (!confirm('Generate AI forecast for next 6 months?')) return;

    const button = event.target.closest('button');
    const originalHTML = button.innerHTML;
    button.disabled = true;
    button.innerHTML = 'Generating...';

    fetch('<?php echo e(route("forecasting.seller-kpi.forecast")); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
        },
        body: JSON.stringify({
            user_id: <?php echo e($user->id); ?>,
            periods: 6
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Forecast generated successfully! Trend: ' + data.trend);
            window.location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        alert('Error generating forecast: ' + error);
    })
    .finally(() => {
        button.disabled = false;
        button.innerHTML = originalHTML;
    });
}

// Edit Mode Functions
function toggleEditMode() {
    const viewModes = document.querySelectorAll('.view-mode');
    const editModes = document.querySelectorAll('.edit-mode');
    const editBtn = document.getElementById('editModeBtn');
    const saveBtn = document.getElementById('saveBtn');
    const cancelBtn = document.getElementById('cancelBtn');

    // Toggle visibility
    viewModes.forEach(el => el.classList.add('hidden'));
    editModes.forEach(el => el.classList.remove('hidden'));

    // Toggle buttons
    editBtn.classList.add('hidden');
    saveBtn.classList.remove('hidden');
    cancelBtn.classList.remove('hidden');
}

function cancelEdit() {
    const viewModes = document.querySelectorAll('.view-mode');
    const editModes = document.querySelectorAll('.edit-mode');
    const editBtn = document.getElementById('editModeBtn');
    const saveBtn = document.getElementById('saveBtn');
    const cancelBtn = document.getElementById('cancelBtn');

    // Reset inputs to original values
    editModes.forEach(input => {
        input.value = input.dataset.original;
    });

    // Toggle visibility
    viewModes.forEach(el => el.classList.remove('hidden'));
    editModes.forEach(el => el.classList.add('hidden'));

    // Toggle buttons
    editBtn.classList.remove('hidden');
    saveBtn.classList.add('hidden');
    cancelBtn.classList.add('hidden');
}

async function saveChanges() {
    const saveBtn = document.getElementById('saveBtn');
    const originalHTML = saveBtn.innerHTML;
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<svg class="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Saving...';

    // Collect all changed data
    const updates = [];
    const editInputs = document.querySelectorAll('.edit-mode');

    editInputs.forEach(input => {
        const forecastId = input.dataset.forecastId;
        const field = input.dataset.field;
        const value = parseFloat(input.value) || 0;

        // Find or create update object for this forecast
        let update = updates.find(u => u.id === forecastId);
        if (!update) {
            update = { id: forecastId };
            updates.push(update);
        }

        update[field] = value;
    });

    try {
        const response = await fetch('<?php echo e(route("forecasting.seller-kpi.update-manual")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({ updates: updates })
        });

        const data = await response.json();

        if (data.success) {
            alert('✅ Past data updated successfully! Achievement % and Grades recalculated.');
            window.location.reload();
        } else {
            alert('❌ Error: ' + (data.message || 'Failed to update'));
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalHTML;
        }
    } catch (error) {
        alert('❌ Error saving changes: ' + error.message);
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalHTML;
    }
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\multistore\resources\views/forecasting/seller-kpi/show.blade.php ENDPATH**/ ?>