<?php
// admin/course-sessions-content.php - محتوای ورود جلسات و دانشجویان با جستجوی Ajax
?>

<!-- ============================================================
     پیام‌ها
     ============================================================ -->
<?php if ($message): ?>
<div class="alert alert-<?= strpos($message, '❌') !== false ? 'alert-danger' : 'alert-success' ?>">
    <i class="fas <?= strpos($message, '❌') !== false ? 'fa-exclamation-circle' : 'fa-check-circle' ?>"></i>
    <?= $message ?>
</div>
<?php endif; ?>

<!-- ============================================================
     بخش جستجو و فیلتر
     ============================================================ -->
<div class="filter-section" style="margin-bottom:20px;padding:16px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;">
        
        <!-- جستجوی استاد -->
        <div style="flex:2;min-width:200px;position:relative;">
            <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-user-search"></i> جستجوی استاد
            </label>
            <input type="text" id="teacherSearch" class="form-control" 
                   placeholder="نام، نام خانوادگی یا کد ملی..." 
                   autocomplete="off"
                   style="width:100%;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;">
            <input type="hidden" id="selected_teacher_id" value="<?= $selected_teacher_id ?>">
            <div id="searchResults" style="position:absolute;top:100%;right:0;left:0;background:white;border:2px solid #355C9C;border-radius:8px;max-height:250px;overflow-y:auto;display:none;z-index:1000;box-shadow:0 8px 25px rgba(0,0,0,0.15);margin-top:4px;"></div>
        </div>

        <!-- فیلتر ترم -->
        <div style="flex:1;min-width:130px;">
            <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-calendar-alt"></i> ترم
            </label>
            <select id="filterTerm" class="form-control" style="width:100%;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;background:white;">
                <option value="0">همه ترم‌ها</option>
                <?php foreach ($allTerms as $term): ?>
                <option value="<?= $term['id'] ?>" <?= ($selected_term_id == $term['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($term['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- دکمه‌ها -->
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <button type="submit" class="btn btn-primary" id="searchBtn" style="padding:10px 24px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;background:#1a237e;color:white;transition:all 0.3s;">
                <i class="fas fa-search"></i> جستجو
            </button>
            <a href="course-sessions.php" class="btn btn-outline" style="padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;text-decoration:none;background:transparent;color:#6b7280;border:2px solid #e5e7eb;transition:all 0.3s;display:inline-flex;align-items:center;gap:6px;">
                <i class="fas fa-redo"></i> بازنشانی
            </a>
        </div>
    </div>
</div>

<!-- ============================================================
     اسکریپت جستجوی Ajax
     ============================================================ -->
<script>
$(document).ready(function() {
    let searchTimer;
    const searchInput = $('#teacherSearch');
    const resultsDiv = $('#searchResults');
    const selectedTeacherId = $('#selected_teacher_id');

    searchInput.on('input', function() {
        clearTimeout(searchTimer);
        const query = $(this).val().trim();
        const termId = $('#filterTerm').val();

        if (query.length < 2) {
            resultsDiv.hide();
            return;
        }

        searchTimer = setTimeout(function() {
            $.ajax({
                url: 'ajax-search-sessions.php',
                type: 'GET',
                data: { search: query, term_id: termId },
                dataType: 'json',
                success: function(response) {
                    if (response.error) {
                        resultsDiv.html('<div style="padding:14px;color:#e74c3c;text-align:center;">' + response.error + '</div>').show();
                        return;
                    }
                    
                    if (response.teachers && response.teachers.length > 0) {
                        let html = '<div style="padding:10px 14px;font-weight:700;color:#1a237e;border-bottom:2px solid #e8eaf6;font-size:13px;">نتایج جستجو (' + response.total + '):</div>';
                        $.each(response.teachers, function(index, teacher) {
                            html += `<div class="search-item" data-id="${teacher.id}" data-name="${teacher.name} ${teacher.family}" style="padding:10px 14px;cursor:pointer;border-bottom:1px solid #f5f5f5;transition:all 0.2s;display:flex;justify-content:space-between;align-items:center;">
                                <span style="font-weight:600;color:#333;">${teacher.name} ${teacher.family}</span>
                                <span style="color:#888;font-size:12px;">${teacher.national_code}</span>
                            </div>`;
                        });
                        resultsDiv.html(html).show();
                    } else {
                        resultsDiv.html('<div style="padding:14px;color:#999;text-align:center;">نتیجه‌ای یافت نشد.</div>').show();
                    }
                },
                error: function() {
                    resultsDiv.html('<div style="padding:14px;color:#e74c3c;text-align:center;">خطا در ارتباط با سرور.</div>').show();
                }
            });
        }, 400);
    });

    $(document).on('click', '.search-item', function() {
        const teacherId = $(this).data('id');
        const teacherName = $(this).data('name');
        const termId = $('#filterTerm').val();
        
        searchInput.val(teacherName);
        resultsDiv.hide();
        window.location.href = 'course-sessions.php?teacher_id=' + teacherId + '&term_id=' + termId;
    });

    $('#searchBtn').on('click', function() {
        const query = searchInput.val().trim();
        const termId = $('#filterTerm').val();
        
        if (query === '') {
            window.location.href = 'course-sessions.php?term_id=' + termId;
        } else {
            $.ajax({
                url: 'ajax-search-sessions.php',
                type: 'GET',
                data: { search: query, term_id: termId },
                dataType: 'json',
                success: function(response) {
                    if (response.teachers && response.teachers.length > 0) {
                        if (response.teachers.length === 1) {
                            window.location.href = 'course-sessions.php?teacher_id=' + response.teachers[0].id + '&term_id=' + termId;
                        } else {
                            let html = '<div style="padding:10px 14px;font-weight:700;color:#1a237e;border-bottom:2px solid #e8eaf6;font-size:13px;">نتایج جستجو (' + response.total + '):</div>';
                            $.each(response.teachers, function(index, teacher) {
                                html += `<div class="search-item" data-id="${teacher.id}" data-name="${teacher.name} ${teacher.family}" style="padding:10px 14px;cursor:pointer;border-bottom:1px solid #f5f5f5;transition:all 0.2s;display:flex;justify-content:space-between;align-items:center;">
                                    <span style="font-weight:600;color:#333;">${teacher.name} ${teacher.family}</span>
                                    <span style="color:#888;font-size:12px;">${teacher.national_code}</span>
                                </div>`;
                            });
                            resultsDiv.html(html).show();
                        }
                    } else {
                        resultsDiv.html('<div style="padding:14px;color:#999;text-align:center;">نتیجه‌ای یافت نشد.</div>').show();
                    }
                }
            });
        }
    });

    $(document).on('click', function(e) {
        if (!$(e.target).closest('#teacherSearch, #searchResults, #searchBtn').length) {
            resultsDiv.hide();
        }
    });

    $(document).on('mouseenter', '.search-item', function() {
        $(this).css('background', '#e8eaf6');
    });
    $(document).on('mouseleave', '.search-item', function() {
        $(this).css('background', '');
    });
});
</script>

<!-- ============================================================
     نمایش داده‌ها
     ============================================================ -->

<?php if (!$selected_teacher_id): ?>
    
    <div class="card" style="text-align:center;padding:60px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
        <i class="fas fa-user-search" style="font-size:64px;color:#9ca3af;display:block;margin-bottom:20px;opacity:0.2;"></i>
        <h3 style="font-size:20px;color:#6b7280;margin-bottom:12px;">برای ثبت جلسات، استاد را جستجو کنید</h3>
        <p style="font-size:14px;color:#9ca3af;max-width:500px;margin:0 auto;">
            از بخش جستجو در بالا، نام استاد مورد نظر را وارد کنید و سپس جلسات او را ثبت کنید.
        </p>
        <div style="display:flex;gap:12px;justify-content:center;margin-top:24px;flex-wrap:wrap;">
            <span style="padding:8px 20px;background:#dbeafe;border-radius:8px;color:#1a237e;font-size:13px;">
                <i class="fas fa-user"></i> جستجو بر اساس نام استاد
            </span>
            <span style="padding:8px 20px;background:#dbeafe;border-radius:8px;color:#1a237e;font-size:13px;">
                <i class="fas fa-calendar"></i> فیلتر بر اساس ترم
            </span>
        </div>
    </div>

<?php elseif ($selected_teacher_id > 0 && $selectedTeacher): ?>

    <div class="card" style="margin-bottom:20px;padding:16px 20px;background:linear-gradient(135deg, #355C9C, #2FA7A3);color:white;border-radius:12px;">
        <div style="display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;">
            <div>
                <h3 style="font-size:18px;font-weight:700;margin:0;">
                    <i class="fas fa-user-graduate"></i> 
                    <?= htmlspecialchars($selectedTeacher['name'] . ' ' . $selectedTeacher['family']) ?>
                </h3>
                <div style="font-size:13px;opacity:0.9;margin-top:4px;">
                    کد ملی: <?= $selectedTeacher['national_code'] ?> | 
                    <?php if (!empty($selected_term_id)): ?>
                        ترم: <?= htmlspecialchars(getTermName($selected_term_id)) ?>
                    <?php else: ?>
                        همه ترم‌ها
                    <?php endif; ?>
                </div>
            </div>
            <div style="text-align:left;background:rgba(255,255,255,0.15);padding:6px 16px;border-radius:12px;">
                <div style="font-size:12px;opacity:0.8;">تعداد دروس</div>
                <div style="font-size:18px;font-weight:700;"><?= count($courses) ?></div>
            </div>
        </div>
    </div>

    <?php if (empty($courses)): ?>
        <div class="card" style="text-align:center;padding:40px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
            <i class="fas fa-book" style="font-size:48px;color:#9ca3af;display:block;margin-bottom:16px;opacity:0.3;"></i>
            <p style="font-size:18px;color:#6b7280;">هیچ درسی برای این استاد ثبت نشده است.</p>
            <p style="font-size:14px;color:#9ca3af;">ابتدا دروس را در صفحه مدیریت دروس ثبت کنید.</p>
        </div>
    <?php else: ?>
        <div class="card" style="padding:0;overflow:hidden;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
            <div class="table-responsive" style="overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;font-size:14px;">
                    <thead>
                        <tr style="background:#f8fafc;border-bottom:2px solid #e5e7eb;">
                            <th style="padding:12px 16px;text-align:right;color:#6b7280;font-weight:600;font-size:13px;">#</th>
                            <th style="padding:12px 16px;text-align:right;color:#6b7280;font-weight:600;font-size:13px;">نام درس</th>
                            <th style="padding:12px 16px;text-align:right;color:#6b7280;font-weight:600;font-size:13px;">نوع</th>
                            <th style="padding:12px 16px;text-align:right;color:#6b7280;font-weight:600;font-size:13px;">ترم</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">تعداد جلسات</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">تعداد دانشجویان</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;width:100px;">عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; foreach ($courses as $course): 
                            $isPractical = in_array($course['course_type'], ['internship', 'practicum', 'project']);
                        ?>
                        <tr style="border-bottom:1px solid #f3f4f6;" class="table-row-hover">
                            <form method="POST" style="display:contents;">
                                <input type="hidden" name="action" value="save_sessions">
                                <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                <input type="hidden" name="term_id" value="<?= $course['term_id'] ?? 0 ?>">
                                <input type="hidden" name="teacher_id" value="<?= $selected_teacher_id ?>">
                                
                                <td style="padding:10px 16px;text-align:center;"><?= $i++ ?></td>
                                <td style="padding:10px 16px;font-weight:600;color:#1f2937;"><?= htmlspecialchars($course['name']) ?></td>
                                <td style="padding:10px 16px;">
                                    <span class="course-type-badge <?= ($course['course_type'] == 'theoretical') ? 'course-type-theoretical' : 'course-type-practical' ?>">
                                        <?= getCourseTypeName($course['course_type']) ?>
                                    </span>
                                </td>
                                <td style="padding:10px 16px;"><?= htmlspecialchars($course['term_name'] ?? 'بدون ترم') ?></td>
                                
                                <!-- ===== تعداد جلسات ===== -->
                                <td style="padding:10px 16px;text-align:center;">
                                    <input type="number" name="sessions_count" value="<?= $course['sessions_count'] ?? 0 ?>" 
                                           class="form-control" 
                                           style="width:80px;padding:6px 10px;border:2px solid <?= $isPractical ? '#f3f4f6' : '#e5e7eb' ?>;border-radius:6px;font-size:13px;text-align:center;display:inline-block;<?= $isPractical ? 'background:#f3f4f6;cursor:not-allowed;' : '' ?>"
                                           min="0" <?= $isPractical ? 'readonly disabled' : '' ?>>
                                    <?php if ($isPractical): ?>
                                        <span style="display:block;font-size:9px;color:#9ca3af;margin-top:2px;">⛔ غیرفعال</span>
                                    <?php endif; ?>
                                </td>
                                
                                <!-- ===== تعداد دانشجویان ===== -->
                                <td style="padding:10px 16px;text-align:center;">
                                    <input type="number" name="student_count" value="<?= $course['student_count'] ?? 0 ?>" 
                                           class="form-control" 
                                           style="width:80px;padding:6px 10px;border:2px solid #e5e7eb;border-radius:6px;font-size:13px;text-align:center;display:inline-block;"
                                           min="0">
                                </td>
                                
                                <td style="padding:10px 16px;text-align:center;">
                                    <button type="submit" class="btn-action btn-action-edit" title="ذخیره">
                                        <i class="fas fa-save"></i>
                                    </button>
                                </td>
                            </form>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>

<?php endif; ?>

<!-- ============================================================
     استایل‌ها
     ============================================================ -->
<style>
.btn-action {
    transition: all 0.2s;
}
.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}
.btn-action-edit {
    background: #1a237e;
}
.btn-action-edit:hover {
    background: #0d1442;
}
.btn-action-delete {
    background: #dc3545;
}
.btn-action-delete:hover {
    background: #bd2130;
}
.table-row-hover {
    transition: background 0.2s;
}
.table-row-hover:hover {
    background: #f9fafb;
}
.form-control:focus {
    border-color: #355C9C !important;
    box-shadow: 0 0 0 3px rgba(53, 92, 156, 0.1) !important;
    outline: none;
}
.search-item:hover {
    background: #e8eaf6 !important;
}
.card {
    transition: all 0.2s;
}
.card:hover {
    box-shadow: 0 4px 16px rgba(0,0,0,0.04);
}
.course-type-badge {
    padding: 3px 12px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    display: inline-block;
}
.course-type-theoretical {
    background: #dbeafe;
    color: #1e40af;
}
.course-type-practical {
    background: #fef3c7;
    color: #92400e;
}
</style>