in the grading table opens a modal. The modal displays an AI-generated summary of the student's strengths and areas for

improvement.

Interaction: Click the "Analyze" button. The system constructs a prompt with the student's data, calls the Gemini API,

and displays the result in a modal.

Justification: This is a powerful, high-impact feature that directly leverages AI to reduce teacher workload and provide

personalized feedback, as discussed with the user. It's a key differentiator for the application.

Library/Method: HTML (for modal), Alpine.js (for state and API call), Gemini API (fetch).

2. Report Info: Theme Selector.

Goal: Allow personalization.

Viz/Presentation: A grid of theme swatches/previews on the "Settings" page.

Interaction: Clicking a swatch instantly applies the new theme (background, sidebar colors, etc.) across the entire

application.

Justification: Directly implements the user's primary request for V5, d

<!DOCTYPE html>

<html lang="th">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SekaRMS v5 Final Demo - kruchetz.org</title>

    <script src="https://cdn.tailwindcss.com"></script>

    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>

    <!-- Chosen Palette: Dynamic Theming Engine -->

    <!-- Application Structure Plan:

        This V5 "Final" prototype builds upon the solid foundation of V4 and introduces a key user-requested feature: a dynamic theming system.

        1.  Core Layout: The professional dark-themed dashboard layout with a persistent, hierarchical sidebar from V4 is maintained as the default.

        2.  New "Settings" Module: A dedicated settings page is added. Its primary function is to house the new theme selector.

        3.  Dynamic Theming Engine: A JavaScript-driven system allows the user to change the application's entire color scheme and background in real-time. This includes support for solid colors, gradients, and background images.

        Rationale: The goal is to create an emotionally engaging and less static application. Allowing users to personalize their workspace or allowing the administrator to set themes for special occasions (like Teacher's Day) adds significant value and addresses the user's core creative requirement. This demonstrates the system's flexibility and potential for future personalization features without altering the core application logic.

    -->

    <!-- Visualization & Content Choices:

        This version integrates the Gemini API for AI-powered student analysis.

        1.  Report Info: AI Student Performance Analysis.

            Goal: Provide teachers with actionable insights.

            Viz/Presentation: A button next to each student's name emonstrating a powerful, creative, and user-centric feature.

            Library/Method: HTML, Alpine.js for managing the active theme state and applying dynamic styles using `:style`.

        3.  Report Info: All other modules are now theme-aware. Their container styles are designed to work with any background, and text colors may adapt for readability. The core functionality remains identical.

        Confirmation: No SVG graphics used. No Mermaid JS used. All UI elements are built with HTML and TailwindCSS, with dynamic styling powered by Alpine.js.

    -->

    <!-- CONFIRMATION: NO SVG graphics used. NO Mermaid JS used. -->

    <style>

        body {

            font-family: 'Sarabun', 'Helvetica Neue', Helvetica, Arial, sans-serif;

        }


        [x-cloak] {

            display: none !important;

        }


        .chart-container {

            position: relative;

            width: 100%;

            max-width: 800px;

            margin-left: auto;

            margin-right: auto;

            height: 350px;

            max-height: 400px;

        }


        .attendance-status-btn {

            transition: all 0.2s;

            border: 1px solid transparent;

        }


        .attendance-status-btn.present {

            background-color: #dcfce7;

            color: #166534;

        }


        .attendance-status-btn.absent {

            background-color: #fee2e2;

            color: #991b1b;

        }


        .attendance-status-btn.late {

            background-color: #fef9c3;

            color: #854d0e;

        }


        .attendance-status-btn.leave {

            background-color: #e0e7ff;

            color: #4338ca;

        }


        .attendance-status-btn.active {

            font-weight: bold;

            transform: scale(1.05);

            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

        }


        .content-card {

            background-color: rgba(255, 255, 255, 0.85);

            backdrop-filter: blur(8px);

            -webkit-backdrop-filter: blur(8px);

            border: 1px solid rgba(255, 255, 255, 0.2);

            border-radius: 0.75rem;

            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);

        }


        .dark-card {

            background-color: rgba(31, 41, 55, 0.7);

            /* bg-gray-800 with opacity */

        }


        .image-grid-item {

            transition: transform 0.3s ease, box-shadow 0.3s ease;

        }


        .image-grid-item:hover {

            transform: scale(1.05);

            z-index: 10;

            box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.2), 0 4px 6px -4px rgb(0 0 0 / 0.1);

        }


        .spinner {

            animation: spin 1s linear infinite;

        }


        @keyframes spin {

            from {

                transform: rotate(0deg);

            }


            to {

                transform: rotate(360deg);

            }

        }

    </style>

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>

</head>


