<?php
ob_start();
session_start();
require_once('config/db.php');
include 'auth_license.php';
require_once 'check_license.php';

if (!isset($_SESSION['user'])) {
    header('Location: auth/login.php');
    exit;
}

$user = $_SESSION['user'];

// الإحصائيات - ستبقى كما هي لتجنب أي خلل
$studentsCount    = $conn->query("SELECT COUNT(*) as count FROM students")->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
$coursesCount      = $conn->query("SELECT COUNT(*) as count FROM courses")->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
$usersCount        = $conn->query("SELECT COUNT(*) as count FROM users")->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
$totalPayments    = $conn->query("SELECT IFNULL(SUM(amount_paid),0) as totalPayments FROM payments")->fetch(PDO::FETCH_ASSOC)['totalPayments'] ?? 0;
$totalDiscounts   = $conn->query("SELECT IFNULL(SUM(discount), 0) as totalDiscounts FROM payments")->fetch(PDO::FETCH_ASSOC)['totalDiscounts'] ?? 0;
$totalExpenses    = $conn->query("SELECT IFNULL(SUM(amount), 0) as totalExpenses FROM expenses")->fetch(PDO::FETCH_ASSOC)['totalExpenses'] ?? 0;

$totalRemaining  = $conn->query("
    SELECT 
        IFNULL(SUM(c.price), 0) - (
            SELECT IFNULL(SUM(amount_paid + discount), 0)
            FROM payments
        ) AS total_remaining
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
")->fetch(PDO::FETCH_ASSOC)['total_remaining'] ?? 0;

$profit = $totalPayments - $totalExpenses;
?>
<?php include('includes/header.php'); // تأكد أن ملف الهيدر يحتوي على دالة __() ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" crossorigin="anonymous" />

<style>
    .action-btn {
        display: flex; flex-direction: column; align-items: center; justify-content: center;
        color: white; padding: 1.25rem 0.5rem; border-radius: 1.5rem;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); text-align: center;
        font-weight: 700; font-size: 0.95rem; transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        position: relative; overflow: hidden; text-decoration: none;
    }
    .action-btn:before {
        content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(255, 255, 255, 0.1); transition: transform 0.5s; transform: scale(0);
        border-radius: 50%; opacity: 0;
    }
    .action-btn:hover:before { transform: scale(1.5); opacity: 1; border-radius: 1.5rem; }
    .action-btn:hover { transform: translateY(-5px) scale(1.05); box-shadow: 0 15px 25px rgba(0, 0, 0, 0.25); }
    .action-btn i { font-size: 2rem; margin-bottom: 0.5rem; transition: color 0.3s; }
    @keyframes fadeInDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
    .animate-fadeInDown { animation: fadeInDown 0.7s ease-out; }
    .animate-fadeInUp { animation: fadeInUp 0.7s ease-out 0.2s; }
    .stat-card {
        background-color: #ffffff; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
        border-radius: 1.5rem; padding: 1.75rem; transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
        position: relative; overflow: hidden;
    }
    .stat-card:hover { transform: translateY(-8px) rotateZ(0.5deg); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); }
    .stat-card::after { content: ''; position: absolute; bottom: 0; left: 0; width: 100%; height: 8px; transition: all 0.4s; }
    .stat-card:hover::after { height: 12px; }
    .border-stat-blue::after { background-color: #3b82f6; }
    .border-stat-green::after { background-color: #10b981; }
    .border-stat-purple::after { background-color: #8b5cf6; }
    .border-stat-red::after { background-color: #ef4444; }
    .border-stat-orange::after { background-color: #f97316; }
    .border-stat-teal::after { background-color: #14b8a6; }
    .border-stat-yellow::after { background-color: #f59e0b; }
    .border-stat-pink::after { background-color: #ec4899; }
    .dark .stat-card { background-color: #1f2937; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); }
    .welcome-hero {
        background-image: linear-gradient(135deg, #4c1d95 0%, #6366f1 100%);
        color: white; padding: 3rem; border-radius: 2.5rem;
        box-shadow: 0 20px 50px rgba(79, 70, 229, 0.5);
    }
    .welcome-hero img { border: 4px solid rgba(255, 255, 255, 0.5); }
</style>

<?php include('includes/navbar.php'); ?>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16">
    <div class="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">

        <div class="text-center mb-16 welcome-hero transition duration-500 hover:scale-[1.01]">
            <div class="flex flex-col sm:flex-row justify-center items-center gap-6">
                <img src="assets/logo.png" alt="Logo" class="w-32 h-32 rounded-full shadow-2xl object-cover transform transition duration-500 hover:rotate-3 border-4 border-white ring-2 ring-[#e2c05e]/20 bg-white">
                <div class="text-right sm:text-center">
                    <h1 class="text-2xl md:text-4xl font-extrabold text-white mb-2 animate-fadeInDown">
                        <span class="text-white-300"><?php echo __("site_title"); ?></span> 👋
                    </h1>
                    <h1 class="text-2xl md:text-4xl font-extrabold text-white mb-2 animate-fadeInDown">
                        <?php echo __("welcome_user"); ?>, <span class="text-yellow-300"><?= htmlspecialchars($user['full_name']) ?></span> 
                    </h1>
                    <p class="text-xl text-indigo-200 font-light animate-fadeInUp">
                        <?php echo __("dashboard_subtitle"); ?>
                    </p>
                </div>
            </div>
        </div>

        <?php if ($user['role'] !== 'teacher'): ?>

            <h2 class="text-2xl font-extrabold text-gray-800 dark:text-gray-100 mt-16 mb-8 pb-3 border-b-4 border-indigo-400/50">📊 <?php echo __("performance_summary"); ?></h2>
            
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="stat-card border-stat-blue">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-users text-blue-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("students_count"); ?></h3>
                    </div>
                    <p class="text-5xl font-extrabold text-blue-700 dark:text-blue-400"><?= $studentsCount ?></p>
                </div>

                <div class="stat-card border-stat-green">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-book-open text-green-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("courses_count"); ?></h3>
                    </div>
                    <p class="text-5xl font-extrabold text-green-700 dark:text-green-400"><?= $coursesCount ?></p>
                </div>

                <div class="stat-card border-stat-purple">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-user-shield text-purple-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("users_count"); ?></h3>
                    </div>
                    <p class="text-5xl font-extrabold text-purple-700 dark:text-purple-400"><?= $usersCount ?></p>
                </div>
                
                <?php if ($user['role'] !== 'staff'): ?>
                <div class="stat-card border-stat-teal">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-chart-line text-teal-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("net_profit"); ?></h3>
                    </div>
                    <p class="text-3xl font-extrabold text-teal-700 dark:text-teal-400"><?= number_format($profit, 2) ?> <?php echo __("currency"); ?></p>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if ($user['role'] !== 'staff'): ?>
            <h2 class="text-2xl font-extrabold text-gray-800 dark:text-gray-100 mt-16 mb-8 pb-3 border-b-4 border-indigo-400/50">💰 <?php echo __("financial_analysis"); ?></h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
                <div class="stat-card border-stat-red">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-wallet text-red-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("total_payments"); ?></h3>
                    </div>
                    <p class="text-3xl font-extrabold text-red-700 dark:text-red-400"><?= number_format($totalPayments, 2) ?> <?php echo __("currency"); ?></p>
                </div>
                <div class="stat-card border-stat-orange">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-file-invoice-dollar text-orange-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("total_expenses"); ?></h3>
                    </div>
                    <p class="text-3xl font-extrabold text-orange-700 dark:text-orange-400"><?= number_format($totalExpenses, 2) ?> <?php echo __("currency"); ?></p>
                </div>
                <div class="stat-card border-stat-yellow">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-hourglass-half text-yellow-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("remaining_amount"); ?></h3>
                    </div>
                    <p class="text-3xl font-extrabold text-yellow-700 dark:text-yellow-400"><?= number_format($totalRemaining, 2) ?> <?php echo __("currency"); ?></p>
                </div>
                <div class="stat-card border-stat-pink">
                    <div class="flex items-center justify-between mb-4">
                        <i class="fas fa-percent text-pink-500 text-3xl opacity-70"></i>
                        <h3 class="text-base font-semibold text-gray-500 dark:text-gray-400"><?php echo __("total_discounts"); ?></h3>
                    </div>
                    <p class="text-3xl font-extrabold text-pink-700 dark:text-pink-400"><?= number_format($totalDiscounts, 2) ?> <?php echo __("currency"); ?></p>
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 shadow-2xl rounded-3xl p-8 mt-12 transition duration-500 hover:shadow-indigo-500/30">
                <h2 class="text-2xl font-bold text-gray-800 dark:text-gray-200 mb-6 text-center">📈 <?php echo __("chart_title"); ?></h2>
                <div class="relative h-96"><canvas id="statsChart"></canvas></div>
            </div>
            <?php endif; ?>

            <h2 class="text-2xl font-extrabold text-gray-800 dark:text-gray-100 mt-16 mb-8 pb-3 border-b-4 border-indigo-400/50">🚀 <?php echo __("quick_actions"); ?></h2>
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-3 gap-6">
                <a href="students/list.php" class="action-btn bg-gradient-to-br from-blue-500 to-indigo-600"><i class="fas fa-graduation-cap"></i> <?php echo __("students"); ?></a>
                <a href="courses/list.php" class="action-btn bg-gradient-to-br from-green-500 to-teal-600"><i class="fas fa-book"></i> <?php echo __("courses"); ?></a>
                <a href="enroll/enroll.php" class="action-btn bg-gradient-to-br from-purple-500 to-pink-600"><i class="fas fa-user-plus"></i> <?php echo __("enroll_student"); ?></a>
                <a href="payments/report.php" class="action-btn bg-gradient-to-br from-yellow-500 to-orange-600"><i class="fas fa-money-check-alt"></i> <?php echo __("payments"); ?></a>
                <a href="expenses/add.php" class="action-btn bg-gradient-to-br from-red-500 to-pink-600"><i class="fas fa-hand-holding-usd"></i> <?php echo __("add_expense"); ?></a>
                <?php if ($user['role'] !== 'staff'): ?>
                    <a href="user/list.php" class="action-btn bg-gradient-to-br from-indigo-500 to-purple-600"><i class="fas fa-users-cog"></i> <?php echo __("users_management"); ?></a>
                    <a href="expenses/report.php" class="action-btn bg-gradient-to-br from-orange-500 to-red-600"><i class="fas fa-chart-pie"></i> <?php echo __("expenses_report"); ?></a>
                    <a href="reports/reports_dashboard.php" class="action-btn bg-gradient-to-br from-cyan-500 to-blue-600"><i class="fas fa-file-alt"></i> <?php echo __("reports"); ?></a>
                <?php endif; ?>
                <a href="auth/logout.php" class="action-btn bg-gradient-to-br from-gray-500 to-gray-700"><i class="fas fa-sign-out-alt"></i> <?php echo __("logout"); ?></a>
            </div>

        <?php endif; ?>
        
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const chartCanvas = document.getElementById('statsChart');
    if (chartCanvas) {
        const ctx = chartCanvas.getContext('2d');
        const totalPayments = <?= $totalPayments ?>;
        const totalExpenses = <?= $totalExpenses ?>;
        const profit = <?= $profit ?>;
        const vibrantColors = ['#ef4444', '#f97316', '#10b981', '#f59e0b', '#ec4899'];
        const lightVibrantColors = ['rgba(239, 68, 68, 0.7)', 'rgba(249, 115, 22, 0.7)', 'rgba(16, 185, 129, 0.7)', 'rgba(252, 211, 77, 0.7)', 'rgba(236, 72, 147, 0.7)'];
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [
                    "<?php echo __("total_payments"); ?>", 
                    "<?php echo __("total_expenses"); ?>", 
                    "<?php echo __("net_profit"); ?>", 
                    "<?php echo __("remaining_amount"); ?>", 
                    "<?php echo __("total_discounts"); ?>"
                ],
                datasets: [{
                    label: "<?php echo __("currency"); ?>",
                    data: [totalPayments, totalExpenses, profit, <?= $totalRemaining ?>, <?= $totalDiscounts ?>],
                    backgroundColor: lightVibrantColors,
                    borderColor: vibrantColors,
                    borderWidth: 2,
                    borderRadius: 8,
                    hoverBackgroundColor: vibrantColors,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: 'y',
                plugins: {
                    legend: { display: false },
                    tooltip: { rtl: <?php echo ($current_lang == 'ar') ? 'true' : 'false'; ?>, bodyFont: { family: 'Cairo', size: 14 }, titleFont: { family: 'Cairo', size: 16, weight: 'bold' } }
                },
                scales: {
                    x: { beginAtZero: true },
                    y: { ticks: { font: { family: 'Cairo', size: 14 } } }
                }
            }
        });
    }
</script>

<?php include('includes/footer.php'); ?>
