<?php
// admin/ajax-search-payment.php - جستجوی اساتید برای فیش پرداخت

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, 5])) {
    echo json_encode(['error' => 'دسترسی غیرمجاز.']);
    exit;
}

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$limit = 15;

$whereConditions = ["u.role_id = (SELECT id FROM roles WHERE level = 6)", "u.is_active = 1"];
$params = [];

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

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

$sql = "SELECT u.id, u.name, u.family, u.national_code, u.degree 
        FROM users u 
        WHERE $whereSQL 
        ORDER BY u.family ASC, u.name ASC 
        LIMIT ?";
$params[] = $limit;

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

echo json_encode([
    'teachers' => $teachers,
    'total' => count($teachers)
]);
exit;
?>