<?php

session_start();
require_once('../config/db.php');

if (!isset($_SESSION['student_id'])) {
    header('Location: login.php');
    exit;
}

// تحديد اللغة - الافتراضي العربية
$lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'ar';

// مصفوفة الترجمة الشاملة (تتضمن بياناتك الأصلية + إضافات الجداول الجديدة)
$translations = [
    'ar' => [
        'dir' => 'rtl',
        'font' => "'Cairo', sans-serif",
        'title' => 'لوحة الطالب | معهد لغة العرب',
        'portal' => 'بوابة الطالب',
        'inst_name' => 'معهد لغة العرب .',
        'badge' => 'طالب متميز',
        'logout' => 'خروج',
        'welcome' => 'أهلاً بك، سيد',
        'hero_desc' => 'في معهد لغة العرب، نسعد بمتابعة تطورك الأكاديمي. يمكنك هنا الإطلاع على مسيرتك التعليمية وإدارة شؤونك المالية بكل سهولة.',
        'today' => 'اليوم',
        'total_fees' => 'إجمالي الرسوم',
        'paid_amount' => 'المبلغ المدفوع',
        'discounts' => 'الخصومات',
        'remaining' => 'المبلغ المتبقي',
        'registered_courses' => 'الدورات المسجلة',
        'course_col' => 'الدورة التعليمية',
        'fees_col' => 'الرسوم',
        'system_col' => 'النظام',
        'rating_col' => 'التقييم',
        'news_title' => 'أخبار المعهد',
        'no_news' => 'لا يوجد إعلانات',
        'payments_log' => 'سجل المدفوعات المالية',
        'amount_col' => 'قيمة الدفعة',
        'discount_col' => 'الخصم',
        'date_col' => 'التاريخ',
        'method_col' => 'طريقة الدفع',
        'notes_col' => 'ملاحظات',
        'currency' => 'د.أ',
        'no_notes' => 'لا توجد ملاحظات',
        'footer_desc' => 'بوابتك لتعلم اللغة العربية لغير الناطقين بها بأعلى معايير الجودة الأكاديمية.',
        'contact_us' => 'تواصل معنا',
        'msg_no_courses' => 'لم يتم تسجيل أي كورسات بعد.',
        'msg_remaining' => 'لديك مبلغ متبقي: {amount} د.أ. يرجى دفعه في أقرب وقت.',
        'msg_cleared' => 'لقد قمت بدفع جميع المبالغ. شكراً لك!',
        'toast_success' => 'تم تقييم الدورة بـ {val} نجوم',
        'toast_error' => 'فشل حفظ التقييم',
        // الإضافات الجديدة للجداول
        'schedule_title' => 'الجدول الدراسي الأسبوعي',
        'attendance_title' => 'سجل الحضور والغياب',
        'day_col' => 'اليوم',
        'time_col' => 'الوقت',
        'status_col' => 'الحالة',
        'teacher_col' => 'المعلم',
		'no_attendance' => 'لا يوجد سجلات حضور حالياً'
    ],
    'en' => [
        'dir' => 'ltr',
        'font' => "'Segoe UI', sans-serif",
        'title' => 'Student Dashboard | Lughat AlArab',
        'portal' => 'Student Portal',
        'inst_name' => 'Lughat AlArab Institute',
        'badge' => 'Distinguished Student',
        'logout' => 'logout',
        'welcome' => 'Welcome, Mr.',
        'hero_desc' => 'At Lughat AlArab Institute, we are pleased to track your academic progress. Here you can view your educational path and manage your financial affairs easily.',
        'today' => 'Today',
        'total_fees' => 'Total Fees',
        'paid_amount' => 'Paid Amount',
        'discounts' => 'Discounts',
        'remaining' => 'Remaining',
        'registered_courses' => 'Registered Courses',
        'course_col' => 'Course Name',
        'fees_col' => 'Fees',
        'system_col' => 'System',
        'rating_col' => 'Rating',
        'news_title' => 'Institute News',
        'no_news' => 'No Announcements',
        'payments_log' => 'Financial Payments Log',
        'amount_col' => 'Amount',
        'discount_col' => 'Discount',
        'date_col' => 'Date',
        'method_col' => 'Method',
        'notes_col' => 'Notes',
        'currency' => 'JOD',
        'no_notes' => 'No notes',
        'footer_desc' => 'Your gateway to learning Arabic for non-native speakers with the highest academic standards.',
        'contact_us' => 'Contact Us',
        'msg_no_courses' => 'No courses registered yet.',
        'msg_remaining' => 'You have a remaining balance: {amount} JOD. Please pay soon.',
        'msg_cleared' => 'All payments cleared. Thank you!',
        'toast_success' => 'Course rated {val} stars',
        'toast_error' => 'Rating failed',
        // الإضافات الجديدة
        'schedule_title' => 'Weekly Schedule',
        'attendance_title' => 'Attendance Log',
        'day_col' => 'Day',
        'time_col' => 'Time',
        'status_col' => 'Status',
        'teacher_col' => 'Teacher',
		'no_attendance' => 'No attendance records found'
    ],
    'tr' => [
        'dir' => 'ltr',
        'font' => "'Segoe UI', sans-serif",
        'title' => 'Öğrenci Paneli | Lughat AlArab',
        'portal' => 'Öğrenci Portalı',
        'inst_name' => 'Lughat AlArab Enstitüsü',
        'badge' => 'Seçkin Öğrenci',
        'logout' => 'Çıkış Yap',
        'welcome' => 'Hoş geldiniz, Sn.',
        'hero_desc' => 'Lughat AlArab Enstitüsü\'nde akademik gelişiminizi takip etmekten mutluluk duyuyoruz.',
        'today' => 'Bugün',
        'total_fees' => 'Toplam Ücret',
        'paid_amount' => 'Ödenen Tutar',
        'discounts' => 'İndirimler',
        'remaining' => 'Kalan Bakiye',
        'registered_courses' => 'Kayıtlı Kurslar',
        'course_col' => 'Kurs Adı',
        'fees_col' => 'Ücret',
        'system_col' => 'Sistem',
        'rating_col' => 'Değerlendirme',
        'news_title' => 'Enstitü Haberleri',
        'no_news' => 'Duyuru bulunmamaktadır',
        'payments_log' => 'Ödeme Kayıtları',
        'amount_col' => 'Tutar',
        'discount_col' => 'İndirim',
        'date_col' => 'Tarih',
        'method_col' => 'Ödeme Yöntemi',
        'notes_col' => 'Notlar',
        'currency' => 'JOD',
        'no_notes' => 'Not bulunamadı',
        'footer_desc' => 'Anadili Arapça olmayanlar için en yüksek akademik standartlarda Arapça öğrenme kapınız.',
        'contact_us' => 'Bize Ulaşın',
        'msg_no_courses' => 'Henüz kayıtlı kurs bulunmamaktadır.',
        'msg_remaining' => 'Kalan bakiyeniz: {amount} JOD.',
        'msg_cleared' => 'Tüm ödemeler tamamlandı. Teşekkürler!',
        'toast_success' => 'Kurs {val} yıldızla değerlendirildi',
        'toast_error' => 'Değerlendirme başarısız',
        // الإضافات الجديدة
        'schedule_title' => 'Haftalık Ders Programı',
        'attendance_title' => 'Yoklama Kaydı',
        'day_col' => 'Gün',
        'time_col' => 'Saat',
        'status_col' => 'Durum',
        'teacher_col' => 'Öğretmen',
		'no_attendance' => 'Henüz yoklama kaydı bulunmamaktadır'
    ]
];

