<?php
/**
 * Finance Dashboard View - SaaS Redesign
 */

// Wallets calculation from live intelligence
$netPersonal = $walletBalances['personal'] ?? 0;
$netBusiness = $walletBalances['business'] ?? 0;
$netSavings  = $walletBalances['savings']  ?? 0;
$netCharity  = $walletBalances['charity']  ?? 0;

$activeTab = $activeTab ?? 'income';

function formatBadge($val, $positiveGreen = true) {
    if ($val > 0) return $positiveGreen ? "<span class='badge bg-success-subtle text-success'>+".number_format($val)."</span>" : "<span class='badge bg-danger-subtle text-danger'>+".number_format($val)."</span>";
    if ($val < 0) return $positiveGreen ? "<span class='badge bg-danger-subtle text-danger'>".number_format($val)."</span>" : "<span class='badge bg-success-subtle text-success'>".number_format($val)."</span>";
    return "<span class='badge bg-light text-dark'>0</span>";
}
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800;900&display=swap');

body { background-color: #f8fafc; }
.finance-dashboard { font-family: 'Cairo', sans-serif; color: #0f172a; }

.card-saas {
    border-radius: 20px;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.04);
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1);
    background: #ffffff;
    overflow: hidden;
}

.card-saas:hover {
    transform: translateY(-6px);
    box-shadow: 0 20px 40px rgba(0,0,0,0.08);
}

