<?php
if (session_status() == PHP_SESSION_NONE) { session_start(); }
include_once 'db_connect.php'; 

// --- دالة الاستعلام الآمن ---
function safeQuery($conn, $sql) {
    try {
        $res = $conn->query($sql);
        if($res) {
            $data = [];
            while($row = $res->fetch_assoc()) { $data[] = $row; }
            return $data;
        }
    } catch (Exception $e) { return []; }
    return [];
}

// 1. معالجة تسجيل الخروج
if (isset($_GET['logout'])) {
    session_destroy();
    echo "<script>window.location.href='login.php';</script>";
    exit;
}

// 2. نظام تسجيل الدخول
if (!isset($_SESSION['parent_id'])) {
    $_SESSION['parent_id'] = 9999; 
    $_SESSION['parent_name'] = 'ولي أمر تجريبي';
}
$parent_id = $_SESSION['parent_id'];

// 3. هندسة جداول الربط
$conn->query("CREATE TABLE IF NOT EXISTS parent_student_link (
    id INT AUTO_INCREMENT PRIMARY KEY, parent_id INT NOT NULL,
    student_name VARCHAR(255) NOT NULL, student_id VARCHAR(100) NULL,
    linked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// التأكد من وجود إعدادات التحكم الزمني للشهادات في قاعدة البيانات
$conn->query("INSERT IGNORE INTO system_settings (setting_key, setting_value) VALUES ('certificate_start_date', '2020-01-01')");
$conn->query("INSERT IGNORE INTO system_settings (setting_key, setting_value) VALUES ('certificate_end_date', '2099-12-31')");
$conn->query("INSERT IGNORE INTO system_settings (setting_key, setting_value) VALUES ('allow_student_certificates', '1')");


// 4. معالجة إنشاء الحساب وتحديث بيانات الأب
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['setup_account'])) {
    $parent_name = $conn->real_escape_string(trim($_POST['parent_name']));
    $phone = $conn->real_escape_string(trim($_POST['phone'])); 
    $password = $conn->real_escape_string(trim($_POST['password']));
    
    $check_user = $conn->query("SELECT id FROM parents WHERE phone = '$phone' OR username = '$phone'");
    if($check_user && $check_user->num_rows > 0) {
        echo "<script>alert('❌ رقم الهاتف مسجل مسبقاً، يرجى استخدام رقم آخر.');</script>";
    } else {
        $school_name_for_parent = '';
        $temp_link_q = $conn->query("SELECT student_id FROM parent_student_link WHERE parent_id = $parent_id LIMIT 1");
        if($temp_link_q && $temp_link_q->num_rows > 0) {
            $linked_st_id = $temp_link_q->fetch_assoc()['student_id'];
            $school_q = $conn->query("SELECT school_name FROM students WHERE student_id = '$linked_st_id' LIMIT 1");
            if($school_q && $school_q->num_rows > 0) {
                $school_name_for_parent = $conn->real_escape_string($school_q->fetch_assoc()['school_name'] ?? '');
            }
        }

        $insert_sql = "INSERT INTO parents (school_name, parent_name, phone, username, password, is_active) 
                       VALUES ('$school_name_for_parent', '$parent_name', '$phone', '$phone', '$password', 1)";
        
        if($conn->query($insert_sql)) {
            $new_parent_id = $conn->insert_id;
            if($parent_id == 9999) {
                $conn->query("UPDATE parent_student_link SET parent_id = $new_parent_id WHERE parent_id = 9999");
            }
            $_SESSION['parent_id'] = $new_parent_id;
            $_SESSION['parent_name'] = $parent_name;
            $parent_id = $new_parent_id;
            
            echo "<script>alert('✅ تم إعداد حسابك بنجاح! يمكنك الآن تسجيل الدخول برقم هاتفك متى شئت.'); window.location.href='parent_dashboard.php';</script>";
        } else {
            echo "<script>alert('❌ حدث خطأ غير متوقع. تأكد من إعدادات قاعدة البيانات.');</script>";
        }
    }
}

// 5. معالجة إلغاء ربط الطالب
if (isset($_GET['unlink_id'])) {
    $unlink_student_id = $conn->real_escape_string($_GET['unlink_id']);
    $conn->query("DELETE FROM parent_student_link WHERE parent_id = $parent_id AND student_id = '$unlink_student_id'");
    echo "<script>alert('✅ تم إزالة الطالب من حسابك بنجاح.'); window.location.href='parent_dashboard.php';</script>";
    exit;
}

// 6. معالجة ربط الطالب الجديد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['link_student'])) {
    $input_id = $conn->real_escape_string(trim($_POST['student_id_input'] ?? ''));
    
    $check_student = $conn->query("SELECT student_name, student_id FROM students WHERE student_id = '$input_id' LIMIT 1");
    if($check_student && $check_student->num_rows > 0) {
        $st_data = $check_student->fetch_assoc();
        $st_name = $conn->real_escape_string($st_data['student_name']);
        $st_id = $conn->real_escape_string($st_data['student_id']);
        
        $check_link = $conn->query("SELECT id FROM parent_student_link WHERE parent_id = $parent_id AND student_id = '$st_id'");
        if($check_link && $check_link->num_rows == 0) {
            $conn->query("INSERT INTO parent_student_link (parent_id, student_name, student_id) VALUES ($parent_id, '$st_name', '$st_id')");
            echo "<script>alert('✅ تم ربط الطالب [$st_name] بنجاح!'); window.location.href='parent_dashboard.php';</script>";
        } else {
            echo "<script>alert('⚠️ هذا الطالب مرتبط بحسابك بالفعل.'); window.location.href='parent_dashboard.php';</script>";
        }
    } else {
        echo "<script>alert('❌ المعرف غير صحيح أو غير موجود في قاعدة بيانات المدرسة.');</script>";
    }
}

