<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
require_once '../includes/functions.php';

if (!isLoggedIn()) {
    echo json_encode(['error' => 'دسترسی غیرمجاز']);
    exit;
}

$search = $_GET['search'] ?? '';
$searchType = $_GET['search_type'] ?? 'all';
$date = $_GET['date'] ?? '';

// ============================================================
// جستجوی جامع در همه فیلدها
// ============================================================
if ($searchType == 'all' && !empty($search) && strlen($search) >= 2) {
    $query = "SELECT m.id, m.fullname, m.national_code, 
                     sf.name as study_field_name,
                     e.name as education_name,
                     m.created_at
              FROM members m 
              LEFT JOIN study_fields sf ON m.study_field_id = sf.id
              LEFT JOIN educations e ON m.education_id = e.id
              WHERE m.fullname LIKE ? 
                 OR m.national_code LIKE ? 
                 OR sf.name LIKE ? 
                 OR e.name LIKE ?
              AND m.status != 'deleted' 
              ORDER BY m.created_at DESC 
              LIMIT 20";

    $stmt = $pdo->prepare($query);
    $searchParam = "%$search%";
    $stmt->execute([$searchParam, $searchParam, $searchParam, $searchParam]);
    $results = $stmt->fetchAll();

    foreach ($results as &$row) {
        $row['created_at'] = convertToPersianDateFa($row['created_at']);
    }

    header('Content-Type: application/json');
    echo json_encode($results);
    exit;
}

// ============================================================
// دریافت دانشجویان یک روز خاص (برای تقویم)
// ============================================================
if ($searchType == 'date' && !empty($date)) {
    $query = "SELECT m.id, m.fullname, m.national_code, 
                     sf.name as study_field_name,
                     e.name as education_name
              FROM members m 
              LEFT JOIN study_fields sf ON m.study_field_id = sf.id
              LEFT JOIN educations e ON m.education_id = e.id
              WHERE DATE(m.created_at) = ? AND m.status != 'deleted'
              ORDER BY m.created_at DESC";

    $stmt = $pdo->prepare($query);
    $stmt->execute([$date]);
    $results = $stmt->fetchAll();

    header('Content-Type: application/json');
    echo json_encode($results);
    exit;
}

echo json_encode([]);
exit;
?>