/* Cheerful Gradients */
.card-gradient-personal { background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%); } /* Light Green */
.card-gradient-business { background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%); } /* Light Blue */
.card-gradient-savings { background: linear-gradient(135deg, #ffffff 0%, #fdf4ff 100%); } /* Light Pink/Purple */
.card-gradient-charity { background: linear-gradient(135deg, #ffffff 0%, #fffbeb 100%); } /* Light Yellow */

.stats-icon {
    width: 64px; height: 64px;
    display: inline-flex; align-items: center; justify-content: center;
    border-radius: 18px; font-size: 1.75rem;
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.card-saas:hover .stats-icon { transform: scale(1.15) rotate(6deg); }

@keyframes fadeSlideUp { 0% { opacity: 0; transform: translateY(30px); } 100% { opacity: 1; transform: translateY(0); } }
.animate-slide-up { animation: fadeSlideUp 0.7s cubic-bezier(0.16, 1, 0.3, 1) forwards; opacity: 0; }
.delay-1 { animation-delay: 0.05s; }
.delay-2 { animation-delay: 0.15s; }
.delay-3 { animation-delay: 0.25s; }
.delay-4 { animation-delay: 0.35s; }

.saas-tabs-container {
    background: #f1f5f9; padding: 6px; border-radius: 20px;
    display: inline-flex; flex-wrap: wrap; gap: 4px; width: 100%;
    box-shadow: inset 0 2px 5px rgba(0,0,0,0.02);
}
.saas-tabs-container .nav-item { flex: 1; min-width: 140px; }
.saas-tabs-container .nav-link {
    border: none; border-radius: 16px; color: #64748b; font-weight: 700;
    padding: 0.85rem 1rem; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    background: transparent; width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 1rem;
}
.saas-tabs-container .nav-link:hover { color: #334155; background: rgba(255,255,255,0.4); }
.saas-tabs-container .nav-link.active {
    background: #ffffff; color: #8b5cf6; box-shadow: 0 4px 15px rgba(0,0,0,0.06), 0 1px 3px rgba(0,0,0,0.02);
    transform: scale(1.01);
}

.btn-premium { 
    border-radius: 16px; font-weight: 700; padding: 0.8rem 1.8rem; 
    transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1); 
    box-shadow: 0 4px 12px rgba(0,0,0,0.06); letter-spacing: 0.3px;
}
.btn-premium:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(0,0,0,0.12); filter: brightness(1.05); }

.timeline-item { position: relative; padding-right: 20px; border-right: 3px solid #e2e8f0; margin-bottom: 1rem; }
.timeline-item::before { content: ''; position: absolute; right: -7.5px; top: 6px; width: 12px; height: 12px; border-radius: 50%; background: #3b82f6; box-shadow: 0 0 0 4px #eff6ff;}
.timeline-item.late::before { background: #ef4444; box-shadow: 0 0 0 4px #fef2f2;}
.timeline-item.paid::before { background: #22c55e; box-shadow: 0 0 0 4px #f0fdf4;}
.timeline-item.paid { opacity: 0.5; }
</style>

<div class="row align-items-center mb-5 animate-slide-up">
    <div class="col-md-7">
        <h1 class="display-6 fw-bold text-dark mb-3" style="letter-spacing: -1px;">
            <i class="fa-solid fa-chart-line text-primary me-2"></i> الذكاء المالي
            <?php
            if (isset($_GET['month']) && isset($_GET['year'])) {
                $m = (int)$_GET['month'];
                $y = (int)$_GET['year'];
                if ($m != date('n') || $y != date('Y')) {
                    $monthsAr = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
                    echo '<span class="badge bg-warning text-dark ms-2 rounded-pill" style="font-size: 0.9rem; vertical-align: middle;"><i class="fa-solid fa-box-archive me-1"></i> أرشيف: ' . $monthsAr[$m] . ' ' . $y . '</span>';
                }
            }
            ?>
        </h1>
        <p class="text-secondary mb-0 fw-semibold fs-5">نظام متقدم لتتبع وتنمية ثروتك وتقسيم الميزانية بذكاء.</p>
    </div>
    <div class="col-md-5 text-md-end mt-4 mt-md-0 d-flex justify-content-md-end gap-2">
        <button class="btn btn-outline-secondary btn-premium shadow-sm py-3 px-4" data-bs-toggle="modal" data-bs-target="#timeArchiveModal">
            <i class="fa-solid fa-calendar-days me-2"></i> الأرشيف
        </button>
        <button class="btn btn-primary btn-premium shadow-sm py-3 px-4" data-bs-toggle="modal" data-bs-target="#categoriesModal">
            <i class="fa-solid fa-layer-group me-2"></i> إدارة التصنيفات
        </button>
    </div>
</div>

<!-- Modal الأرشيف -->
<div class="modal fade" id="timeArchiveModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold text-dark"><i class="fa-solid fa-calendar-days text-primary me-2"></i> تصفح الأرشيف المالي</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 bg-white text-center">
                <p class="text-muted mb-4">اختر الشهر والسنة لاستعراض سجلات الدخل والمصروفات الخاصة به.</p>
                <form action="<?= BASE_URL ?>/finance" method="GET" class="d-flex align-items-center gap-2 justify-content-center m-0" id="localTimeForm">
                    <select name="month" class="form-select bg-light border-0 fw-bold shadow-none" style="width: 120px;">
                        <?php 
                        $actMonth = (int)($_GET['month'] ?? date('n'));
                        $actYear = $_GET['year'] ?? date('Y');
                        $monthsAr = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
                        foreach($monthsAr as $mNum => $mName): ?>
                            <option value="<?= $mNum ?>" <?= $actMonth == $mNum ? 'selected' : '' ?>><?= $mName ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="year" class="form-select bg-light border-0 fw-bold shadow-none" style="width: 100px;">
                        <?php for($y=2024; $y<=date('Y')+2; $y++): ?>
                            <option value="<?= $y ?>" <?= $actYear == $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </form>
            </div>
            <div class="modal-footer bg-light border-0 d-flex justify-content-between">
                <a href="<?= BASE_URL ?>/finance" class="btn btn-success"><i class="fa-solid fa-reply me-1"></i> العودة للشهر الحالي</a>
                <div>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary fw-bold" onclick="document.getElementById('localTimeForm').submit();">تطبيق واستعراض</button>
                </div>
            </div>
        </div>
    </div>
</div>

<?= display_flash_message('finance') ?>

<!-- Overview Cards -->
<div class="row mb-5 g-4">
    <div class="col-md-3 col-6 animate-slide-up delay-1">
        <div class="card card-saas card-gradient-personal h-100 p-2">
            <div class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                <div class="stats-icon bg-success-subtle text-success mb-3"><i class="fa-solid fa-wallet"></i></div>
                <h6 class="mb-2 text-secondary fw-bold text-uppercase" style="letter-spacing: 0.5px;">المحفظة الشخصية (50%)</h6>
                <h3 class="fw-bold mb-0 text-dark"><?= number_format($netPersonal) ?> <small class="text-muted fs-6">ج.م</small></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6 animate-slide-up delay-2">
        <div class="card card-saas card-gradient-business h-100 p-2">
            <div class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                <div class="stats-icon bg-primary-subtle text-primary mb-3"><i class="fa-solid fa-briefcase"></i></div>
                <h6 class="mb-2 text-secondary fw-bold text-uppercase" style="letter-spacing: 0.5px;">صندوق العمل (20%)</h6>
                <h3 class="fw-bold mb-0 text-dark"><?= number_format($netBusiness) ?> <small class="text-muted fs-6">ج.م</small></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6 animate-slide-up delay-3">
        <div class="card card-saas card-gradient-savings h-100 p-2">
            <div class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                <div class="stats-icon bg-info-subtle text-info mb-3"><i class="fa-solid fa-piggy-bank"></i></div>
                <h6 class="mb-2 text-secondary fw-bold text-uppercase" style="letter-spacing: 0.5px;">صندوق الادخار (20%)</h6>
                <h3 class="fw-bold mb-0 text-dark"><?= number_format($netSavings) ?> <small class="text-muted fs-6">ج.م</small></h3>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6 animate-slide-up delay-4">
        <div class="card card-saas card-gradient-charity h-100 p-2">
            <div class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                <div class="stats-icon bg-warning-subtle text-warning mb-3"><i class="fa-solid fa-hand-holding-heart"></i></div>
                <h6 class="mb-2 text-secondary fw-bold text-uppercase" style="letter-spacing: 0.5px;">صندوق الصدقات (10%)</h6>
                <h3 class="fw-bold mb-0 text-dark"><?= number_format($netCharity) ?> <small class="text-muted fs-6">ج.م</small></h3>
            </div>
        </div>
    </div>
</div>

<!-- Finance Intelligence Widgets -->
<?php if(isset($financeAnalysis)): ?>
<div class="row mb-5 animate-slide-up delay-4">
    <!-- Cash Flow Panel -->
    <div class="col-md-7 mb-4 mb-md-0">
        <div class="card card-saas h-100 p-3" style="background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center border-bottom pb-3 mb-4">
                    <h5 class="fw-bold text-dark mb-0"><i class="fa-solid fa-water text-info me-2"></i> محرك التدفق النقدي</h5>
                    <span class="badge bg-light text-secondary border">محدث لحظياً</span>
                </div>
                
                <div class="row g-4 text-center">
                    <?php 
                    $flowPeriods = [
                        'اليوم' => $financeAnalysis['cash_flow']['today'],
                        'هذا الأسبوع' => $financeAnalysis['cash_flow']['week'],
                        'هذا الشهر' => $financeAnalysis['cash_flow']['month']
                    ];
                    foreach($flowPeriods as $label => $flow): 
                        $flowColor = $flow['net'] >= 0 ? "success" : "danger";
                        $flowIcon = $flow['net'] >= 0 ? "up" : "down";
                    ?>
                    <div class="col-4">
                        <div class="p-3 rounded-4 bg-white shadow-sm h-100 border border-<?php echo $flowColor; ?>-subtle">
                            <h6 class="text-secondary small fw-bold mb-3"><?= $label ?></h6>
                            <h5 class="fw-bold text-<?= $flowColor ?> mb-2" dir="ltr">
                                <?= number_format(abs($flow['net'])) ?> <i class="fa-solid fa-arrow-trend-<?= $flowIcon ?> ms-1 small"></i>
                            </h5>
                            <div class="d-flex justify-content-between small px-2 mt-3 text-muted">
                                <span><i class="fa-solid fa-arrow-down text-success me-1"></i><?= number_format($flow['in']) ?></span>
                                <span><i class="fa-solid fa-arrow-up text-danger me-1"></i><?= number_format($flow['out']) ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Pressure Score Panel -->
    <div class="col-md-5">
        <?php 
            $pScore = $financeAnalysis['pressure_score']['score'];
            $pLevel = $financeAnalysis['pressure_score']['level'];
            $pLabel = $financeAnalysis['pressure_score']['label'];
            
            $pTheme = 'success'; $pIcon = 'fa-shield-halved';
            if($pLevel == 'medium') { $pTheme = 'warning'; $pIcon = 'fa-scale-unbalanced'; }
            if($pLevel == 'high') { $pTheme = 'danger'; $pIcon = 'fa-radiation'; }
        ?>
        <div class="card card-saas h-100 p-3 bg-<?= $pTheme ?>-subtle border-<?= $pTheme ?>">
            <div class="card-body d-flex flex-column justify-content-center align-items-center text-center">
                <div class="stats-icon bg-white text-<?= $pTheme ?> shadow-sm mb-4" style="width: 80px; height: 80px; font-size: 2.2rem;">
                    <i class="fa-solid <?= $pIcon ?>"></i>
                </div>
                <h4 class="fw-bold mb-3 text-<?= $pTheme ?>"><?= $pLabel ?></h4>
                
                <div class="w-100 px-4 mb-3">
                    <div class="progress" style="height: 12px; border-radius: 10px; background-color: rgba(255,255,255,0.5);">
                      <div class="progress-bar progress-bar-striped progress-bar-animated bg-<?= $pTheme ?>" role="progressbar" style="width: <?= $pScore ?>%;"></div>
                    </div>
                </div>
                
                <p class="text-muted fw-bold mb-0">مؤشر الضغط المالي: <span class="fs-4 text-<?= $pTheme ?>"><?= $pScore ?>%</span></p>
                <?php if($pLevel === 'high'): ?>
                <div class="alert alert-danger mt-3 mb-0 fw-bold shadow-sm animation-pulse">
                    <i class="fa-solid fa-hand text-danger me-2"></i> أوقف الصرف فوراً!
                </div>
                <style>@keyframes pulseAlert { 0% {transform: scale(1);} 50% {transform: scale(1.05);} 100% {transform: scale(1);} } .animation-pulse { animation: pulseAlert 2s infinite; }</style>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