// 7. جلب أبناء ولي الأمر
$my_children = [];
$children_query = $conn->query("SELECT id, student_name, student_id FROM parent_student_link WHERE parent_id = $parent_id");
if($children_query) { while($child = $children_query->fetch_assoc()) { $my_children[] = $child; } }

// 8. جلب كل بيانات الابن النشط الحقيقية
$active_child_id = $_GET['child_id'] ?? ($my_children[0]['student_id'] ?? null);

$transport_data = null;
$student_info = null;
$active_child_name = "";
$absences = [];
$grades = [];
$schedule = [];
$notifications = [];

if($active_child_id) {
    $esc_id = $conn->real_escape_string($active_child_id);
    
    $student_info_q = $conn->query("SELECT * FROM students WHERE student_id = '$esc_id' LIMIT 1");
    if($student_info_q && $student_info_q->num_rows > 0) { 
        $student_info = $student_info_q->fetch_assoc(); 
        $active_child_name = $student_info['student_name'];
    }
    
    $esc_name = $conn->real_escape_string($active_child_name);

    $trans_q = $conn->query("SELECT st.*, b.bus_number, b.driver_name, b.driver_phone, b.supervisor_name, b.traccar_device_id, b.camera_stream_url FROM student_transport st JOIN school_buses b ON st.bus_id = b.id WHERE st.student_name = '$esc_name' LIMIT 1");
    if($trans_q) { $transport_data = $trans_q->fetch_assoc(); }

    $absences = safeQuery($conn, "SELECT * FROM attendance WHERE student_id = '$esc_id' ORDER BY attendance_date DESC LIMIT 30");
    $grades = safeQuery($conn, "SELECT * FROM academic_grades WHERE student_id = '$esc_id' ORDER BY id DESC");

    $notifications = safeQuery($conn, "SELECT * FROM notifications WHERE student_id = '$esc_id' OR student_id = 'all' ORDER BY id DESC LIMIT 10");
}

// جلب لوجو واسم المدرسة للهوية البصرية
$school_logo = '';
$display_school_name = 'Roozmari Parent';

