<!-- TAB 0: ANALYTICS -->
    <div class="tab-pane fade <?= $activeTab=='analytics'?'show active':'' ?>" id="analytics" role="tabpanel">
        <div class="row mb-4 align-items-center">
            <div class="col-md-6">
                <h4 class="fw-bold text-dark"><i class="fa-solid fa-brain text-primary me-2"></i> الذكاء المالي والتحليل</h4>
            </div>
            <div class="col-md-6 text-md-end">
                <div class="btn-group shadow-sm">
                    <a href="?tab=analytics&timeframe=30" class="btn <?= (!isset($_GET['timeframe']) || $_GET['timeframe'] == 30) ? 'btn-primary fw-bold' : 'btn-light' ?>">آخر 30 يوماً</a>
                    <a href="?tab=analytics&timeframe=current_month" class="btn <?= (isset($_GET['timeframe']) && $_GET['timeframe'] == 'current_month') ? 'btn-primary fw-bold' : 'btn-light' ?>">الشهر الحالي</a>
                </div>
            </div>
        </div>

        <!-- Metrics Overview -->
        <div class="row mb-4 g-3">
            <div class="col-md-3 col-6">
                <div class="card card-saas h-100 p-3 bg-light">
                    <div class="text-secondary small fw-bold mb-1"><i class="fa-solid fa-arrow-down text-success"></i> إجمالي الدخل</div>
                    <div class="fs-4 fw-bold text-dark"><?= number_format($financeAnalysis['metrics']['total_income']) ?> <small>ج.م</small></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card card-saas h-100 p-3 bg-light">
                    <div class="text-secondary small fw-bold mb-1"><i class="fa-solid fa-arrow-up text-danger"></i> إجمالي الصرف</div>
                    <div class="fs-4 fw-bold text-dark"><?= number_format($financeAnalysis['metrics']['total_expenses']) ?> <small>ج.م</small></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card card-saas h-100 p-3 bg-light">
                    <div class="text-secondary small fw-bold mb-1"><i class="fa-solid fa-scale-balanced text-primary"></i> المحصلة (الفائض)</div>
                    <div class="fs-4 fw-bold text-<?= $financeAnalysis['metrics']['surplus'] >= 0 ? 'success' : 'danger' ?>"><?= number_format($financeAnalysis['metrics']['surplus']) ?> <small>ج.م</small></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card card-saas h-100 p-3 <?= $financeAnalysis['metrics']['savings_rate'] > 20 ? 'bg-success-subtle' : ($financeAnalysis['metrics']['savings_rate'] < 5 ? 'bg-danger-subtle' : 'bg-warning-subtle') ?>">
                    <div class="text-secondary small fw-bold mb-1"><i class="fa-solid fa-piggy-bank"></i> معدل الادخار</div>
                    <div class="fs-4 fw-bold text-dark"><?= $financeAnalysis['metrics']['savings_rate'] ?>% <span class="badge bg-white text-dark ms-2"><?= $financeAnalysis['metrics']['status'] == 'good' ? 'ممتاز' : 'خطر' ?></span></div>
                </div>
            </div>
        </div>

        <!-- Smart Insights Row -->
        <?php if (!empty($financeAnalysis['insights'])): ?>
        <div class="row mb-4">
            <?php foreach($financeAnalysis['insights'] as $insight): ?>
                <div class="col-md-4 mb-3">
                    <div class="card card-saas border-start border-4 border-<?= $insight['type'] ?> h-100 bg-<?= $insight['type'] ?>-subtle">
                        <div class="card-body">
                            <h6 class="fw-bold text-<?= $insight['type'] ?> mb-2"><i class="fa-solid fa-bell me-1"></i> <?= $insight['title'] ?></h6>
                            <p class="mb-0 text-dark small fw-semibold"><?= $insight['text'] ?></p>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Visual Analytics Row -->
        <div class="row mb-4 justify-content-center">
            <div class="col-md-6 mb-4">
                <div class="card card-saas h-100 p-3">
                    <div class="card-body text-center">
                        <h5 class="fw-bold mb-4 text-secondary"><i class="fa-solid fa-chart-pie me-2 text-primary"></i> هيكل المصروفات</h5>
                        <div style="position: relative; height: 220px; width: 100%; display: flex; justify-content: center;">
                            <canvas id="financePieChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- NEW: Per-Account Monthly Breakdown -->
        <div class="card card-saas p-4 mb-5">
            <h5 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-file-invoice-dollar text-primary me-2"></i> تحليل المصروفات حسب الحساب (هذا الشهر)</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle border-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="border-0 rounded-start">اسم الحساب</th>
                            <th class="border-0">إجمالي الصرف</th>
                            <th class="border-0">عدد العمليات</th>
                            <th class="border-0 rounded-end">النسبة من الإجمالي</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $totalMonthSpent = array_sum(array_column($accountAnalysis, 'total_spent')) ?: 1;
                        foreach($accountAnalysis as $acc): 
                            $percent = round(($acc->total_spent / $totalMonthSpent) * 100);
                        ?>
                        <tr>
                            <td class="fw-bold text-dark"><?= htmlspecialchars($acc->category) ?></td>
                            <td class="fw-bold text-danger"><?= number_format($acc->total_spent) ?> ج.م</td>
                            <td class="text-muted fw-bold"><?= $acc->txn_count ?></td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div class="progress flex-grow-1" style="height: 6px;">
                                        <div class="progress-bar bg-primary" style="width: <?= $percent ?>%"></div>
                                    </div>
                                    <span class="small fw-bold text-secondary"><?= $percent ?>%</span>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($accountAnalysis)): ?>
                        <tr><td colspan="4" class="text-center py-4 text-muted">لا توجد مصروفات مسجلة لهذا الشهر حتى الآن.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Budgets -->
        <?php if (!empty($financeAnalysis['budgets'])): ?>
        <div class="card card-saas p-4 mb-4">
            <h5 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-scale-balanced me-2 text-primary"></i> رصد الميزانيات المخصصة</h5>
            <div class="row">
                <?php foreach($financeAnalysis['budgets'] as $budget): ?>
                    <div class="col-md-6 mb-4">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="fw-bold"><?= htmlspecialchars($budget['category']) ?> <span class="badge bg-light text-secondary ms-2">الحد: <?= number_format($budget['limit']) ?></span></span>
                            <span class="text-<?= $budget['status'] ?> fw-bold"><?= $budget['percent'] ?>%</span>
                        </div>
                        <div class="progress" style="height: 12px; border-radius: 6px; background-color: #f1f5f9;">
                            <div class="progress-bar bg-<?= $budget['status'] ?>" role="progressbar" style="width: <?= $budget['percent'] ?>%;"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-2 small text-secondary">
                            <span>المستخدم: <?= number_format($budget['used']) ?> ج.م</span>
                            <span>المتبقي: <strong class="text-dark"><?= number_format($budget['remaining']) ?> ج.م</strong></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Goals -->
        <?php if (!empty($financeAnalysis['goals'])): ?>
        <div class="card card-saas p-4 mb-4">
            <h5 class="fw-bold mb-4 text-dark"><i class="fa-solid fa-bullseye me-2 text-primary"></i> تتبع أهداف الادخار النشطة</h5>
            <div class="row">
                <?php foreach($financeAnalysis['goals'] as $goal): ?>
                    <div class="col-md-6 mb-4">
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span class="fw-bold fs-6"><?= htmlspecialchars($goal['title']) ?> 
                                <span class="badge bg-<?= $goal['urgency_color'] ?>-subtle text-<?= $goal['urgency_color'] ?> ms-2" style="font-size: 0.75rem;">
                                    <?php
                                        if ($goal['urgency'] === 'urgent') echo 'عاجل (وقت قصير)';
                                        elseif ($goal['urgency'] === 'normal') echo 'متوسط (وقت معتدل)';
                                        else echo 'آمن (وقت كافي)';
                                    ?>
                                </span>
                            </span>
                            <span class="text-<?= $goal['on_track'] ? 'success' : 'danger' ?> fw-bold"><?= $goal['percent'] ?>%</span>
                        </div>
                        <div class="progress" style="height: 12px; border-radius: 6px; background-color: #f1f5f9;">
                            <div class="progress-bar bg-<?= $goal['on_track'] ? 'success' : 'danger' ?>" role="progressbar" style="width: <?= $goal['percent'] ?>%;"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-2 small text-secondary">
                            <span>المدخر: <?= number_format($goal['current']) ?> <span class="text-muted">من</span> <?= number_format($goal['target']) ?> ج.م</span>
                            <?php if (!$goal['on_track']): ?>
                                <span class="text-danger fw-bold" title="القسط الشهري المطلوب: <?= number_format($goal['required_monthly']) ?> ج.م"><i class="fa-solid fa-triangle-exclamation"></i> الادخار لا يكفي</span>
                            <?php else: ?>
                                <span class="text-success"><i class="fa-solid fa-check-circle"></i> المسار سليم</span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    
