<?php
// admin/ajax-search-sessions.php - جستجوی اساتید برای صفحه ثبت جلسات (Ajax)

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

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['error' => 'لطفاً وارد شوید.']);
    exit;
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1, 2, 3])) {
    echo json_encode(['error' => 'دسترسی غیرمجاز.']);
    exit;
}

// ===== دریافت پارامترها =====
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$term_id = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// ===== شرط‌های جستجو =====
$whereConditions = ["u.role_id = (SELECT id FROM roles WHERE level = 6)"];

if (!empty($search)) {
    $whereConditions[] = "(u.name LIKE ? OR u.family LIKE ? OR u.national_code LIKE ? OR u.mobile LIKE ?)";
    $searchTerm = "%$search%";
    $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm];
} else {
    $params = [];
}

if ($term_id > 0) {
    $whereConditions[] = "EXISTS (SELECT 1 FROM courses c WHERE c.teacher_id = u.id AND c.term_id = ?)";
    $params[] = $term_id;
}

$whereSQL = implode(' AND ', $whereConditions);

// ===== کوئری اصلی =====
$sql = "SELECT u.id, u.name, u.family, u.national_code, u.mobile 
        FROM users u 
        WHERE $whereSQL 
        ORDER BY u.id DESC 
        LIMIT ? OFFSET ?";

$params[] = $limit;
$params[] = $offset;

$teachers = fetchAll($sql, $params);

// ===== تعداد کل =====
$countSql = "SELECT COUNT(*) as total FROM users u WHERE $whereSQL";
$countParams = array_slice($params, 0, count($params) - 2);
$totalResult = fetchOne($countSql, $countParams);
$total = $totalResult['total'] ?? 0;

// ===== خروجی =====
echo json_encode([
    'teachers' => $teachers,
    'total' => $total,
    'page' => $page,
    'totalPages' => ceil($total / $limit)
]);
exit;
?>