<?php
// admin/teachers.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()) {
    header('Location: ../login.php');
    exit;
}

$user = getCurrentUser();
if ($user['role_level'] == 6) {
    header('Location: ../teacher/profile.php');
    exit;
}

$pageTitle = 'مدیریت مدرسین';
$pageSubtitle = 'لیست کامل اساتید دانشگاه';

// ===== دریافت فیلترها =====
$search = $_GET['search'] ?? '';
$term_filter = $_GET['term_filter'] ?? 0;
$status_filter = $_GET['status'] ?? 'all';

// ===== آمار مدرسین =====
$totalTeachers = getTotalTeachers();
$activeTeachers = fetchCount("SELECT id FROM users WHERE role_id = (SELECT id FROM roles WHERE level = 6) AND is_active = 1");
$inactiveTeachers = $totalTeachers - $activeTeachers;
$teachersWithSheba = getTeachersWithSheba();
$teachersWithoutSheba = getTeachersWithoutSheba();

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

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

// فیلتر وضعیت
if ($status_filter == 'with_sheba') {
    $whereConditions[] = "u.sheba_number IS NOT NULL AND u.sheba_number != '' AND u.is_sheba_confirmed = 1";
} elseif ($status_filter == 'without_sheba') {
    $whereConditions[] = "(u.sheba_number IS NULL OR u.sheba_number = '')";
} elseif ($status_filter == 'active') {
    $whereConditions[] = "u.is_active = 1";
} elseif ($status_filter == 'inactive') {
    $whereConditions[] = "u.is_active = 0";
} elseif ($status_filter == 'pending_sheba') {
    $whereConditions[] = "u.sheba_number IS NOT NULL AND u.sheba_number != '' AND u.is_sheba_confirmed = 0";
}

// فیلتر ترم
if ($term_filter > 0) {
    $whereConditions[] = "EXISTS (SELECT 1 FROM courses c WHERE c.teacher_id = u.id AND c.term_id = ?)";
    $params[] = $term_filter;
}

$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.id DESC",
    $params
);

// ===== دریافت لیست ترم‌ها برای فیلتر =====
$allTerms = getAllTerms();

// ===== پردازش فرم =====
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'confirm_sheba') {
        $teacherId = $_POST['teacher_id'] ?? 0;
        $result = confirmTeacherSheba($teacherId);
        if ($result !== false) {
            $message = '✅ شماره شبا با موفقیت تأیید شد.';
            // به‌روزرسانی لیست
            $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.id DESC",
                $params
            );
        } else {
            $message = '❌ خطا در تأیید شماره شبا.';
        }
    } elseif ($action == 'toggle_status') {
        $teacherId = $_POST['teacher_id'] ?? 0;
        $currentStatus = $_POST['current_status'] ?? 1;
        $newStatus = $currentStatus ? 0 : 1;
        
        $result = updateData('users', ['is_active' => $newStatus], 'id = :id', ['id' => $teacherId]);
        if ($result !== false) {
            $message = 'وضعیت مدرس با موفقیت تغییر یافت.';
            $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.id DESC",
                $params
            );
        } else {
            $message = 'خطا در تغییر وضعیت مدرس.';
        }
    } elseif ($action == 'delete_teacher') {
        // ===== فقط مدیر سامانه (سطح 1) اجازه حذف دارد =====
        if ($user['role_level'] != 1) {
            $message = '❌ فقط مدیر سامانه می‌تواند مدرس را حذف کند.';
        } else {
            $teacherId = $_POST['teacher_id'] ?? 0;
            
            if ($teacherId > 0) {
                // ===== شروع تراکنش برای حذف کامل =====
                try {
                    $pdo->beginTransaction();
                    
                    // 1. حذف تراکنش‌ها
                    deleteData('transactions', 'teacher_id = :id', ['id' => $teacherId]);
                    
                    // 2. حذف جلسات
                    deleteData('course_sessions', 'teacher_id = :id', ['id' => $teacherId]);
                    
                    // 3. حذف دروس
                    deleteData('courses', 'teacher_id = :id', ['id' => $teacherId]);
                    
                    // 4. حذف کاربر
                    deleteData('users', 'id = :id', ['id' => $teacherId]);
                    
                    $pdo->commit();
                    $message = '✅ مدرس و تمام اطلاعات مرتبط با موفقیت حذف شد.';
                    
                    // به‌روزرسانی لیست
                    $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.id DESC",
                        $params
                    );
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $message = '❌ خطا در حذف مدرس: ' . $e->getMessage();
                }
            } else {
                $message = '❌ شناسه مدرس نامعتبر.';
            }
        }
    }
}

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