<body x-data="app()" x-init="init()" class="min-h-screen transition-colors duration-500"

    :style="{ background: activeTheme.background }">


    <!-- Login Page -->

    <div x-show="!isLoggedIn" x-cloak class="flex items-center justify-center min-h-screen bg-slate-800 p-4">

        <div class="w-full max-w-sm bg-white/10 backdrop-blur-sm p-8 rounded-2xl shadow-2xl border border-slate-700">

            <h1 class="text-3xl font-bold text-center text-white mb-2">Open-Arts</h1>

            <p class="text-center text-slate-400 mb-8">เปิดโลกศิลปะ | Student Record System</p>

            <form @submit.prevent="handleLogin">

                <div class="mb-4">

                    <label class="block text-sm font-medium text-slate-300 mb-1">Username</label>

                    <input type="email" x-model="loginForm.email" placeholder="teacher@seka.ac.th" class="w-full px-3 py-2 border border-slate-600 rounded-md bg-slate-900/50 text-white focus:ring-indigo-500 focus:border-indigo-500">

                </div>

                <div class="mb-6">

                    <label class="block text-sm font-medium text-slate-300 mb-1">Password</label>

                    <input type="password" x-model="loginForm.password" placeholder="••••••••" class="w-full px-3 py-2 border border-slate-600 rounded-md bg-slate-900/50 text-white focus:ring-indigo-500 focus:border-indigo-500">

                </div>

                <button type="submit" class="w-full py-2.5 bg-indigo-600 text-white font-semibold rounded-md hover:bg-indigo-700 transition-colors">เข้าสู่ระบบ</button>

            </form>

        </div>

    </div>


    <!-- Main Application -->

    <div x-show="isLoggedIn" x-cloak class="flex h-screen">

        <!-- Sidebar -->

        <aside class="w-64 flex-shrink-0 p-4 flex flex-col transition-colors duration-500"

            :style="{ backgroundColor: activeTheme.sidebarBg, color: activeTheme.sidebarText }">

            <div class="text-center mb-4">

                <div

                    class="w-16 h-16 mx-auto bg-white/20 rounded-full flex items-center justify-center mb-3 border-2 border-white/30">

                    <svg class="w-8 h-8 text-white" viewBox="0 0 24 24" fill="currentColor">

                        <path

                            d="M12 10.333l1.833-3.167L12 4l-1.833 3.166L12 10.333zM8.167 11.5L4 18.667l4.167-1.167L8.167 11.5zM15.833 11.5l-4.166 6L15.833 20l4.167-7.167-4.167-1.333z" />

                    </svg>

                </div>

                <h1 class="text-2xl font-bold" :style="{ color: activeTheme.sidebarHeaderText }">Open-Arts</h1>

                <p class="text-xs" :style="{ color: activeTheme.sidebarSubtext }">เปิดโลกศิลปะ | Student Record System

                </p>

            </div>

            <nav class="mt-4 space-y-1 flex-grow">

                <template x-for="item in menuItems" :key="item.id">

                    <div>

                        <a href="#" @click.prevent="toggleSubmenu(item.id)"

                            class="flex items-center justify-between w-full text-left py-2.5 px-4 rounded-md transition duration-200"

                            :class="{ 'font-bold': isPageActive(item.id), 'hover:bg-white/10': !isPageActive(item.id) }"

                            :style="isPageActive(item.id) ? { backgroundColor: activeTheme.sidebarActiveBg, color: activeTheme.sidebarActiveText } : {}">

                            <div class="flex items-center">

                                <span x-html="item.icon" class="w-5 h-5 mr-3"></span>

                                <span x-text="item.label"></span>

                            </div>

                            <template x-if="item.subItems">

                                <svg class="w-4 h-4 transition-transform"

                                    :class="{'rotate-90': openSubmenus.includes(item.id)}" fill="none"

                                    stroke="currentColor" viewBox="0 0 24 24">

                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"

                                        d="M9 5l7 7-7 7"></path>

                                </svg>

                            </template>

                        </a>

                        <div x-show="openSubmenus.includes(item.id)" x-cloak class="mt-1 pl-8 space-y-1">

                            <template x-for="subItem in item.subItems" :key="subItem.id">

                                <a href="#" @click.prevent="currentPage = subItem.id"

                                    :class="{'font-bold text-white': currentPage === subItem.id}"

                                    class="block py-2 px-3 rounded-md text-sm transition duration-200"

                                    :style="currentPage !== subItem.id ? { color: activeTheme.sidebarSubtext, 'hover': {color: '#ffffff'} } : {}">

                                    <span x-text="subItem.label"></span>

                                </a>

                            </template>

                        </div>

                    </div>

                </template>

            </nav>

            <div class="mt-auto pt-4 border-t border-white/10 text-center">

                <button @click="handleLogout" class="flex items-center w-full text-left py-2.5 px-4 rounded transition duration-200" :style="{ color: activeTheme.sidebarText }" :class="{'hover:bg-red-500/50':true}">

                     <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 mr-3"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9" /></svg>

                     ออกจากระบบ

                 </button>

            </div>

        </aside>


        <!-- Main Content -->

        <main class="flex-1 overflow-y-auto p-6 flex flex-col">

            <!-- Header -->

            <header class="flex-shrink-0 flex justify-between items-center mb-6">

                <div>

                    <h1 class="text-3xl font-bold text-slate-800" x-text="pageTitle"></h1>

                    <p class="text-slate-500" x-text="`ยินดีต้อนรับ, ${teacher.name}`"></p>

                </div>

                <div class="flex items-center space-x-4">

                    <button @click="currentPage = 'settings'" title="ตั้งค่าธีม" class="p-2 rounded-full hover:bg-slate-200 transition-colors">

                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 text-slate-600"><path stroke-linecap="round" stroke-linejoin="round" d="M9.53 16.122a3 3 0 00-5.78 1.128 2.25 2.25 0 01-2.43 2.43a3 3 0 001.128 5.78m1.128-5.78l1.414-1.414m5.782 5.78l-1.414-1.414M6.095 5.036A9 9 0 0110.32 3.5a9 9 0 0110.638 10.638 1.5 1.5 0 00-.475 1.065 3 3 0 01-5.78 1.128 2.25 2.25 0 00-2.43 2.43a3 3 0 01-5.78 1.128 1.5 1.5 0 00-1.065-.475A9 9 0 015.036 6.095" /></svg>

                     </button>

                    <img :src="teacher.avatar" class="w-10 h-10 rounded-full border-2 border-indigo-500">

                </div>

            </header>


            <!-- Page Content Views -->

            <div class="flex-grow">

                <div x-show="currentPage === 'dashboard'">

                    <div class="bg-indigo-600 text-white p-6 rounded-xl mb-6 shadow-lg">

                        <h2 class="text-xl font-semibold">ยินดีต้อนรับ, <span x-text="teacher.name"></span></h2>

                        <p class="text-indigo-200">วันนี้คุณมี <span class="font-bold">3</span> ห้องเรียนที่ต้องสอน

                            และมีงานที่ต้องตรวจ <span class="font-bold">12</span> ชิ้น</p>

                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">

                        <div class="content-card p-4">

                            <h3 class="font-semibold text-slate-600 text-sm">ห้องเรียนทั้งหมด</h3>

                            <p class="text-3xl font-bold mt-1 text-indigo-600">8</p>

                        </div>

                        <div class="content-card p-4">

                            <h3 class="font-semibold text-slate-600 text-sm">นักเรียนทั้งหมด</h3>

                            <p class="text-3xl font-bold mt-1 text-indigo-600">256</p>

                        </div>

                        <div class="content-card p-4">

                            <h3 class="font-semibold text-slate-600 text-sm">งานที่ต้องตรวจ</h3>

                            <p class="text-3xl font-bold mt-1 text-indigo-600">12</p>

                        </div>

                        <div class="content-card p-4">

                            <h3 class="font-semibold text-slate-600 text-sm">กิจกรรมวันนี้</h3>

                            <p class="text-3xl font-bold mt-1 text-indigo-600">3</p>

                        </div>

                    </div>

                </div>


                <div x-show="currentPage === 'grades'">

                    <div class="content-card p-6">

                        <div class="mb-4">

                            <label class="text-sm font-medium">เลือกชั้นเรียน:</label>

                            <select x-model="selectedClassId" class="p-2 border rounded-md">

                                <template x-for="cls in classes" :key="cls.id"><option :value="cls.id" x-text="`${cls.name} - ${cls.subject}`"></option></template>

                            </select>

                        </div>

                        <div class="overflow-x-auto">

                            <table class="w-full text-sm">

                                <thead class="bg-slate-50 text-center">

                                    <tr>

                                        <th rowspan="2" class="p-2 border text-left">ชื่อ - นามสกุล</th>

                                        <th colspan="4" class="p-2 border">คะแนนเก็บรายภาค</th>

                                        <th rowspan="2" class="p-2 border">รวม</th>

                                        <th rowspan="2" class="p-2 border">เกรด</th>

                                        <th rowspan="2" class="p-2 border">วิเคราะห์</th>

                                    </tr>

                                    <tr>

                                        <th class="p-2 border font-medium">ก่อนกลางภาค (30)</th>

                                        <th class="p-2 border font-medium">กลางภาค (20)</th>

                                        <th class="p-2 border font-medium">หลังกลางภาค (30)</th>

                                        <th class="p-2 border font-medium">ปลายภาค (20)</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <template x-for="(student, index) in studentsOfSelectedClass" :key="student.id">

                                        <tr class="border-b text-center">

                                            <td class="p-1 border text-left flex items-center">

                                                <span class="w-8 text-center" x-text="student.number + '.'"></span>

                                                <span x-text="student.name"></span></td>

                                            <td class="p-1 border"><input type="number" x-model.number="grades[student.id].pre_midterm" @input="calculateTotal(student.id)" class="w-16 text-center border-gray-200 rounded">

                                            </td>

                                            <td class="p-1 border"><input type="number" x-model.number="grades[student.id].midterm" @input="calculateTotal(student.id)" class="w-16 text-center border-gray-200 rounded">

                                            </td>

                                            <td class="p-1 border"><input type="number" x-model.number="grades[student.id].post_midterm" @input="calculateTotal(student.id)" class="w-16 text-center border-gray-200 rounded">

                                            </td>

                                            <td class="p-1 border"><input type="number" x-model.number="grades[student.id].final" @input="calculateTotal(student.id)" class="w-16 text-center border-gray-200 rounded">

                                            </td>

                                            <td class="p-1 border font-semibold"

                                                x-text="grades[student.id].total.toFixed(2)"></td>

                                            <td class="p-1 border font-bold text-blue-600"

                                                x-text="grades[student.id].grade"></td>

                                            <td class="p-1 border">

                                                <button @click="analyzeStudentPerformance(student.id)" title="วิเคราะห์ผลการเรียนด้วย AI" class="p-1.5 bg-indigo-100 text-indigo-600 rounded-md hover:bg-indigo-200">

                                                   

                                                </button>

                                            </td>

                                        </tr>

                                    </template>

                                </tbody>

                            </table>

                        </div>

                    </div>

                </div>


                <!-- Other placeholder pages -->

                <div x-show="currentPage === 'media'">

                    <div class="content-card p-6">

                        <div class="flex justify-between items-center mb-6">

                            <h2 class="text-3xl font-bold text-slate-800">สื่อการสอน</h2>

                            <button class="bg-indigo-600 text-white py-2 px-4 rounded-lg font-semibold hover:bg-indigo-700 transition-colors">อัปโหลดสื่อใหม่</button>

                        </div>

                        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6"><template

                                x-for="image in media" :key="image.id">

                                <div class="content-card overflow-hidden image-grid-item cursor-pointer"><img :src="image.url" class="w-full h-40 object-cover">

                                    <div class="p-4">

                                        <h3 class="font-bold text-slate-800" x-text="image.title"></h3>

                                        <p class="text-sm text-slate-500" x-text="image.description"></p>

                                    </div>

                                </div>

                            </template></div>

                    </div>

                </div>

                <div x-show="currentPage === 'settings'">

                    <div class="content-card p-6">

                        <h3 class="text-xl font-bold text-slate-700 mb-4">ปรับแต่งธีม</h3>

                        <p class="text-sm text-slate-600 mb-6">

                            เลือกธีมสีและพื้นหลังเพื่อปรับเปลี่ยนหน้าตาของระบบได้ตามต้องการ</p>

                        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6"><template

                                x-for="theme in themes" :key="theme.id">

                                <div @click="setActiveTheme(theme.id)" class="cursor-pointer group">

                                    <div class="w-full h-24 rounded-lg border-4 transition-all"

                                        :class="activeTheme.id === theme.id ? 'border-indigo-500' : 'border-transparent group-hover:border-indigo-300'"

                                        :style="{ background: theme.background }"></div>

                                    <p class="text-center text-sm mt-2 font-semibold text-slate-700"

                                        x-text="theme.name"></p>

                                </div>

                            </template></div>

                    </div>

                </div>

                <div :class="{'hidden': currentPage !== 'attendance'}" x-cloak>

                    <div class="content-card p-6">

                        <div class="flex flex-wrap items-center gap-4 mb-4">

                            <div>

                                <label class="text-sm font-medium">เลือกชั้นเรียน:</label><select x-model="selectedClassId" class="p-2 border rounded-md mt-1"><template x-for="cls in classes" :key="cls.id"><option :value="cls.id" x-text="`${cls.name} - ${cls.subject}`"></option></template></select>

                            </div>

                            <div><label class="text-sm font-medium">วันที่:</label><input type="date" x-model="attendanceDate" class="p-2 border rounded-md mt-1">

                            </div>

                        </div>

                        <div class="overflow-x-auto">

                            <table class="w-full text-left">

                                <thead class="bg-slate-50">

                                    <tr>

                                        <th class="p-3">เลขที่</th>

                                        <th class="p-3">ชื่อ - นามสกุล</th>

                                        <th class="p-3 text-center">สถานะ</th>

                                    </tr>

                                </thead>

                                <tbody><template x-for="student in studentsOfSelectedClass" :key="student.id">

                                        <tr class="border-b">

                                            <td class="p-3" x-text="student.number"></td>

                                            <td class="p-3" x-text="student.name"></td>

                                            <td class="p-3 text-center">

                                                <div class="flex justify-center space-x-1">

                                                    <button @click="setAttendance(student.id, 'present')" :class="{'active present': getAttendance(student.id) === 'present'}" class="attendance-status-btn px-3 py-1 text-xs rounded-full">มา</button><button @click="setAttendance(student.id, 'absent')" :class="{'active absent': getAttendance(student.id) === 'absent'}" class="attendance-status-btn px-3 py-1 text-xs rounded-full">ขาด</button><button @click="setAttendance(student.id, 'leave')" :class="{'active leave': getAttendance(student.id) === 'leave'}" class="attendance-status-btn px-3 py-1 text-xs rounded-full">ลา</button><button @click="setAttendance(student.id, 'late')" :class="{'active late': getAttendance(student.id) === 'late'}" class="attendance-status-btn px-3 py-1 text-xs rounded-full">สาย</button>

                                                </div>

                                            </td>

                                        </tr>

                                    </template></tbody>

                            </table>

                        </div>

                    </div>

                </div>

                <div :class="{'hidden': currentPage !== 'reports'}" x-cloak>

                    <div class="content-card p-6">

                        <h3 class="text-xl font-bold text-slate-700 mb-4">สรุปผลการเรียน</h3>

                        <div class="mb-4">

                            <label class="text-sm font-medium">เลือกชั้นเรียน:</label><select x-model="selectedClassId" class="p-2 border rounded-md"><template x-for="cls in classes" :key="cls.id"><option :value="cls.id" x-text="`${cls.name} - ${cls.subject}`"></option></template></select>

                        </div>

                        <div class="chart-container"><canvas id="gradeChart"></canvas></div>

                    </div>

                </div>

                <div x-show="['behavior', 'subjects'].includes(currentPage)" x-cloak>

                    <div class="content-card p-6">

                        <h3 class="text-xl font-bold text-slate-700 mb-4" x-text="pageTitle"></h3>

                        <p>หน้านี้อยู่ในระหว่างการพัฒนา</p>

                    </div>

                </div>

            </div>

            <!-- Footer -->

            <footer class="text-center text-xs text-slate-400 mt-8 py-4 border-t border-slate-200">

                <p>Copyright © 2024. พัฒนาและออกแบบระบบโดย คุณครูวิระเชษฐ์ ทวีทรัพย์ ตำแหน่งครู-วิทยฐานะครูชำนาญการพิเศษ

                    กลุ่มสาระการเรียนรู้ศิลปะ โรงเรียนเซกา สพม.บึงกาฬ</p>

                <p class="mt-1">open-arts & open source project Ai</p>

            </footer>

        </main>

    </div>


    <!-- AI Analysis Modal -->

    <div x-show="isAnalysisModalOpen" @keydown.escape.window="isAnalysisModalOpen = false"

        class="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center p-4 z-50" x-cloak>

        <div @click.away="isAnalysisModalOpen = false" class="bg-white w-full max-w-2xl rounded-lg shadow-xl p-6">

            <div class="flex justify-between items-center mb-4">

                <h3 class="text-xl font-bold text-slate-800">✨ ข้อเสนอแนะจาก AI สำหรับ

                    <span x-text="analyzingStudent?.name"></span></h3>

                <button @click="isAnalysisModalOpen = false" class="p-1 text-slate-500 hover:text-slate-800">&times;</button>

            </div>

            <div class="min-h-[200px]">

                <div x-show="isAnalyzing" class="flex flex-col items-center justify-center h-full">

                    <div class="w-8 h-8 border-4 border-indigo-200 border-t-indigo-600 rounded-full spinner"></div>

                    <p class="mt-3 text-slate-600">กำลังวิเคราะห์ข้อมูลผลการเรียน...</p>

                </div>

                <div x-show="!isAnalyzing" x-html="analysisResult" class="prose max-w-none"></div>

            </div>

        </div>

    </div>


    <script>

        function app() {

        return {

            isLoggedIn: false,

            currentPage: 'dashboard',

            teacher: { 

                name: 'อ.วิระเชษฐ์ ทวีทรัพย์',

                avatar: 'https://placehold.co/100x100/4f46e5/ffffff?text=อ.วิระเชษฐ์'

            },

            loginForm: { email: 'teacher@seka.ac.th', password: '123456' },

            menuItems: [

                { id: 'dashboard', label: 'หน้าหลัก', icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h7.5" /></svg>' },

                { 

                    id: 'classManagement', 

                    label: 'ห้องเรียน', 

                    icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25" /></svg>',

                    subItems: [

                        { id: 'attendance', label: 'เช็คชื่อเข้าเรียน' },

                        { id: 'grades', label: 'ทำคะแนน' },

                        { id: 'behavior', label: 'งานพฤติกรรม' },

                    ] 

                },

                { id: 'media', label: 'สื่อการสอน', icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.158 0L10.5 9.75" /></svg>' },

                { id: 'reports', label: 'รายงานผล', icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h3.75c.621 0 1.125.504 1.125 1.125v6.75c0 .621-.504 1.125-1.125 1.125h-3.75A1.125 1.125 0 013 21v-7.875zM12.75 8.625c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125v12.375c0 .621-.504 1.125-1.125 1.125h-3.75a1.125 1.125 0 01-1.125-1.125V8.625zM21 16.875c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125v4.125c0 .621-.504 1.125-1.125 1.125h-3.75a1.125 1.125 0 01-1.125-1.125V16.875z" /></svg>' },

                { id: 'settings', label: 'ตั้งค่า', icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9.53 16.122a3 3 0 00-5.78 1.128 2.25 2.25 0 01-2.43 2.43a3 3 0 001.128 5.78m1.128-5.78l1.414-1.414m5.782 5.78l-1.414-1.414M6.095 5.036A9 9 0 0110.32 3.5a9 9 0 0110.638 10.638 1.5 1.5 0 00-.475 1.065 3 3 0 01-5.78 1.128 2.25 2.25 0 00-2.43 2.43a3 3 0 01-5.78 1.128 1.5 1.5 0 00-1.065-.475A9 9 0 015.036 6.095" /></svg>' },

            ],

            openSubmenus: [],

            // AI Analysis State

            isAnalysisModalOpen: false,

            isAnalyzing: false,

            analyzingStudent: null,

            analysisResult: '',

            // Theming Data

            themes: [

                { id: 'default_dark', name: 'Default Dark', background: '#f0f4f8', sidebarBg: '#1f2937', sidebarText: '#d1d5db', sidebarSubtext: '#9ca3af', sidebarHeaderText: '#ffffff', sidebarActiveBg: '#4f46e5', sidebarActiveText: '#ffffff' },

                { id: 'light_clean', name: 'Light & Clean', background: '#ffffff', sidebarBg: '#e5e7eb', sidebarText: '#374151', sidebarSubtext: '#4b5563', sidebarHeaderText: '#111827', sidebarActiveBg: '#60a5fa', sidebarActiveText: '#ffffff' },

                { id: 'creative_gradient', name: 'Creative Gradient', background: 'linear-gradient(to right, #6ee7b7, #3b82f6, #9333ea)', sidebarBg: 'rgba(255, 255, 255, 0.1)', sidebarText: '#ffffff', sidebarSubtext: '#e5e7eb', sidebarHeaderText: '#ffffff', sidebarActiveBg: 'rgba(255, 255, 255, 0.3)', sidebarActiveText: '#ffffff' },

                { id: 'teachers_day', name: 'วันครู (กล้วยไม้)', background: 'url(https://images.unsplash.com/photo-1567401893414-76b7b1e5a7a5?q=80&w=2070&auto=format&fit=crop) center/cover', sidebarBg: 'rgba(55, 48, 163, 0.8)', sidebarText: '#e0e7ff', sidebarSubtext: '#c7d2fe', sidebarHeaderText: '#ffffff', sidebarActiveBg: '#a78bfa', sidebarActiveText: '#ffffff' },

            ],

            activeTheme: {},

            classes: [

                { id: 'c1', name: 'ม.5/1', subject: 'ศ30209 กราฟิกดีไซน์ 1' },

                { id: 'c2', name: 'ม.4/3', subject: 'ศ30101 ทัศนศิลป์พื้นฐาน' },

            ],

            students: {

                c1: [

                    { id: 's16745', name: 'นายกิตติชัย ระหา', number: '1' },

                    { id: 's16707', name: 'นายกิตติพันธ์ นันธชัย', number: '2' },

                    { id: 's18715', name: 'นายณัฐพนธ์ แก้วกระมล', number: '3' },

                    { id: 's18716', name: 'นายปฏิภาณ สมตน', number: '4' },

                    { id: 's17790', name: 'นายผลิตทรัพย์ ปัญญารส', number: '6' },

                ],

                c2: [

                    { id: 's20001', name: 'เด็กชายตัวอย่าง หนึ่ง', number: '1'},

                    { id: 's20002', name: 'เด็กหญิงตัวอย่าง สอง', number: '2'},

                ]

            },

            media: [

                { id: 1, url: 'https://placehold.co/600x400/a78bfa/ffffff?text=ผลงานนักเรียน+1', title: 'การออกแบบ Poster', description: 'นายกิตติชัย ระหา' },

                { id: 2, url: 'https://placehold.co/600x400/f472b6/ffffff?text=ผลงานนักเรียน+2', title: 'Infographic Design', description: 'นายกิตติพันธ์ นันธชัย' },

                { id: 3, url: 'https://placehold.co/600x400/fbbf24/ffffff?text=ผลงานนักเรียน+3', title: 'Character Design', description: 'นายณัฐพนธ์ แก้วกระมล' },

                { id: 4, url: 'https://placehold.co/600x400/60a5fa/ffffff?text=ผลงานนักเรียน+4', title: 'Typography Art', description: 'นายปฏิภาณ สมตน' },

            ],

            grades: {},

            attendance: {},

            selectedClassId: 'c1',

            attendanceDate: new Date().toISOString().slice(0, 10),

            gradeChartInstance: null,


            get pageTitle() {

                const mainItem = this.menuItems.find(item => item.id === this.currentPage || (item.subItems && item.subItems.some(sub => sub.id === this.currentPage)));

                if (mainItem?.subItems) {

                    const subItem = mainItem.subItems.find(sub => sub.id === this.currentPage);

                    return subItem?.label || mainItem.label;

                }

                return mainItem?.label || 'Dashboard';

            },

            

            get studentsOfSelectedClass() { return this.students[this.selectedClassId] || []; },


            init() {

                this.setActiveTheme('default_dark');

                this.$watch('selectedClassId', (newClassId) => {

                    this.initializeDataForClass(newClassId);

                    if(this.currentPage === 'reports') { this.renderGradeChart(); }

                });

                this.initializeDataForClass(this.selectedClassId);

                this.$watch('currentPage', (newPage) => {

                    if(newPage === 'reports') { this.$nextTick(() => this.renderGradeChart()); }

                });

            },


            setActiveTheme(themeId) {

                const newTheme = this.themes.find(t => t.id === themeId);

                if (newTheme) { this.activeTheme = newTheme; }

            },


            initializeDataForClass(classId){

                const studentsInClass = this.students[classId] || [];

                studentsInClass.forEach(student => {

                    if (!this.grades[student.id]) { this.grades[student.id] = { pre_midterm: 0, midterm: 0, post_midterm: 0, final: 0, total: 0, grade: '0' }; }

                });

                if (classId === 'c1') {

                    this.grades['s16745'] = { pre_midterm: 24, midterm: 12, post_midterm: 24, final: 16, total: 76, grade: '3.5' };

                    this.grades['s16707'] = { pre_midterm: 25, midterm: 13, post_midterm: 23, final: 15, total: 76, grade: '3.5' };

                    this.grades['s18715'] = { pre_midterm: 23, midterm: 16, post_midterm: 21, final: 14, total: 74, grade: '3' };

                }

            },

            

            toggleSubmenu(itemId) {

                const item = this.menuItems.find(i => i.id === itemId);

                if (item.subItems) {

                    const index = this.openSubmenus.indexOf(itemId);

                    if (index > -1) { this.openSubmenus.splice(index, 1); } 

                    else { this.openSubmenus.push(itemId); }

                } else { this.currentPage = itemId; }

            },

            

            isPageActive(itemId) {

                const item = this.menuItems.find(i => i.id === itemId);

                if (item?.subItems) { return item.subItems.some(sub => sub.id === this.currentPage); }

                return this.currentPage === itemId;

            },

            

            async analyzeStudentPerformance(studentId) {

                this.analyzingStudent = this.studentsOfSelectedClass.find(s => s.id === studentId);

                const studentGrades = this.grades[studentId];

                if (!this.analyzingStudent || !studentGrades) return;

                

                this.isAnalyzing = true;

                this.analysisResult = '';

                this.isAnalysisModalOpen = true;


                const prompt = `

                    คุณคือที่ปรึกษาด้านการศึกษาที่มีประสบการณ์สูง โปรดวิเคราะห์ข้อมูลของนักเรียนต่อไปนี้และให้ข้อเสนอแนะที่สร้างสรรค์และเป็นประโยชน์สำหรับครู

                    

                    ข้อมูลนักเรียน:

                    - ชื่อ: ${this.analyzingStudent.name}

                    - ชั้นเรียน: ${this.classes.find(c => c.id === this.selectedClassId).name}

                    - รายวิชา: ${this.classes.find(c => c.id === this.selectedClassId).subject}

                    

                    ผลการเรียน:

                    - คะแนนก่อนกลางภาค: ${studentGrades.pre_midterm} / 30

                    - คะแนนกลางภาค: ${studentGrades.midterm} / 20

                    - คะแนนหลังกลางภาค: ${studentGrades.post_midterm} / 30

                    - คะแนนปลายภาค: ${studentGrades.final} / 20

                    - คะแนนรวม: ${studentGrades.total.toFixed(2)} / 100

                    - เกรด: ${studentGrades.grade}

                    

                    จากข้อมูลทั้งหมดนี้ กรุณาสรุปประเด็นต่อไปนี้ในรูปแบบ HTML ที่มีการจัดรูปแบบสวยงาม (ใช้ h4, ul, li, strong):

                    1.  **จุดเด่นของนักเรียน:** 2-3 ข้อ ที่ควรส่งเสริมและให้กำลังใจ

                    2.  **สิ่งที่ควรพัฒนา:** 2-3 ข้อ ที่นักเรียนควรให้ความสำคัญเพิ่มเติม พร้อมข้อเสนอแนะที่เป็นรูปธรรมสำหรับครูในการช่วยเหลือ

                `;


                try {

                    const apiKey = ""; // Left empty as per instruction

                    const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;

                    

                    const payload = {

                        contents: [{ role: "user", parts: [{ text: prompt }] }]

                    };


                    const response = await fetch(apiUrl, {

                        method: 'POST',

                        headers: { 'Content-Type': 'application/json' },

                        body: JSON.stringify(payload)

                    });


                    if (!response.ok) {

                        throw new Error(`API Error: ${response.status} ${response.statusText}`);

                    }


                    const result = await response.json();

                    

                    if (result.candidates && result.candidates.length > 0 && result.candidates[0].content.parts.length > 0) {

                        this.analysisResult = result.candidates[0].content.parts[0].text;

                    } else {

                        this.analysisResult = "<p>ไม่สามารถสร้างข้อเสนอแนะได้ในขณะนี้ โปรดลองอีกครั้ง</p>";

                    }

                } catch (error) {

                    console.error('Error calling Gemini API:', error);

                    this.analysisResult = `<p class="text-red-500">เกิดข้อผิดพลาดในการเชื่อมต่อกับ AI: ${error.message}</p>`;

                } finally {

                    this.isAnalyzing = false;

                }

            },


            handleLogin() { this.isLoggedIn = true; this.currentPage = 'dashboard'; },

            handleLogout() { this.isLoggedIn = false; },

            getAttendance(studentId) { return this.attendance[this.attendanceDate]?.[studentId] || 'present'; },

            setAttendance(studentId, status) {

                if (!this.attendance[this.attendanceDate]) { this.attendance[this.attendanceDate] = {}; }

                this.attendance[this.attendanceDate][studentId] = status;

            },

            calculateTotal(studentId) {

                const sGrades = this.grades[studentId];

                const total = (sGrades.pre_midterm || 0) + (sGrades.midterm || 0) + (sGrades.post_midterm || 0) + (sGrades.final || 0);

                this.grades[studentId].total = total;

                this.grades[studentId].grade = this.calculateGrade(total);

            },

            calculateGrade(totalScore) {

                if (totalScore >= 80) return '4'; if (totalScore >= 75) return '3.5'; if (totalScore >= 70) return '3';

                if (totalScore >= 65) return '2.5'; if (totalScore >= 60) return '2'; if (totalScore >= 55) return '1.5';

                if (totalScore >= 50) return '1'; return '0';

            },

            renderGradeChart() {

                if (this.gradeChartInstance) { this.gradeChartInstance.destroy(); }

                const ctx = document.getElementById('gradeChart')?.getContext('2d');

                if (!ctx) return;

                const gradeCounts = { '4': 0, '3.5': 0, '3': 0, '2.5': 0, '2': 0, '1.5': 0, '1': 0, '0': 0 };

                this.studentsOfSelectedClass.forEach(student => {

                    const grade = this.grades[student.id]?.grade;

                    if (gradeCounts.hasOwnProperty(grade)) { gradeCounts[grade]++; }

                });

                this.gradeChartInstance = new Chart(ctx, {

                    type: 'bar',

                    data: {

                        labels: Object.keys(gradeCounts),

                        datasets: [{

                            label: 'จำนวนนักเรียน',

                            data: Object.values(gradeCounts),

                            backgroundColor: 'rgba(79, 70, 229, 0.6)',

                            borderColor: 'rgba(79, 70, 229, 1)',

                            borderWidth: 1

                        }]

                    },

                    options: {

                        responsive: true, maintainAspectRatio: false,

                        scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } },

                        plugins: {

                            legend: { display: false },

                            title: { display: true, text: `สรุปผลการเรียน ${this.classes.find(c=>c.id === this.selectedClassId).name}` }

                        }

                    }

                });

            }

        }

    }

    </script>


</body>


</html>