<?php
// admin/courses.php - مدیریت دروس با جستجوی Ajax

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

if (!isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

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

$pageTitle = 'مدیریت دروس';
$pageSubtitle = 'مدیریت دروس اساتید';

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

// ===== دریافت لیست ترم‌ها برای فیلتر =====
$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
         FROM courses c
         LEFT JOIN terms t ON c.term_id = t.id
         LEFT JOIN users u ON c.teacher_id = u.id
         WHERE $whereSQL
         ORDER BY t.id DESC, c.name ASC",
        $params
    );
}

// ===== پردازش فرم =====
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $courseId = $_POST['course_id'] ?? 0;
    $teacherId = $_POST['teacher_id'] ?? 0;
    $termId = $_POST['term_id'] ?? 0;
    $name = $_POST['name'] ?? '';
    $course_type = $_POST['course_type'] ?? 'theoretical';
    $units = $_POST['units'] ?? 0;
    $hours = $_POST['hours'] ?? 0;
    $salary = $_POST['salary'] ?? 0;
    
    if ($action == 'add') {
        $data = [
            'teacher_id' => $teacherId,
            'term_id' => $termId,
            'name' => $name,
            'course_type' => $course_type,
            'units' => $units,
            'hours' => $hours,
            'salary' => $salary
        ];
        $result = createCourse($data);
        $message = $result ? 'درس اضافه شد.' : 'خطا';
        // به‌روزرسانی لیست
        if ($selected_teacher_id > 0) {
            $courses = fetchAll(
                "SELECT c.*, t.name as term_name, t.code as term_code,
                        u.name as teacher_name, u.family as teacher_family
                 FROM courses c
                 LEFT JOIN terms t ON c.term_id = t.id
                 LEFT JOIN users u ON c.teacher_id = u.id
                 WHERE c.teacher_id = ?
                 ORDER BY t.id DESC, c.name ASC",
                [$selected_teacher_id]
            );
        }
    } elseif ($action == 'edit') {
        $data = [
            'teacher_id' => $teacherId,
            'term_id' => $termId,
            'name' => $name,
            'course_type' => $course_type,
            'units' => $units,
            'hours' => $hours,
            'salary' => $salary
        ];
        $result = updateCourse($courseId, $data);
        $message = ($result !== false) ? 'درس ویرایش شد.' : 'خطا';
        if ($selected_teacher_id > 0) {
            $courses = fetchAll(
                "SELECT c.*, t.name as term_name, t.code as term_code,
                        u.name as teacher_name, u.family as teacher_family
                 FROM courses c
                 LEFT JOIN terms t ON c.term_id = t.id
                 LEFT JOIN users u ON c.teacher_id = u.id
                 WHERE c.teacher_id = ?
                 ORDER BY t.id DESC, c.name ASC",
                [$selected_teacher_id]
            );
        }
    } elseif ($action == 'delete') {
        $result = deleteCourse($courseId);
        $message = $result ? 'درس حذف شد.' : 'خطا';
        if ($selected_teacher_id > 0) {
            $courses = fetchAll(
                "SELECT c.*, t.name as term_name, t.code as term_code,
                        u.name as teacher_name, u.family as teacher_family
                 FROM courses c
                 LEFT JOIN terms t ON c.term_id = t.id
                 LEFT JOIN users u ON c.teacher_id = u.id
                 WHERE c.teacher_id = ?
                 ORDER BY t.id DESC, c.name ASC",
                [$selected_teacher_id]
            );
        }
    }
}

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