<?php
// admin/course-sessions.php - ورود جلسات و دانشجویان

session_start();
require_once '../config/database.php';
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!isLoggedIn() || !in_array($_SESSION['role_level'], [1,2,3])) {
    header('Location: dashboard.php');
    exit;
}

$pageTitle = 'ورود جلسات و دانشجویان';
$pageSubtitle = 'ثبت تعداد جلسات برگزار شده و دانشجویان برای هر درس';

$message = '';

// ===== دریافت پارامترها =====
$selected_teacher_id = $_GET['teacher_id'] ?? 0;
$selected_term_id = $_GET['term_id'] ?? 0;

// ===== دریافت لیست اساتید و ترم‌ها =====
$teachers = getAllTeachers();
$allTerms = getAllTerms();

// ===== دریافت دروس استاد =====
$courses = [];
$selectedTeacher = null;
if ($selected_teacher_id > 0) {
    $selectedTeacher = fetchOne("SELECT * FROM users WHERE id = ?", [$selected_teacher_id]);
    
    $whereConditions = ["c.teacher_id = ?"];
    $params = [$selected_teacher_id];
    
    if ($selected_term_id > 0) {
        $whereConditions[] = "c.term_id = ?";
        $params[] = $selected_term_id;
    }
    
    $whereSQL = implode(' AND ', $whereConditions);
    
    $courses = fetchAll(
        "SELECT c.*, t.name as term_name, t.code as term_code,
                u.name as teacher_name, u.family as teacher_family,
                cs.id as session_id, cs.sessions_count, cs.student_count
         FROM courses c
         LEFT JOIN terms t ON c.term_id = t.id
         LEFT JOIN users u ON c.teacher_id = u.id
         LEFT JOIN course_sessions cs ON c.id = cs.course_id AND c.term_id = cs.term_id
         WHERE $whereSQL
         ORDER BY t.id DESC, c.name ASC",
        $params
    );
}

// ===== پردازش فرم =====
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'save_sessions') {
        $course_id = $_POST['course_id'] ?? 0;
        $term_id = $_POST['term_id'] ?? 0;
        $teacher_id = $_POST['teacher_id'] ?? 0;
        $sessions_count = $_POST['sessions_count'] ?? 0;
        $student_count = $_POST['student_count'] ?? 0;
        
        if ($course_id > 0 && $term_id > 0) {
            // بررسی وجود رکورد
            $existing = fetchOne(
                "SELECT id FROM course_sessions WHERE course_id = ? AND term_id = ?",
                [$course_id, $term_id]
            );
            
            if ($existing) {
                $result = updateData(
                    'course_sessions',
                    [
                        'sessions_count' => $sessions_count,
                        'student_count' => $student_count
                    ],
                    'id = :id',
                    ['id' => $existing['id']]
                );
            } else {
                $result = insertData('course_sessions', [
                    'course_id' => $course_id,
                    'term_id' => $term_id,
                    'teacher_id' => $teacher_id,
                    'sessions_count' => $sessions_count,
                    'student_count' => $student_count
                ]);
            }
            
            $message = $result ? '✅ اطلاعات با موفقیت ذخیره شد.' : '❌ خطا در ذخیره اطلاعات.';
            
            // به‌روزرسانی لیست
            $whereConditions = ["c.teacher_id = ?"];
            $params = [$selected_teacher_id];
            if ($selected_term_id > 0) {
                $whereConditions[] = "c.term_id = ?";
                $params[] = $selected_term_id;
            }
            $whereSQL = implode(' AND ', $whereConditions);
            $courses = fetchAll(
                "SELECT c.*, t.name as term_name, t.code as term_code,
                        u.name as teacher_name, u.family as teacher_family,
                        cs.id as session_id, cs.sessions_count, cs.student_count
                 FROM courses c
                 LEFT JOIN terms t ON c.term_id = t.id
                 LEFT JOIN users u ON c.teacher_id = u.id
                 LEFT JOIN course_sessions cs ON c.id = cs.course_id AND c.term_id = cs.term_id
                 WHERE $whereSQL
                 ORDER BY t.id DESC, c.name ASC",
                $params
            );
        }
    }
}

$content = 'course-sessions-content.php';
require_once '../includes/layout.php';
?>