<?php
// admin/export-excel.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()) {
    die('ابتدا وارد شوید.');
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1,2,5])) {
    die('دسترسی غیرمجاز.');
}

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

// دریافت لیست مدرسین
$whereConditions = ["u.role_id = (SELECT id FROM roles WHERE level = 6)"];
$params = [];

if ($status == 'with_sheba') {
    $whereConditions[] = "u.sheba_number IS NOT NULL AND u.sheba_number != '' AND u.is_sheba_confirmed = 1";
} elseif ($status == 'without_sheba') {
    $whereConditions[] = "(u.sheba_number IS NULL OR u.sheba_number = '')";
}

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);

$teachers = fetchAll(
    "SELECT u.*, r.name as role_name 
     FROM users u 
     LEFT JOIN roles r ON u.role_id = r.id 
     WHERE $whereSQL 
     ORDER BY u.name ASC",
    $params
);

// =============================================
// خروجی CSV
// =============================================
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="teachers_export_' . date('Ymd_His') . '.csv"');

$output = fopen('php://output', 'w');
fwrite($output, "\xEF\xBB\xBF");

// هدر
fputcsv($output, ['ردیف', 'نام', 'نام‌خانوادگی', 'کد ملی', 'موبایل', 'شماره شبا', 'وضعیت شبا', 'وضعیت']);

$i = 1;
foreach ($teachers as $teacher) {
    fputcsv($output, [
        $i++,
        $teacher['name'],
        $teacher['family'],
        $teacher['national_code'],
        $teacher['mobile'],
        $teacher['sheba_number'] ?? '',
        $teacher['is_sheba_confirmed'] ? 'تأیید شده' : 'در انتظار تأیید',
        $teacher['is_active'] ? 'فعال' : 'غیرفعال'
    ]);
}

fclose($output);
exit;
?>