if ($student_info && !empty($student_info['school_name'])) {
    $sc_name_esc = $conn->real_escape_string($student_info['school_name']);
    $sc_q = $conn->query("SELECT school_name, school_logo FROM schools WHERE school_name = '$sc_name_esc' LIMIT 1");
    if ($sc_q && $sc_q->num_rows > 0) {
        $sc_data = $sc_q->fetch_assoc();
        $display_school_name = $sc_data['school_name'];
        $school_logo = $sc_data['school_logo'];
    }
} else {
    $sc_q = $conn->query("SELECT school_name, school_logo FROM schools LIMIT 1");
    if ($sc_q && $sc_q->num_rows > 0) {
        $sc_data = $sc_q->fetch_assoc();
        $display_school_name = $sc_data['school_name'];
        $school_logo = $sc_data['school_logo'];
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة ولي الأمر | <?= htmlspecialchars($display_school_name) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <?php require_once 'theme_lang_loader.php'; ?>
    <style>
        /* 🚀 تم تعديل الخلفية إلى تدرج سمائي فاتح مريح جداً للعين 🚀 */
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: linear-gradient(180deg, #f0f9ff 0%, #e0f2fe 100%) !important; color: #334155; padding: 0; margin: 0; min-height: 100vh; }
        
        .navbar { background: #1e293b; color: #fff; padding: 12px 20px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
        .navbar .logo { font-size: 20px; font-weight: bold; color: #fff; display: flex; align-items: center; gap: 12px; }
        .navbar .logo img { height: 45px; width: 45px; object-fit: contain; background: #fff; padding: 2px; border-radius: 50%; }
        
        .user-actions { display: flex; gap: 15px; align-items: center; }
        .nav-btn { background: rgba(255,255,255,0.1); color: #fff; border: 1px solid rgba(255,255,255,0.2); padding: 8px 15px; border-radius: 20px; font-size: 13px; font-weight: bold; cursor: pointer; text-decoration: none; display: flex; align-items: center; gap: 6px; transition: 0.3s; }
        .nav-btn:hover { background: rgba(255,255,255,0.2); }
        .nav-btn.logout { background: #ef4444; border-color: #dc2626; }
        .nav-btn.logout:hover { background: #dc2626; }

        .child-tabs { display: flex; gap: 10px; padding: 15px 20px; background: #fff; overflow-x: auto; box-shadow: 0 1px 3px rgba(0,0,0,0.1); align-items: center; }
        .child-tab { padding: 10px 20px; background: #f1f5f9; border-radius: 20px; color: #475569; text-decoration: none; font-weight: bold; font-size: 14px; white-space: nowrap; border: 1px solid #cbd5e1; transition: 0.3s; cursor:pointer; }
        .child-tab.active { background: #3b82f6; color: #fff; border-color: #3b82f6; box-shadow: 0 2px 10px rgba(59,130,246,0.3); }
        .add-btn { background: #10b981; color: white; border: none; padding: 10px 20px; border-radius: 20px; font-weight: bold; cursor: pointer; display: flex; align-items: center; gap: 5px; font-size: 14px; margin-right: auto; }
        .container { padding: 20px; max-width: 1200px; margin: 0 auto; }
        
        .unlink-btn { background: #fee2e2; color: #ef4444; padding: 6px 12px; border-radius: 6px; font-size: 13px; font-weight: bold; text-decoration: none; display: flex; align-items: center; gap: 5px; border: 1px solid #fca5a5; transition: 0.3s; }
        .unlink-btn:hover { background: #ef4444; color: white; }

        .widgets-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; }
        .widget { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e2e8f0; border-top: 4px solid #3b82f6; }
        .widget.widget-transport { border-top-color: #f59e0b; }
        .widget.widget-academic { border-top-color: #10b981; }
        .widget.widget-notices { border-top-color: #8b5cf6; }
        
        .widget-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .widget-title { font-size: 18px; font-weight: bold; color: #1e293b; display: flex; align-items: center; gap: 8px; }
        .info-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed #e2e8f0; font-size: 14px; }
        
        .action-btn { display: inline-flex; justify-content: center; align-items: center; gap: 8px; width: 100%; padding: 12px; border-radius: 8px; border: none; font-size: 15px; font-weight: bold; cursor: pointer; color: white; transition: 0.2s; margin-top: 10px; }
        .btn-gps { background: #10b981; } .btn-cam { background: #3b82f6; } .btn-view { background: #475569; }
        .action-btn:hover { filter: brightness(1.1); }
        
        .notice-card { background: #f8fafc; border-right: 4px solid #8b5cf6; padding: 12px; margin-bottom: 10px; border-radius: 4px; font-size: 13px; }
        .notice-card strong { color: #1e293b; display: block; margin-bottom: 5px; font-size: 15px; }
        
        /* Modals */
        .modal-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15,23,42,0.85); z-index:9999; justify-content:center; align-items:center; backdrop-filter: blur(4px); }
        .modal-box { background:#fff; width:95%; max-width:900px; max-height:85vh; overflow-y:auto; border-radius:12px; padding:25px; position:relative; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5); }
        .modal-close { position:absolute; top:15px; left:20px; font-size:30px; cursor:pointer; color:#ef4444; background: #fee2e2; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 50%; z-index: 100; }
        .modal-close:hover { background: #ef4444; color: white; }
        
        table.data-table { width:100%; border-collapse:collapse; margin-top:15px; text-align:center; font-size:14px; }
        table.data-table th, table.data-table td { padding:12px; border:1px solid #e2e8f0; }
        table.data-table th { background:#f8fafc; color:#1e293b; font-weight: bold; border-bottom: 2px solid #cbd5e1; }
        table.data-table tr:hover { background: #f1f5f9; }
        
        /* 🚀 إجبار أي حاوية سوداء على أخذ اللون الشفاف ليظهر السمائي 🚀 */
        .bg-black, [style*="background: black"], [style*="background:#000"] {
            background-color: transparent !important;
        }
    </style>
</head>
<body>

    <div class="navbar">
        <div class="logo">
            <?php if(!empty($school_logo)): ?>
                <img src="<?= htmlspecialchars($school_logo) ?>" alt="Logo" onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($display_school_name) ?>&background=0D8ABC&color=fff'">
            <?php else: ?>
                <i class="fas fa-university"></i>
            <?php endif; ?>
            <?= htmlspecialchars($display_school_name) ?>
        </div>
        
        <div class="user-actions">
            <?php if($parent_id == 9999): ?>
                <button onclick="openModal('accountModal')" class="nav-btn" title="حفظ بياناتك للعودة لاحقاً"><i class="fas fa-user-shield"></i> إنشاء بيانات الدخول</button>
            <?php else: ?>
                <span style="font-size: 14px; margin-left: 10px;">مرحباً، <?= htmlspecialchars($_SESSION['parent_name']) ?></span>
            <?php endif; ?>
            <a href="?logout=1" class="nav-btn logout"><i class="fas fa-sign-out-alt"></i> خروج</a>
        </div>
    </div>

    <?php if(empty($my_children)): ?>
        <div style="background:#fff; max-width:500px; margin:40px auto; padding:30px; text-align:center; border-radius:12px; border-top:4px solid #3b82f6;">
            <i class="fas fa-link" style="font-size:40px; color:#3b82f6; margin-bottom:15px;"></i>
            <h2>ربط حساب طالب</h2>
            <form method="POST">
                <input type="text" name="student_id_input" placeholder="أدخل معرف الطالب (مثال: RM-26-5XPI)" required autocomplete="off" style="width:90%; padding:15px; margin:20px 0; text-align:center; border:2px dashed #cbd5e1; border-radius:8px; font-size:18px;">
                <button type="submit" name="link_student" class="action-btn btn-cam" style="width:90%;">تأكيد وربط الحساب</button>
            </form>
            <p style="color:#94a3b8; font-size:13px; margin-top:15px;">يرجى إدخال الـ ID الخاص بالطالب المتوفر في المدرسة.</p>
        </div>
    <?php else: ?>
        
        <div class="child-tabs">
            <?php foreach($my_children as $child): ?>
                <a href="?child_id=<?= urlencode($child['student_id']) ?>" class="child-tab <?= ($active_child_id == $child['student_id']) ? 'active' : '' ?>">
                    <i class="fas fa-child"></i> <?= htmlspecialchars($child['student_name']) ?>
                </a>
            <?php endforeach; ?>
            <button onclick="openModal('linkModal')" class="add-btn"><i class="fas fa-plus"></i> إضافة طالب آخر</button>
        </div>

        <div class="container">
            <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #cbd5e1; padding-bottom: 15px; margin-top: 0; margin-bottom: 25px;">
                <h2 style="margin: 0; display: flex; align-items: center; gap: 10px; color: #0f172a; font-weight: 900; font-size: 24px;">
                    <i class="fas fa-user-graduate" style="color: #3b82f6;"></i>
                    لوحة الطالب: <span style="color: #3b82f6;"><?= htmlspecialchars($active_child_name) ?></span>
                    <?php if($student_info): ?>
                        <small style="color:#64748b; font-size:15px; font-weight:bold;">
                            (<?= htmlspecialchars($student_info['stage'] ?? '') ?> - <?= htmlspecialchars($student_info['department'] ?? '') ?> - <?= htmlspecialchars($student_info['branch'] ?? '') ?>)
                        </small>
                    <?php endif; ?>
                </h2>
                <a href="?unlink_id=<?= urlencode($active_child_id) ?>" class="unlink-btn" onclick="return confirm('هل أنت متأكد من أنك تريد إزالة بيانات هذا الطالب من حسابك؟')">
                    <i class="fas fa-user-minus"></i> إلغاء ربط الطالب
                </a>
            </div>
            
            <div class="widgets-grid">
                
                <div class="widget widget-academic">
                    <div class="widget-header"><div class="widget-title"><i class="fas fa-graduation-cap widget-icon" style="color:#10b981;"></i> الشؤون الأكاديمية</div></div>
                    
                    <?php if($student_info): ?>
                        <div class="info-row">
                            <span style="color:#475569;">الدرجة الشهرية:</span> 
                            <strong style="color:#3b82f6; font-size:18px;"><?= htmlspecialchars($student_info['month_grade'] ?? '0') ?></strong>
                        </div>
                        <div class="info-row">
                            <span style="color:#475569;">نسبة النجاح:</span> 
                            <strong style="color:#10b981; font-size:18px;"><?= htmlspecialchars($student_info['success_rate'] ?? '0') ?>%</strong>
                        </div>
                        <div class="info-row">
                            <span style="color:#475569;">أيام الغياب الكلية:</span> 
                            <strong style="color:<?= ($student_info['absence_days'] > 0) ? '#ef4444' : '#10b981' ?>; font-size:18px;"><?= htmlspecialchars($student_info['absence_days'] ?? '0') ?> يوم</strong>
                        </div>
                        
                        <?php if(!empty($student_info['teacher_note'])): ?>
                            <div style="background:#fef3c7; border-right:4px solid #f59e0b; padding:12px; margin-top:15px; border-radius:4px;">
                                <strong style="color:#b45309; display:block; margin-bottom:5px;"><i class="fas fa-comment-dots"></i> ملاحظة المعلم:</strong>
                                <span style="color:#92400e; font-size:14px;"><?= htmlspecialchars($student_info['teacher_note']) ?></span>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>

                    <button class="action-btn btn-view" onclick="openModal('absencesModal')" style="margin-top:15px;"><i class="fas fa-calendar-times"></i> سجل الغيابات التفصيلي (<?= count($absences) ?>)</button>
                    <button class="action-btn btn-view" onclick="openModal('gradesModal')"><i class="fas fa-star"></i> سجل الامتحانات والدرجات (<?= count($grades) ?>)</button>
                    <button class="action-btn" style="background:#8b5cf6;" onclick="openModal('scheduleModal')"><i class="fas fa-table"></i> الجدول الدراسي الأسبوعي</button>
                    
                    <?php
                    // 🚀 جلب إعدادات التحكم الزمني للشهادة 🚀
                    $cert_settings_q = $conn->query("SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ('allow_student_certificates', 'certificate_start_date', 'certificate_end_date')");
                    $cert_config = [];
                    if($cert_settings_q) {
                        while($s_row = $cert_settings_q->fetch_assoc()) {
                            $cert_config[$s_row['setting_key']] = $s_row['setting_value'];
                        }
                    }

                    $is_allowed_global = ($cert_config['allow_student_certificates'] ?? '1') === '1';
                    $start_date = $cert_config['certificate_start_date'] ?? '2020-01-01';
                    $end_date = $cert_config['certificate_end_date'] ?? '2099-12-31';
                    $today = date('Y-m-d');
                    
                    // التحقق الزمني الدقيق
                    $is_in_date_range = ($today >= $start_date && $today <= $end_date);
                    $show_certificate_button = ($is_allowed_global && $is_in_date_range);

                    // توليد التوكن الخاص بالطالب
                    $secret_salt = "Rooz" . substr(md5($display_school_name), 0, 10);
                    $child_token = hash('sha256', $active_child_id . $secret_salt);
                    ?>

                    <!-- عرض زر الشهادة بناءً على التوقيت والإعدادات -->
                    <?php if ($show_certificate_button): ?>
                        <button onclick="openChildCertificate('<?= htmlspecialchars($active_child_id); ?>', '<?= $child_token; ?>')" style="width: 100%; margin-top: 10px; background: linear-gradient(135deg, #10b981, #059669); color: #fff; border: none; padding: 12px; border-radius: 8px; font-weight: bold; cursor: pointer; transition: 0.3s; box-shadow: 0 4px 15px rgba(16,185,129,0.3);">
                            <i class="fas fa-file-certificate"></i> استعراض وطباعة الشهادة المدرسية
                        </button>
                    <?php else: ?>
                        <div style="width: 100%; margin-top: 10px; background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px dashed #ef4444; padding: 10px; border-radius: 8px; font-weight: bold; text-align: center; font-size: 0.9rem;">
                            <i class="fas fa-lock"></i> الشهادات محجوبة (إما مغلقة من الإدارة أو خارج فترة العرض)
                        </div>
                    <?php endif; ?>
                </div>

                <div class="widget widget-notices">
                    <div class="widget-header"><div class="widget-title"><i class="fas fa-bell widget-icon" style="color:#8b5cf6;"></i> إشعارات المدرسة</div></div>
                    <div style="max-height:300px; overflow-y:auto; padding-left:5px;">
                        <?php if(!empty($notifications)): ?>
                            <?php foreach($notifications as $notif): ?>
                                <div class="notice-card">
                                    <div style="display:flex; justify-content:space-between;">
                                        <strong><?= htmlspecialchars($notif['title'] ?? 'إشعار إداري') ?></strong>
                                    </div>
                                    <!-- 🚀 تم إزالة htmlspecialchars من هنا ليظهر الزر والـ HTML بشكل حقيقي 🚀 -->
                                    <div style="color:#334155; margin-bottom:8px; line-height:1.5;"><?= $notif['message'] ?? $notif['content'] ?? '' ?></div>
                                    <div style="text-align:left; color:#94a3b8; font-size:11px;"><?= htmlspecialchars($notif['created_at'] ?? '') ?></div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div style="text-align:center; color:#94a3b8; padding:30px 0;"><i class="far fa-bell-slash" style="font-size:30px; margin-bottom:10px;"></i><br>لا توجد إشعارات حالياً</div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="widget widget-transport">
                    <div class="widget-header"><div class="widget-title"><i class="fas fa-bus widget-icon" style="color:#f59e0b;"></i> النقل المدرسي</div></div>
                    <?php if($transport_data): ?>
                        <div class="info-row" style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px dashed #e2e8f0;">
                            <span style="color:#64748b; font-weight: bold;">منطقة النقل:</span> 
                            <strong style="color:#b45309; font-weight: 900;"><?= htmlspecialchars($transport_data['pickup_address'] ?? 'غير محدد') ?></strong>
                        </div>
                        <div class="info-row" style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px dashed #e2e8f0;">
                            <span style="color:#64748b; font-weight: bold;">وقت المرور:</span> 
                            <strong style="color:#0f172a; font-weight: 900;"><i class="far fa-clock" style="color: #3b82f6;"></i> <?= htmlspecialchars($transport_data['pickup_time'] ?? '') ?></strong>
                        </div>
                        <div class="info-row" style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px dashed #e2e8f0;">
                            <span style="color:#64748b; font-weight: bold;">المشرف/المشرفة:</span> 
                            <strong style="color:#0f172a; font-weight: 900;"><?= htmlspecialchars($transport_data['supervisor_name'] ?: 'غير محدد') ?></strong>
                        </div>
                        <div class="info-row" style="display: flex; justify-content: space-between; padding: 12px 0;">
                            <span style="color:#64748b; font-weight: bold;">رقم الموبايل:</span> 
                            <strong dir="ltr" style="color:#0f172a; font-weight: 900;"><?= htmlspecialchars($transport_data['driver_phone'] ?? 'غير متوفر') ?> <i class="fas fa-phone-alt" style="color:#10b981; font-size:12px; margin-left:5px;"></i></strong>
                        </div>
                        
                        <div style="display:flex; gap:10px; margin-top:20px;">
                            <?php if(!empty($transport_data['traccar_device_id'])): 
                                $traccar_val = trim($transport_data['traccar_device_id']);
                                $gps_url = (strpos($traccar_val, 'http') === 0) ? $traccar_val : "http://YOUR_VPS_IP:8082/?deviceId=" . $traccar_val;
                            ?>
                                <button class="action-btn btn-gps" style="flex: 1; background: #10b981; color: #fff; padding: 12px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 6px rgba(16,185,129,0.2); transition: 0.3s;" onclick="openLiveView('<?= htmlspecialchars($gps_url) ?>')"><i class="fas fa-map-marker-alt"></i> تتبع الخريطة</button>
                            <?php endif; ?>
                            
                            <?php if(!empty($transport_data['camera_stream_url'])): ?>
                                <button class="action-btn btn-cam" style="flex: 1; background: #3b82f6; color: #fff; padding: 12px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 6px rgba(59,130,246,0.2); transition: 0.3s;" onclick="openLiveView('<?= htmlspecialchars($transport_data['camera_stream_url']) ?>')"><i class="fas fa-video"></i> بث الكاميرا</button>
                            <?php endif; ?>
                        </div>
                        
                        <?php if(empty($transport_data['traccar_device_id']) && empty($transport_data['camera_stream_url'])): ?>
                            <div style="text-align:center; color:#64748b; font-weight:bold; font-size: 13px; margin-top: 15px; padding: 12px; background: #f1f5f9; border-radius: 8px; border: 1px dashed #cbd5e1;">لا توجد روابط تتبع أو كاميرا مضافة لهذا الباص حالياً</div>
                        <?php endif; ?>
                        
                    <?php else: ?>
                        <div style="text-align:center; color:#94a3b8; padding:30px 0;"><i class="fas fa-route" style="font-size:40px; margin-bottom:10px; opacity:0.5;"></i><br>الطالب غير مسجل في خطوط النقل</div>
                    <?php endif; ?>
                </div>

        <div id="liveModal" class="modal-overlay">
            <div class="modal-box" style="height: 75vh; display: flex; flex-direction: column; padding: 0; overflow: hidden; max-width: 1000px;">
                <div style="background: #1e293b; padding: 15px; display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="color: white; margin: 0; font-size: 16px;"><i class="fas fa-satellite-dish" style="color: #10b981;"></i> نافذة المراقبة المباشرة</h3>
                    <span onclick="closeLiveView()" style="color: #ef4444; font-size: 28px; cursor: pointer; line-height: 1;">&times;</span>
                </div>
                <div id="liveModalContent" style="flex: 1; background: #000;"></div>
            </div>
        </div>

        <div id="accountModal" class="modal-overlay">
            <div class="modal-box" style="max-width:400px; text-align:center;">
                <span class="modal-close" onclick="closeModal('accountModal')">×</span>
                <div style="background:#eff6ff; padding:20px; border-radius:12px; margin-bottom:20px;">
                    <i class="fas fa-user-shield" style="font-size:40px; color:#3b82f6; margin-bottom:10px;"></i>
                    <h3 style="color:#1e293b; margin:0;">إنشاء بيانات الدخول</h3>
                    <p style="color:#64748b; font-size:13px; margin-top:5px;">هذه البيانات ستسمح لك بتسجيل الدخول مستقبلاً لمتابعة أبنائك.</p>
                </div>
                <form method="POST">
                    <div style="text-align: right; margin-bottom: 15px;">
                        <label style="font-size:14px; font-weight:bold; color:#475569;">الاسم الكامل لولي الأمر:</label>
                        <input type="text" name="parent_name" value="<?= htmlspecialchars($_SESSION['parent_name'] == 'ولي أمر تجريبي' ? '' : $_SESSION['parent_name']) ?>" placeholder="اكتب اسمك الثلاثي" required autocomplete="off" style="width:100%; box-sizing:border-box; padding:12px; margin-top:5px; border:1px solid #cbd5e1; border-radius:8px; outline:none;">
                    </div>
                    <div style="text-align: right; margin-bottom: 15px;">
                        <label style="font-size:14px; font-weight:bold; color:#475569;">رقم الهاتف (يُستخدم للدخول):</label>
                        <input type="text" name="phone" placeholder="مثال: 07500000000" required autocomplete="off" style="width:100%; box-sizing:border-box; padding:12px; margin-top:5px; border:1px solid #cbd5e1; border-radius:8px; outline:none; text-align:left; direction:ltr;">
                    </div>
                    <div style="text-align: right; margin-bottom: 20px;">
                        <label style="font-size:14px; font-weight:bold; color:#475569;">كلمة المرور:</label>
                        <input type="password" name="password" placeholder="اكتب كلمة مرور قوية" required autocomplete="off" style="width:100%; box-sizing:border-box; padding:12px; margin-top:5px; border:1px solid #cbd5e1; border-radius:8px; outline:none;">
                    </div>
                    <button type="submit" name="setup_account" class="action-btn btn-gps"><i class="fas fa-save"></i> إنشاء وحفظ الحساب</button>
                </form>
            </div>
        </div>

        <div id="linkModal" class="modal-overlay">
            <div class="modal-box" style="max-width:500px; text-align:center;">
                <span class="modal-close" onclick="closeModal('linkModal')">×</span>
                <h3 style="color:#1e293b; margin-top:0;">إضافة طالب آخر للحساب</h3>
                <form method="POST">
                    <input type="text" name="student_id_input" placeholder="أدخل معرف الطالب (مثال: RM-26-VR1X)" required autocomplete="off" style="width:90%; padding:15px; margin:20px 0; text-align:center; border:2px dashed #cbd5e1; border-radius:8px; font-size:18px;">
                    <button type="submit" name="link_student" class="action-btn btn-gps" style="width:90%;">تأكيد وربط الحساب</button>
                </form>
            </div>
        </div>

        <div id="absencesModal" class="modal-overlay">
            <div class="modal-box">
                <span class="modal-close" onclick="closeModal('absencesModal')">×</span>
                <h3 style="color:#1e293b; margin-top:0; border-bottom: 2px solid #e2e8f0; padding-bottom: 10px;"><i class="fas fa-calendar-times"></i> سجل غيابات الطالب التفصيلي</h3>
                <?php if(!empty($absences)): ?>
                    <table class="data-table">
                        <tr><th>التاريخ</th><th>الحالة</th><th>ملاحظات</th></tr>
                        <?php foreach($absences as $ab): 
                            $status_val = strtolower($ab['status'] ?? '');
                            $status_text = ($status_val == 'absent') ? 'غائب' : (($status_val == 'present') ? 'حاضر' : ($ab['status'] ?? 'غائب'));
                            $status_color = ($status_val == 'absent' || $status_val == 'غائب بدون عذر') ? '#ef4444' : '#10b981';
                        ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($ab['attendance_date'] ?? $ab['date'] ?? 'غير محدد') ?></strong></td>
                                <td style="color:<?= $status_color ?>; font-weight:bold;"><?= htmlspecialchars($status_text) ?></td>
                                <td><?= htmlspecialchars($ab['reason'] ?? $ab['notes'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </table>
                <?php else: ?>
                    <p style="text-align:center; color:#10b981; font-weight:bold; padding:20px; background:#f0fdf4; border-radius:8px;">لم يتم تسجيل أي غيابات للطالب في هذا السجل.</p>
                <?php endif; ?>
            </div>
        </div>

        <div id="gradesModal" class="modal-overlay">
            <div class="modal-box">
                <span class="modal-close" onclick="closeModal('gradesModal')">×</span>
                <h3 style="color:#1e293b; margin-top:0; border-bottom: 2px solid #e2e8f0; padding-bottom: 10px;"><i class="fas fa-star"></i> سجل الدرجات والامتحانات الإضافية</h3>
                <?php if(!empty($grades)): ?>
                    <table class="data-table">
                        <tr><th>المادة</th><th>نوع الامتحان</th><th>الدرجة</th></tr>
                        <?php foreach($grades as $g): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($g['subject_name'] ?? $g['subject'] ?? 'مادة') ?></strong></td>
                                <td><?= htmlspecialchars($g['exam_type'] ?? $g['exam_name'] ?? 'امتحان') ?></td>
                                <td style="font-weight:bold; color:#3b82f6;"><?= htmlspecialchars($g['grade'] ?? $g['mark'] ?? '0') ?> / <?= htmlspecialchars($g['max_grade'] ?? '100') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </table>
                <?php else: ?>
                    <p style="text-align:center; color:#94a3b8; padding:20px; background:#f8fafc; border-radius:8px;">لم يتم رصد درجات إضافية لهذا الطالب في هذا السجل بعد.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- 🚀 النافذة المنبثقة للشهادة (Modal) 🚀 -->
        <div id="parentCertificateModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 100000; align-items: center; justify-content: center;">
            <div style="background: #fff; width: 95%; max-width: 900px; height: 90vh; border-radius: 15px; overflow: hidden; display: flex; flex-direction: column; position: relative;">
                <!-- شريط التحكم العلوي -->
                <div style="background: #1e293b; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="margin: 0; color: #fff;"><i class="fas fa-file-certificate" style="color: #10b981;"></i> الشهادة الأكاديمية للطالب</h3>
                    <div>
                        <button onclick="document.getElementById('parentCertFrame').contentWindow.print()" style="background: #10b981; color: #fff; border: none; padding: 8px 15px; border-radius: 6px; cursor: pointer; margin-left: 10px; font-weight: bold;"><i class="fas fa-print"></i> طباعة / حفظ PDF</button>
                        <button onclick="document.getElementById('parentCertificateModal').style.display='none'" style="background: transparent; color: #ef4444; border: none; font-size: 25px; cursor: pointer; line-height: 1;">&times;</button>
                    </div>
                </div>
                <!-- إطار استدعاء الشهادة -->
                <iframe id="parentCertFrame" src="" style="width: 100%; height: 100%; border: none;"></iframe>
            </div>
        </div>

        <div id="scheduleModal" class="modal-overlay">
            <div class="modal-box" style="max-width:1000px; padding: 0; background: #f8fafc; overflow-y: auto; max-height: 90vh;">
                <span class="modal-close" onclick="closeModal('scheduleModal')" style="z-index: 999; top: 15px; right: auto; left: 15px;">&times;</span>
                
                <div style="background: linear-gradient(135deg, #8b5cf6, #6d28d9); padding: 30px; text-align: center; color: white;">
                    <h2 style="margin: 0; font-size: 2rem; font-weight: 900; text-shadow: 0 2px 4px rgba(0,0,0,0.3);"><i class="fas fa-calendar-alt"></i> الجدول الدراسي الأسبوعي</h2>
                    <p style="margin: 5px 0 0 0; opacity: 0.9;">الطالب: <?= htmlspecialchars($active_child_name) ?></p>
                </div>

                <div style="padding: 30px; overflow-x: auto;">
                    <?php
                    if (!function_exists('superCleanMatch')) {
                        function superCleanMatch($str) {
                            if(empty($str)) return '';
                            $unify = ['أ', 'إ', 'آ', 'ة', 'ه', 'ي', 'ى'];
                            $with  = ['ا', 'ا', 'ا', ' ', ' ', 'ي', 'ي'];
                            $str = str_replace($unify, $with, mb_strtolower(trim($str)));
                            $remove = ['المرحلة', 'المرحله', 'الصف', 'شعبة', 'شعبه', 'قسم'];
                            $str = str_replace($remove, '', $str);
                            $str = preg_replace('/\s+/', '', $str);
                            return $str;
                        }
                    }

                    if ($student_info) {
                        $sg = $student_info['stage'] ?? '';
                        $sd = $student_info['department'] ?? '';
                        $sb = $student_info['branch'] ?? '';
                        
                        $c_sg = superCleanMatch($sg);
                        $c_sd = superCleanMatch($sd);
                        $c_sb = superCleanMatch($sb);

                        $current_school_name = $student_info['school_name'] ?? '';

                        echo '<div style="background: rgba(139, 92, 246, 0.1); border: 1px dashed #8b5cf6; padding: 15px; border-radius: 12px; margin-bottom: 20px; color: #6d28d9; font-weight: bold; text-align: center;">';
                        echo 'الصف: ' . htmlspecialchars($sg) . ' ' . (!empty($sd) && $sd != 'عام' ? ' - ' . htmlspecialchars($sd) : '') . (!empty($sb) && $sb != 'عام' && $sb != 'الكل' ? ' - شعبة ' . htmlspecialchars($sb) : '');
                        echo '</div>';

                        $student_schedule_matrix = [];
                        $days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس'];
                        $std_has_schedule = false;

                        $q_std_sched = "SELECT * FROM generated_schedules WHERE school_name = '" . $conn->real_escape_string($current_school_name) . "' AND is_published = 1";
                        $res_std_sched = @$conn->query($q_std_sched);

                        if ($res_std_sched && $res_std_sched->num_rows > 0) {
                            while($row = $res_std_sched->fetch_assoc()) {
                                
                                $row_sg = superCleanMatch($row['stage_name']);
                                $row_sd = superCleanMatch($row['department_name']);
                                $row_sb = superCleanMatch($row['section_name']);

                                $stage_match = empty($c_sg) || ($c_sg === $row_sg);
                                $dept_match = empty($c_sd) || $sd == 'عام' || ($c_sd === $row_sd);
                                $branch_match = empty($c_sb) || $sb == 'الكل' || $sb == 'عام' || ($c_sb === $row_sb);

                                if ($stage_match && $dept_match && $branch_match) {
                                    $std_has_schedule = true;
                                    $p_num = (int)$row['period_number'];
                                    
                                    $day_db = superCleanMatch($row['day_of_week']);
                                    if (strpos($day_db, 'احد') !== false) $day_key = 'الأحد';
                                    elseif (strpos($day_db, 'اثنين') !== false) $day_key = 'الاثنين';
                                    elseif (strpos($day_db, 'ثلاثاء') !== false) $day_key = 'الثلاثاء';
                                    elseif (strpos($day_db, 'اربعاء') !== false) $day_key = 'الأربعاء';
                                    elseif (strpos($day_db, 'خميس') !== false) $day_key = 'الخميس';
                                    else $day_key = trim($row['day_of_week']);

                                    $student_schedule_matrix[$day_key][$p_num] = $row;
                                }
                            }
                        }
                    } else {
                        $std_has_schedule = false;
                    }
                    ?>

                    <div id="printable-schedule-area">
                        <?php if(!$std_has_schedule): ?>
                            <div style="background: rgba(148, 163, 184, 0.1); border: 1px dashed rgba(148, 163, 184, 0.5); border-radius: 20px; padding: 50px; text-align: center;">
                                <i class="fas fa-calendar-times" style="font-size: 5rem; color: #94a3b8; margin-bottom: 20px; opacity: 0.8;"></i>
                                <h3 style="color: #334155; font-size: 1.5rem; margin-bottom: 10px; font-weight: 900;">لا يوجد جدول حالياً</h3>
                                <p style="color: #64748b; font-size: 1rem;">لم تقم إدارة المدرسة بنشر الجدول الأسبوعي لهذا الصف حتى الآن.</p>
                            </div>
                        <?php else: ?>
                            <div style="border-radius: 12px; border: 1px solid #cbd5e1; background: white; box-shadow: 0 10px 25px rgba(0,0,0,0.05);">
                                <table style="width: 100%; border-collapse: collapse; text-align: center; font-family: 'Tajawal', sans-serif;">
                                    <thead>
                                        <tr style="background-color: #8b5cf6; color: white;">
                                            <th style="padding: 15px; border: 1px solid #7c3aed; width: 14%;">اليوم</th>
                                            <?php for($i=1; $i<=6; $i++): ?>
                                            <th style="padding: 15px; border: 1px solid #7c3aed; width: 14%;">الحصة <?= $i ?></th>
                                            <?php endfor; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($days as $day): ?>
                                            <tr style="transition: 0.2s;" onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                                                <td style="padding: 15px; font-weight: bold; color: #6d28d9; background: #f3e8ff; border: 1px solid #cbd5e1;"><?= $day ?></td>
                                                <?php for($p=1; $p<=6; $p++): ?>
                                                    <td style="padding: 15px; border: 1px solid #cbd5e1; vertical-align: middle;">
                                                        <?php if(isset($student_schedule_matrix[$day][$p])): $cell = $student_schedule_matrix[$day][$p]; ?>
                                                            <div style="background: rgba(139, 92, 246, 0.1); border: 1px solid rgba(139, 92, 246, 0.3); padding: 10px; border-radius: 8px; display: inline-block; width: 100%; min-width: 80px;">
                                                                <div style="font-weight: 900; font-size: 1.1rem; color: #6d28d9; margin-bottom: 5px;">
                                                                    <?= htmlspecialchars($cell['subject_name']) ?>
                                                                </div>
                                                                <div style="font-size: 0.8rem; color: #475569; font-weight: bold;">
                                                                    <?php
                                                                    $raw_teacher = $cell['teacher_name'];
                                                                    $tech_n = @$conn->query("SELECT display_name FROM teachers WHERE teacher_name = '$raw_teacher' LIMIT 1");
                                                                    if($tech_n && $tech_n->num_rows > 0) {
                                                                        echo htmlspecialchars($tech_n->fetch_assoc()['display_name']);
                                                                    } else {
                                                                        echo htmlspecialchars(trim(preg_replace('/[0-9]+/', '', str_ireplace('teacher_', '', $raw_teacher))));
                                                                    }
                                                                    ?>
                                                                </div>
                                                            </div>
                                                        <?php else: ?>
                                                            <span style="color: #cbd5e1; font-size: 1.2rem;">---</span>
                                                        <?php endif; ?>
                                                    </td>
                                                <?php endfor; ?>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if($std_has_schedule): ?>
                    <div style="text-align: center; margin-top: 25px;">
                        <button onclick="printParentSchedule()" style="background: #1e293b; color: white; border: none; padding: 12px 30px; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 1.1rem; box-shadow: 0 4px 6px rgba(0,0,0,0.1); transition: 0.3s;" onmouseover="this.style.background='#0f172a'" onmouseout="this.style.background='#1e293b'">
                            <i class="fas fa-print"></i> طباعة الجدول
                        </button>
                    </div>
                    <?php endif; ?>

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

    <?php endif; ?>

    <script>
        function openModal(modalId) {
            document.getElementById(modalId).style.display = 'flex';
        }
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function openLiveView(url) {
            const modal = document.getElementById('liveModal');
            const content = document.getElementById('liveModalContent');
            modal.style.display = 'flex';
            content.innerHTML = `<iframe src="${url}" style="width:100%; height:100%; border:none;" allowfullscreen></iframe>`;
        }

        function closeLiveView() {
            document.getElementById('liveModal').style.display = 'none';
            document.getElementById('liveModalContent').innerHTML = ''; 
        }

        // 🚀 دالة فتح الشهادة للابن باستخدام التوكن المشفر 🚀
        function openChildCertificate(childId, token) {
            document.getElementById('parentCertFrame').src = 'print_student_certificate.php?student_id=' + childId + '&token=' + token;
            document.getElementById('parentCertificateModal').style.display = 'flex';
        }

        function printParentSchedule() {
            var printContents = document.getElementById('printable-schedule-area').innerHTML;
            var childName = "<?= htmlspecialchars($active_child_name) ?>";
            var schoolName = "<?= htmlspecialchars($display_school_name) ?>";
            var className = "<?= htmlspecialchars($sg ?? '') ?> <?= (!empty($sd) && $sd != 'عام' ? ' - ' . htmlspecialchars($sd) : '') ?> <?= (!empty($sb) && $sb != 'عام' && $sb != 'الكل' ? ' - شعبة ' . htmlspecialchars($sb) : '') ?>";
            
            let cleanContents = printContents.replace(/style="[^"]*"/g, ''); 
            
            let printFrame = document.createElement('iframe');
            printFrame.style.position = 'fixed';
            printFrame.style.right = '-9999px';
            printFrame.style.bottom = '-9999px';
            printFrame.style.width = '0';
            printFrame.style.height = '0';
            printFrame.style.border = '0';
            document.body.appendChild(printFrame);
            
            let doc = printFrame.contentWindow.document;
            doc.open();
            doc.write(`
                <html dir="rtl">
                <head>
                    <title>طباعة الجدول الأسبوعي</title>
                    <style>
                        @import url("https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;900&display=swap"); 
                        body { font-family: "Tajawal", sans-serif; padding: 20px; color: #000; background: #fff; } 
                        h2, h3 { text-align: center; margin: 5px; } 
                        
                        div { overflow: visible !important; }
                        
                        table { 
                            width: 100% !important; 
                            border-collapse: collapse; 
                            text-align: center; 
                            margin-top: 20px; 
                            page-break-inside: auto;
                        } 
                        tr { page-break-inside: avoid; page-break-after: auto; }
                        th, td { border: 2px solid #000 !important; padding: 12px !important; } 
                        th { 
                            background-color: #f1f5f9 !important; 
                            font-weight: bold; 
                            font-size: 1.2rem; 
                            -webkit-print-color-adjust: exact; 
                            color-adjust: exact;
                        } 
                        td { font-size: 1.1rem; } 
                        
                        @page { size: landscape; margin: 10mm; }
                    </style>
                </head>
                <body>
                    <h2>الجدول الدراسي الأسبوعي</h2>
                    <h3>الطالب: ${childName} | ${className}</h3>
                    <h4 style="text-align:center; color:#555;">${schoolName}</h4>
                    ${cleanContents}
                </body>
                </html>
            `);
            doc.close();
            
            setTimeout(function() {
                printFrame.contentWindow.focus();
                printFrame.contentWindow.print();
                setTimeout(() => { document.body.removeChild(printFrame); }, 2000);
            }, 800);
        }
    </script>
</body>
</html>