$t = $translations[$lang];
$student_id = $_SESSION['student_id'];

// استكمال جلب البيانات من قاعدة البيانات...
// (باقي الكود البرمجي كما هو في ردي السابق)

// تسجيل الخروج
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// بيانات الطالب
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

// الإعلانات المرئية
$stmt = $conn->prepare("SELECT * FROM announcements WHERE visible = 1 ORDER BY created_at DESC");
$stmt->execute();
$announcements = $stmt->fetchAll(PDO::FETCH_ASSOC);

// الكورسات المسجلة
$stmt = $conn->prepare("
    SELECT e.id as enrollment_id, c.id as course_id, c.course_name, c.price, e.enrollment_date, e.attendance_type
    FROM enrollments e
    JOIN courses c ON c.id = e.course_id
    WHERE e.student_id = ?
    ORDER BY e.enrollment_date ASC
");
$stmt->execute([$student_id]);
$enrollments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- جديد: جلب الجدول الدراسي ---
$stmt_sch = $conn->prepare("
    SELECT s.*, c.course_name 
    FROM student_schedules s
    JOIN courses c ON s.course_id = c.id
    WHERE s.student_id = ?
    ORDER BY FIELD(day_name, 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'), start_time
");
$stmt_sch->execute([$student_id]);
$schedules = $stmt_sch->fetchAll(PDO::FETCH_ASSOC);

// --- جديد: جلب سجل الحضور والغياب ---
$stmt_att = $conn->prepare("
    SELECT a.*, c.course_name 
    FROM attendance a
    JOIN courses c ON a.course_id = c.id
    WHERE a.student_id = ?
    ORDER BY attendance_date DESC
");
$stmt_att->execute([$student_id]);
$attendance_records = $stmt_att->fetchAll(PDO::FETCH_ASSOC);

// الدفعات
$stmt = $conn->prepare("SELECT amount_paid, discount, payment_date, payment_method, notes FROM payments WHERE student_id = ? ORDER BY payment_date ASC");
$stmt->execute([$student_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// حساب المبالغ
$total_paid_all = !empty($payments) ? array_sum(array_column($payments, 'amount_paid')) : 0;
$total_discount_all = !empty($payments) ? array_sum(array_column($payments, 'discount')) : 0;
$total_courses = !empty($enrollments) ? array_sum(array_column($enrollments, 'price')) : 0;
$remaining_all = $total_courses - ($total_paid_all + $total_discount_all);

// إشعار الدفع
$notification = "";
$notificationType = "";
if ($total_courses == 0) {
    $notification = $t['msg_no_courses'];
    $notificationType = 'info';
} elseif ($remaining_all > 0) {
    $notification = str_replace('{amount}', number_format($remaining_all, 2), $t['msg_remaining']);
    $notificationType = 'warning';
} else {
    $notification = $t['msg_cleared'];
    $notificationType = 'success';
}
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $t['dir'] ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $t['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
    /* 1. المتغيرات اللونية الأساسية */
    :root {
        --gold: #c5a059;
        --dark: #1a1a1a;
        --beige: #e8e4d9;
        --white: #ffffff;
    }

    /* 2. الإعدادات العامة للجسم (Body) */
    body { 
        font-family: <?= $t['font'] ?>; 
        background-image: url('../assets/pngegg2.jpg');
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        background-attachment: fixed;
        background-color: #d6d1c2;
        word-wrap: break-word;
        margin: 0;
        padding: 0;
        position: relative;
    }

    /* 3. طبقة التغطية الشفافة */
    .bg-overlay {
        position: fixed;
        top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(232, 228, 217, 0.88); 
        z-index: -1;
    }

    /* 4. الهيدر */
    .glass-header {
        background: rgba(26, 26, 26, 0.98);
        border-bottom: 3px solid var(--gold);
        backdrop-filter: blur(10px);
    }

    /* 5. قسم الترحيب الرئيسي */
    .hero-section {
        position: relative;
        overflow: hidden;
        background-color: #000000 !important;
        background-image: linear-gradient(rgba(0, 0, 0, 0.90), rgba(0, 0, 0, 0.85)), 
                          url('../assets/pngegg2.jpg');
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        border-radius: 20px;
        border-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>: 6px solid var(--gold);
        transition: all 0.3s ease;
        z-index: 10;
        box-shadow: 0 20px 40px rgba(0,0,0,0.2);
    }

    .hero-section::after { display: none !important; }

    /* 6. بطاقات البيانات */
    .stat-card, .announcement-card, .custom-table tr {
        background: var(--white) !important;
        border-radius: 24px;
        border: 1px solid rgba(197, 160, 89, 0.15);
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.05);
        border-color: var(--gold);
    }

    /* 7. الأزرار */
    .btn-gold-outline {
        border: 2px solid var(--gold);
        color: var(--gold);
        background: transparent;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        font-weight: bold;
    }

    .btn-gold-outline:hover {
        background: var(--gold);
        color: var(--white);
    }

    /* 8. الجداول */
    .custom-table thead {
        background: var(--dark);
        color: var(--gold);
    }

    .custom-table tr {
        background: var(--white);
        border-bottom: 8px solid var(--beige);
    }

    /* الحالات للحضور والغياب */
    .status-badge {
        padding: 4px 12px;
        border-radius: 50px;
        font-size: 11px;
        font-weight: bold;
    }
    .status-attendance { background: #dcfce7; color: #166534; }
    .status-absence { background: #fee2e2; color: #991b1b; }
    .status-excuse { background: #fef9c3; color: #854d0e; }

    /* 9. التنسيقات المتجاوبة */
    @media (min-width: 768px) {
        .hero-section { 
            border-radius: 30px; 
            border-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>-width: 8px; 
        }
    }

    @media (max-width: 768px) {
        .custom-table thead { display: none; }
        .custom-table tr { 
            display: block; 
            margin-bottom: 1.2rem; 
            padding: 1.2rem;
            border-radius: 20px;
        }
        .custom-table td { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding: 0.7rem 0 !important;
            border: none !important;
            text-align: <?= ($t['dir'] == 'rtl' ? 'left' : 'right') ?>;
        }
        .custom-table td::before {
            content: attr(data-label);
            font-weight: 800;
            color: var(--dark);
            margin-<?= ($t['dir'] == 'rtl' ? 'left' : 'right') ?>: 1rem;
            opacity: 0.7;
        }
    }

    .star {
        color: var(--gold);
        text-shadow: 0 0 5px rgba(197, 160, 89, 0.3);
    }
</style>
</head>
<body class="flex flex-col min-h-screen">

    <div class="bg-overlay"></div>

    <header class="glass-header sticky top-0 z-40 w-full shadow-2xl">
        <div class="max-w-7xl mx-auto px-4">
            <div class="flex justify-between items-center h-20">
                <div class="flex items-center gap-3 md:gap-4">
                    <div class="bg-white p-1 rounded-lg md:rounded-xl shadow-inner flex items-center justify-center">
                        <img src="../assets/logo.png" alt="logo" class="h-10 md:h-12 w-auto object-contain">
                    </div>
                    <div>
                        <span class="block text-lg md:text-xl font-black text-white leading-none"><?= $t['inst_name'] ?></span>
                        <span class="text-[8px] md:text-[10px] text-[#c5a059] font-bold tracking-[0.2em] md:tracking-[0.3em] uppercase"><?= $t['portal'] ?></span>
                    </div>
                </div>
                
                <div class="flex items-center gap-2 md:gap-4">
                    <div class="text-<?= ($t['dir'] == 'rtl' ? 'left' : 'right') ?> m<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2 md:m<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-4 hidden sm:block">
                        <span class="block text-xs md:text-sm font-black text-white"><?= htmlspecialchars($student['full_name']) ?></span>
                        <span class="text-[9px] bg-[#c5a059]/20 text-[#c5a059] px-2 py-0.5 rounded font-bold"><?= $t['badge'] ?></span>
                    </div>
                    <a href="?logout=1" class="btn-gold-outline px-3 md:px-5 py-1.5 md:py-2 rounded-lg md:rounded-xl font-bold text-xs md:text-sm whitespace-nowrap">
                        <i class="fas fa-sign-out-alt m<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-1 md:m<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2"></i> <?= $t['logout'] ?>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <main class="flex-grow container max-w-7xl mx-auto px-4 py-6 md:py-10 space-y-8 md:space-y-10">
        
        <section class="hero-section p-6 md:p-12 text-white shadow-xl">
            <div class="absolute inset-0 bg-black/20 pointer-events-none"></div>
            <div class="relative z-10 flex flex-col md:flex-row justify-between items-center gap-6">
                <div class="text-center <?= ($t['dir'] == 'rtl' ? 'md:text-right' : 'md:text-left') ?> w-full">
                    <h1 class="text-2xl md:text-5xl font-black mb-3 md:mb-4">
                        <?= $t['welcome'] ?> <?= explode(' ', $student['full_name'])[0] ?> ✨
                    </h1>
                    <p class="text-gray-300 text-sm md:text-lg max-w-2xl leading-relaxed"><?= $t['hero_desc'] ?></p>
                </div>
                <div class="bg-white/5 backdrop-blur-xl p-4 md:p-6 rounded-2xl md:rounded-3xl border border-white/10 text-center min-w-[140px] md:min-w-[180px]">
                    <p class="text-[#c5a059] text-[10px] md:text-xs font-black uppercase mb-1 md:mb-2"><?= $t['today'] ?></p>
                    <p class="text-lg md:text-2xl font-bold"><?= date('d M, Y') ?></p>
                </div>
            </div>
        </section>

        <?php if($notification): ?>
            <div class="p-4 md:p-5 rounded-xl md:rounded-2xl border-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-4 md:border-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-8 shadow-sm flex items-center gap-3 md:gap-4 <?= ($notificationType=='success' ? 'bg-green-50 border-green-600 text-green-800' : ($notificationType=='warning' ? 'bg-amber-50 border-amber-500 text-amber-800' : 'bg-blue-50 border-blue-600 text-blue-800')) ?>">
                <div class="shrink-0 w-8 h-8 md:w-10 md:h-10 rounded-full bg-white flex items-center justify-center shadow-sm">
                    <i class="fas <?= ($notificationType=='success' ? 'fa-check text-green-600' : 'fa-exclamation text-amber-600') ?> text-xs md:text-base"></i>
                </div>
                <p class="font-bold text-xs md:text-base leading-tight"><?= $notification ?></p>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
            <div class="stat-card p-5 md:p-6">
                <div class="w-10 h-10 md:w-12 md:h-12 bg-gray-100 text-gray-800 rounded-xl md:rounded-2xl flex items-center justify-center mb-3 md:mb-4"><i class="fas fa-book-open"></i></div>
                <p class="text-gray-400 font-bold text-[10px] md:text-xs uppercase"><?= $t['total_fees'] ?></p>
                <h3 class="text-xl md:text-2xl font-black text-gray-800 mt-1"><?= number_format($total_courses, 2) ?> <span class="text-xs md:text-sm font-normal text-gray-400"><?= $t['currency'] ?></span></h3>
            </div>
            <div class="stat-card p-5 md:p-6">
                <div class="w-10 h-10 md:w-12 md:h-12 bg-green-50 text-green-600 rounded-xl md:rounded-2xl flex items-center justify-center mb-3 md:mb-4"><i class="fas fa-check-double"></i></div>
                <p class="text-gray-400 font-bold text-[10px] md:text-xs uppercase"><?= $t['paid_amount'] ?></p>
                <h3 class="text-xl md:text-2xl font-black text-green-600 mt-1"><?= number_format($total_paid_all, 2) ?> <span class="text-xs md:text-sm font-normal text-gray-400"><?= $t['currency'] ?></span></h3>
            </div>
            <div class="stat-card p-5 md:p-6">
                <div class="w-10 h-10 md:w-12 md:h-12 bg-[#c5a059]/10 text-[#c5a059] rounded-xl md:rounded-2xl flex items-center justify-center mb-3 md:mb-4"><i class="fas fa-percentage"></i></div>
                <p class="text-gray-400 font-bold text-[10px] md:text-xs uppercase"><?= $t['discounts'] ?></p>
                <h3 class="text-xl md:text-2xl font-black text-[#c5a059] mt-1"><?= number_format($total_discount_all, 2) ?> <span class="text-xs md:text-sm font-normal text-gray-400"><?= $t['currency'] ?></span></h3>
            </div>
            <div class="stat-card p-5 md:p-6 border-red-100 bg-red-50/30">
                <div class="w-10 h-10 md:w-12 md:h-12 bg-red-100 text-red-600 rounded-xl md:rounded-2xl flex items-center justify-center mb-3 md:mb-4"><i class="fas fa-wallet"></i></div>
                <p class="text-gray-400 font-bold text-[10px] md:text-xs uppercase"><?= $t['remaining'] ?></p>
                <h3 class="text-xl md:text-2xl font-black text-red-600 mt-1"><?= number_format($remaining_all, 2) ?> <span class="text-xs md:text-sm font-normal text-gray-400"><?= $t['currency'] ?></span></h3>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 md:gap-10">
            <div class="space-y-6">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-2 h-6 md:h-8 bg-[#c5a059] rounded-full"></div>
                    <h2 class="text-xl md:text-2xl font-black text-gray-800"><?= $t['schedule_title'] ?></h2>
                </div>
                <div class="overflow-x-visible">
                    <table class="w-full custom-table border-separate border-spacing-y-2">
                        <thead>
                            <tr class="text-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>">
                                <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl"><?= $t['day_col'] ?></th>
                                <th class="p-4 md:p-5"><?= $t['course_col'] ?></th>
                                <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl"><?= $t['time_col'] ?></th>
                            </tr>
                        </thead>
                  <tbody class="font-bold text-gray-700">
    <?php if(!empty($schedules)): foreach ($schedules as $sch): ?>
    <tr class="shadow-sm hover:shadow-md transition-all">
        <td data-label="<?= $t['day_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl text-[#c5a059]">
            <?php 
                $days_ar = ['Saturday' => 'السبت', 'Sunday' => 'الأحد', 'Monday' => 'الإثنين', 'Tuesday' => 'الثلاثاء', 'Wednesday' => 'الأربعاء', 'Thursday' => 'الخميس', 'Friday' => 'الجمعة'];
                $days_tr = ['Saturday' => 'Cumartesi', 'Sunday' => 'Pazar', 'Monday' => 'Pazartesi', 'Tuesday' => 'Salı', 'Wednesday' => 'Çarşamba', 'Thursday' => 'Perşembe', 'Friday' => 'Cuma'];
                $days_en = ['Saturday' => 'Saturday', 'Sunday' => 'Sunday', 'Monday' => 'Monday', 'Tuesday' => 'Tuesday', 'Wednesday' => 'Wednesday', 'Thursday' => 'Thursday', 'Friday' => 'Friday'];

                if ($lang == 'ar') echo $days_ar[$sch['day_name']];
                elseif ($lang == 'tr') echo $days_tr[$sch['day_name']];
                else echo $days_en[$sch['day_name']];
            ?>
        </td>

        <td data-label="<?= $t['course_col'] ?>" class="p-3 md:p-5">
            <?= htmlspecialchars($sch['course_name']) ?>
        </td>

        <td data-label="<?= $t['time_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl">
            <span class="bg-gray-100 px-3 py-1 rounded-lg text-xs font-black text-gray-800">
                <?php 
                    // تحويل نظام AM/PM حسب اللغة
                    $time_formatted = date('h:i A', strtotime($sch['start_time']));
                    if ($lang == 'ar') {
                        $time_formatted = str_replace(['AM', 'PM'], ['ص', 'م'], $time_formatted);
                    }
                    echo $time_formatted;
                ?>
            </span>
        </td>
    </tr>
    <?php endforeach; else: ?>
    <tr>
        <td colspan="3" class="text-center p-8 opacity-50 font-medium italic text-gray-500">
            <div class="flex flex-col items-center justify-center gap-2">
                <i class="fas fa-calendar-xmark text-3xl mb-1"></i>
                <span>
                    <?php 
                        $no_schedule_text = [
                            'ar' => 'لا يوجد جدول دراسي مسجل حالياً',
                            'en' => 'No schedule available at the moment',
                            'tr' => 'Şu an kayıtlı ders programı bulunmamaktadır'
                        ];
                        echo $no_schedule_text[$lang];
                    ?>
                </span>
            </div>
        </td>
    </tr>
    <?php endif; ?>
</tbody>
                    </table>
                </div>
            </div>

            <div class="space-y-6">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-2 h-6 md:h-8 bg-red-600 rounded-full"></div>
                    <h2 class="text-xl md:text-2xl font-black text-gray-800"><?= $t['attendance_title'] ?></h2>
                </div>
                <div class="overflow-x-visible">
                    <table class="w-full custom-table border-separate border-spacing-y-2">
                        <thead>
                            <tr class="text-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>">
                                <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl"><?= $t['date_col'] ?></th>
                                <th class="p-4 md:p-5"><?= $t['status_col'] ?></th>
                                <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl"><?= $t['teacher_col'] ?></th>
                            </tr>
                        </thead>
                        <tbody class="font-bold text-gray-700">
    <?php if(!empty($attendance_records)): foreach ($attendance_records as $att): ?>
    <tr class="shadow-sm hover:shadow-md transition-all">
        <td data-label="<?= $t['date_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl text-xs">
            <?= $att['attendance_date'] ?>
        </td>

        <td data-label="<?= $t['status_col'] ?>" class="p-3 md:p-5">
            <?php 
                // 1. خريطة الألوان (CSS Classes)
                $status_map = [
                    'حضور'   => 'status-attendance', // أخضر
                    'غياب'   => 'status-absence',    // أحمر
                    'استئذان' => 'status-excuse',     // أصفر
                    'تأخير'  => 'status-late'        // برتقالي
                ];
                $s_class = isset($status_map[$att['status']]) ? $status_map[$att['status']] : 'bg-gray-100 text-gray-600';

                // 2. مصفوفة الترجمة الشاملة للحالات
                $status_translations = [
                    'ar' => ['حضور' => 'حضور', 'غياب' => 'غياب', 'استئذان' => 'استئذان', 'تأخير' => 'تأخير'],
                    'en' => ['حضور' => 'Present', 'غياب' => 'Absent', 'استئذان' => 'Excused', 'تأخير' => 'Late'],
                    'tr' => ['حضور' => 'Burada', 'غياب' => 'Yok', 'استئذان' => 'İzinli', 'تأخير' => 'Gecikti']
                ];

                // جلب النص بناءً على اللغة المفعلة
                $s_text = isset($status_translations[$lang][$att['status']]) 
                          ? $status_translations[$lang][$att['status']] 
                          : $att['status'];
            ?>
            <span class="status-badge <?= $s_class ?> inline-flex items-center gap-1">
                <?php if($att['status'] == 'استئذان'): ?>
                    <span class="text-[10px]">⚠️</span>
                <?php elseif($att['status'] == 'تأخير'): ?>
                    <span class="text-[10px]">⏰</span>
                <?php endif; ?>
                <?= $s_text ?>
            </span>
        </td>

        <td data-label="<?= $t['teacher_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl text-xs">
            <?= htmlspecialchars($att['teacher_name']) ?>
        </td>
    </tr>
    <?php endforeach; else: ?>
    <tr>
        <td colspan="3" class="text-center p-8 opacity-50 font-medium italic text-gray-500">
            <div class="flex flex-col items-center justify-center gap-2">
                <i class="fas fa-clipboard-question text-3xl mb-1"></i>
                <span>
                    <?php 
                        // ترجمة فورية للرسالة
                        $no_att_text = [
                            'ar' => 'لا يوجد سجلات حضور حالياً',
                            'en' => 'No attendance records found',
                            'tr' => 'Henüz yoklama kaydı bulunmamaktadır'
                        ];
                        echo $no_att_text[$lang];
                    ?>
                </span>
            </div>
        </td>
    </tr>
    <?php endif; ?>
</tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 md:gap-10">
           <div class="lg:col-span-2 space-y-6">
    <div class="flex items-center gap-3 mb-2">
        <div class="w-2 h-6 md:h-8 bg-[#c5a059] rounded-full"></div>
        <h2 class="text-xl md:text-2xl font-black text-gray-800"><?= $t['registered_courses'] ?></h2>
    </div>
    <div class="overflow-x-visible">
        <table class="w-full custom-table border-separate border-spacing-y-2">
            <thead>
                <tr class="text-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>">
                    <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl"><?= $t['course_col'] ?></th>
                    <th class="p-4 md:p-5"><?= $t['fees_col'] ?></th>
                    <th class="p-4 md:p-5"><?= $t['system_col'] ?></th>
                    <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl text-center"><?= $t['rating_col'] ?></th>
                </tr>
            </thead>
            <tbody class="font-bold text-gray-700">
                <?php if (!empty($enrollments)): foreach ($enrollments as $en): 
                    $stmt2 = $conn->prepare("SELECT rating FROM course_ratings WHERE enrollment_id=? AND student_id=?");
                    $stmt2->execute([$en['enrollment_id'], $student_id]);
                    $existingRating = $stmt2->fetchColumn() ?: 0;
                ?>
                <tr class="shadow-sm hover:shadow-md transition-all">
                    <td data-label="<?= $t['course_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl">
                        <div class="flex items-center gap-3">
                            <div class="hidden sm:flex w-10 h-10 bg-gray-100 rounded-lg items-center justify-center text-[#c5a059]"><i class="fas fa-graduation-cap"></i></div>
                            <span class="text-sm md:text-base"><?= htmlspecialchars($en['course_name']) ?></span>
                        </div>
                    </td>
                    <td data-label="<?= $t['fees_col'] ?>" class="p-3 md:p-5 text-gray-900"><?= number_format($en['price'], 2) ?> <?= $t['currency'] ?></td>
                    <td data-label="<?= $t['system_col'] ?>" class="p-3 md:p-5">
                        <?php 
                            $system_translations = [
                                'ar' => ['وجاهي' => 'وجاهي', 'أونلاين' => 'أونلاين', 'اونلاين' => 'أونلاين'],
                                'en' => ['وجاهي' => 'In-Person', 'أونلاين' => 'Online', 'اونلاين' => 'Online'],
                                'tr' => ['وجاهي' => 'Yüz Yüze', 'أونلاين' => 'Uzaktan Eğitim', 'اونلاين' => 'Uzaktan Eğitim']
                            ];
                            $current_system = trim($en['attendance_type']);
                            $display_system = isset($system_translations[$lang][$current_system]) ? $system_translations[$lang][$current_system] : $current_system;
                        ?>
                        <span class="px-2 md:px-3 py-1 bg-beige text-[#c5a059] border border-[#c5a059]/20 rounded-lg text-[10px] md:text-xs">
                            <?= htmlspecialchars($display_system) ?>
                        </span>
                    </td>
                    <td data-label="<?= $t['rating_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl">
                        <div class="stars flex justify-center gap-1" data-enrollment="<?= $en['enrollment_id'] ?>">
                            <?php for($i=1;$i<=5;$i++): ?>
                                <span class="star cursor-pointer text-lg md:text-xl transition-colors <?= ($existingRating >= $i) ? 'text-[#c5a059]' : 'text-gray-200' ?>" data-value="<?= $i ?>">&#9733;</span>
                            <?php endfor; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; else: ?>
                <tr>
                    <td colspan="4" class="text-center p-12 opacity-50 font-medium italic text-gray-500">
                        <div class="flex flex-col items-center justify-center gap-2">
                            <i class="fas fa-book-open text-4xl mb-2 text-gray-300"></i>
                            <span>
                                <?php 
                                    $no_courses_text = [
                                        'ar' => 'لم تقم بالتسجيل في أي دورة تعليمية بعد',
                                        'en' => 'You have not registered for any courses yet',
                                        'tr' => 'Henüz herhangi bir kursa kayıt yaptırmadınız'
                                    ];
                                    echo $no_courses_text[$lang];
                                ?>
                            </span>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

            <div class="space-y-6">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-2 h-6 md:h-8 bg-gray-800 rounded-full"></div>
                    <h2 class="text-xl md:text-2xl font-black text-gray-800"><?= $t['news_title'] ?></h2>
                </div>
                <div class="space-y-4">
                    <?php if(!empty($announcements)): foreach($announcements as $ann): ?>
                        <div class="announcement-card p-5 md:p-6 group">
                            <h3 class="font-black text-sm md:text-base text-gray-800 mb-2 group-hover:text-[#c5a059] transition-colors"><?= htmlspecialchars($ann['title']) ?></h3>
                            <p class="text-gray-500 text-xs md:text-sm leading-relaxed mb-4"><?= nl2br(htmlspecialchars($ann['message'])) ?></p>
                            <div class="flex justify-between items-center border-t pt-3 text-[9px] md:text-[10px] font-bold text-gray-400 italic">
                                <span><i class="far fa-calendar-alt m<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-1"></i> <?= date('d-m-Y', strtotime($ann['created_at'])) ?></span>
                                <i class="fas fa-bullhorn text-gray-200"></i>
                            </div>
                        </div>
                    <?php endforeach; else: ?>
                        <div class="text-center py-10 opacity-30">
                            <i class="fas fa-inbox text-4xl mb-3"></i>
                            <p class="font-bold text-sm"><?= $t['no_news'] ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

       <section class="space-y-6 pb-12">
    <div class="flex items-center gap-3 mb-2">
        <div class="w-2 h-6 md:h-8 bg-green-600 rounded-full"></div>
        <h2 class="text-xl md:text-2xl font-black text-gray-800"><?= $t['payments_log'] ?></h2>
    </div>
    <div class="overflow-x-visible">
        <table class="w-full custom-table border-separate border-spacing-y-2">
            <thead>
                <tr class="text-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>">
                    <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl"><?= $t['amount_col'] ?></th>
                    <th class="p-4 md:p-5"><?= $t['discount_col'] ?></th>
                    <th class="p-4 md:p-5 text-center"><?= $t['date_col'] ?></th>
                    <th class="p-4 md:p-5"><?= $t['method_col'] ?></th>
                    <th class="p-4 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl"><?= $t['notes_col'] ?></th>
                </tr>
            </thead>
            <tbody class="font-bold text-gray-700">
                <?php if (!empty($payments)): foreach ($payments as $p): ?>
                <tr class="shadow-sm hover:shadow-md transition-all">
                    <td data-label="<?= $t['amount_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'r' : 'l') ?>-2xl">
                        <span class="text-green-600"><?= number_format($p['amount_paid'], 2) ?> <?= $t['currency'] ?></span>
                    </td>
                    <td data-label="<?= $t['discount_col'] ?>" class="p-3 md:p-5 text-red-600"><?= number_format($p['discount'], 2) ?></td>
                    <td data-label="<?= $t['date_col'] ?>" class="p-3 md:p-5 text-center text-xs">
                        <span class="bg-gray-50 px-2 py-1 rounded-full"><?= $p['payment_date'] ?></span>
                    </td>
                    <td data-label="<?= $t['method_col'] ?>" class="p-3 md:p-5">
                        <?php 
                            $method_translations = [
                                'ar' => ['نقداً' => 'نقداً', 'فيزا' => 'فيزا', 'كليك' => 'كليك', 'تحويل بنكي' => 'تحويل بنكي'],
                                'en' => ['نقداً' => 'Cash', 'فيزا' => 'Visa/Card', 'كليك' => 'CliQ', 'تحويل بنكي' => 'Bank Transfer'],
                                'tr' => ['نقداً' => 'Nakit', 'فيزا' => 'Kredi Kartı', 'كليك' => 'CliQ', 'تحويل بنكي' => 'Banka Havalesi']
                            ];
                            $current_method = trim($p['payment_method']);
                            $display_method = isset($method_translations[$lang][$current_method]) ? $method_translations[$lang][$current_method] : $current_method;
                        ?>
                        <span class="px-2 py-1 bg-beige text-[#c5a059] rounded-lg text-[10px]">
                            <?= htmlspecialchars($display_method) ?>
                        </span>
                    </td>
                    <td data-label="<?= $t['notes_col'] ?>" class="p-3 md:p-5 rounded-<?= ($t['dir'] == 'rtl' ? 'l' : 'r') ?>-2xl text-[10px] font-normal">
                        <?php 
                            $notes_translations = [
                                'ar' => ['مدفوع' => 'مدفوع', 'غير مدفوع' => 'غير مدفوع', 'متبقي' => 'يوجد متبقي', 'مدفوع جزئيا' => 'مدفوع جزئياً'],
                                'en' => ['مدفوع' => 'Paid', 'غير مدفوع' => 'Unpaid', 'متبقي' => 'Balance Due', 'مدفوع جزئيا' => 'Partially Paid'],
                                'tr' => ['مدفوع' => 'Ödendi', 'غير مدفوع' => 'Ödenmedi', 'متبقي' => 'Bakiye Var', 'مدفوع جزئيا' => 'Kısmen Ödendi']
                            ];
                            $current_note = trim($p['notes']);
                            $display_note = $current_note;
                            foreach ($notes_translations[$lang] as $key => $val) {
                                if (stripos($current_note, $key) !== false) {
                                    $display_note = $val;
                                    break;
                                }
                            }
                        ?>
                        <?= htmlspecialchars($display_note) ?: $t['no_notes'] ?>
                    </td>
                </tr>
                <?php endforeach; else: ?>
                <tr>
                    <td colspan="5" class="text-center p-12 opacity-50 font-medium italic text-gray-500">
                        <div class="flex flex-col items-center justify-center gap-2">
                            <i class="fas fa-receipt text-4xl mb-2 text-gray-300"></i>
                            <span>
                                <?php 
                                    $no_payments_text = [
                                        'ar' => 'لا يوجد دفعات مالية مسجلة حالياً',
                                        'en' => 'No financial payments recorded yet',
                                        'tr' => 'Henüz kayıtlı bir ödeme bulunmamaktadır'
                                    ];
                                    echo $no_payments_text[$lang];
                                ?>
                            </span>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</section>
    </main>

   <footer class="bg-[#1a1a1a] text-white border-t-4 border-[#c5a059] mt-auto">
        <div class="max-w-7xl mx-auto px-4 md:px-6 py-8 md:py-12">
            <div class="flex flex-col md:flex-row justify-between items-center gap-8">
                
                <div class="flex flex-col items-center md:items-start text-center md:text-<?= ($t['dir'] == 'rtl' ? 'right' : 'left') ?>">
                    <div class="bg-white p-2 rounded-xl shadow-lg mb-4 inline-block">
                        <img src="../assets/cropped-logo.png" alt="logo" class="h-12 md:h-16 w-auto object-contain">
                    </div>
                    <p class="text-gray-400 text-xs md:text-sm max-w-xs leading-relaxed"><?= $t['footer_desc'] ?></p>
                </div>
                
                <div class="flex flex-col items-center gap-3 md:gap-4">
                    <h4 class="font-bold text-gray-400 uppercase text-[10px] md:text-xs tracking-widest"><?= $t['contact_us'] ?></h4>
                    <div class="flex gap-4">
                        <a href="https://m.facebook.com/LughatAlArabInstitute/" class="w-10 h-10 md:w-11 md:h-11 bg-white/5 text-white rounded-xl flex items-center justify-center hover:bg-[#c5a059] transition-all"><i class="fab fa-facebook-f"></i></a>
                        <a href="https://www.instagram.com/lughatalarabinstitute?igsh=MXVxMnlzeDYybDF6cw==" class="w-10 h-10 md:w-11 md:h-11 bg-white/5 text-white rounded-xl flex items-center justify-center hover:bg-[#c5a059] transition-all"><i class="fab fa-instagram"></i></a>
                        <a href="https://wa.me/962775400430" target="_blank" class="w-10 h-10 md:w-11 md:h-11 bg-white/5 text-white rounded-xl flex items-center justify-center hover:bg-green-600 transition-all">
                            <i class="fab fa-whatsapp text-xl md:text-2xl"></i>
                        </a>
                    </div>
                </div>

                <div class="text-center md:text-<?= ($t['dir'] == 'rtl' ? 'left' : 'right') ?>">
                    <p class="text-gray-500 text-[10px] md:text-xs font-bold uppercase tracking-widest">&copy; <?= date('Y') ?> <?= $t['inst_name'] ?></p>
                    <p class="text-[#c5a059] text-[9px] md:text-[10px] font-black uppercase tracking-[0.3em] mt-1">Lughat AlArab Institute</p>
                </div>
            </div>
        </div>
    </footer>


    <script>
    document.addEventListener('DOMContentLoaded', () => {
        // Star Rating Logic
        document.querySelectorAll('.stars').forEach(container => {
            const stars = container.querySelectorAll('.star');
            const enrollmentId = container.dataset.enrollment;

            stars.forEach(star => {
                star.addEventListener('click', () => {
                    const val = parseInt(star.dataset.value);
                    stars.forEach(s => s.classList.toggle('text-[#c5a059]', s.dataset.value <= val));
                    stars.forEach(s => s.classList.toggle('text-gray-200', s.dataset.value > val));

                    const formData = new FormData();
                    formData.append('enrollment_id', enrollmentId);
                    formData.append('rating', val);

                    fetch('save_rating.php', { method: 'POST', body: formData })
                    .then(r => r.ok ? showToast("تم التقييم بنجاح") : showToast("فشل التقييم", "error"));
                });
            });
        });
    });

    function showToast(m, type = 'success') {
        const t = document.createElement('div');
        t.className = `fixed bottom-10 right-10 ${type === 'success' ? 'bg-[#1a1a1a]' : 'bg-red-900'} text-[#c5a059] border-l-4 border-[#c5a059] px-6 py-3 rounded-xl shadow-2xl z-50 font-black text-sm`;
        t.textContent = m;
        document.body.appendChild(t);
        setTimeout(() => t.remove(), 3000);
    }
    </script>
</body>
</html>