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

if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'admin') {
    header('Location: ../index.php');
    exit;
}

$fields = $pdo->query("SELECT * FROM dynamic_fields ORDER BY section, sort_order")->fetchAll();
$educations = $pdo->query("SELECT * FROM educations ORDER BY sort_order")->fetchAll();
$referrals = $pdo->query("SELECT * FROM referrals ORDER BY sort_order")->fetchAll();
$courses = getAllCourses();

$sections = [
    'personal' => 'اطلاعات شخصی',
    'educational' => 'اطلاعات تحصیلی',
    'status' => 'وضعیت‌ها',
    'referral' => 'معرف'
];

// ============================================================
// پردازش Ajax (بدون رفرش)
// ============================================================
if (isset($_POST['ajax_action'])) {
    $response = ['success' => false, 'message' => 'خطا در پردازش'];
    
    try {
        switch ($_POST['ajax_action']) {
            case 'add_course':
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("INSERT INTO courses (name, education_id, sort_order) VALUES (?, ?, ?)");
                $stmt->execute([
                    $_POST['course_name'],
                    $_POST['course_education_id'],
                    $_POST['course_sort']
                ]);
                $pdo->commit();
                $response = ['success' => true, 'message' => '✅ رشته تحصیلی با موفقیت اضافه شد'];
                break;
                
            case 'edit_course':
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("UPDATE courses SET name = ?, education_id = ?, sort_order = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['course_name'],
                    $_POST['course_education_id'],
                    $_POST['course_sort'],
                    $_POST['course_id']
                ]);
                $pdo->commit();
                $response = ['success' => true, 'message' => '✅ رشته تحصیلی با موفقیت ویرایش شد'];
                break;
                
            case 'toggle_course':
                $stmt = $pdo->prepare("UPDATE courses SET status = ? WHERE id = ?");
                $stmt->execute([$_POST['status'], $_POST['course_id']]);
                $response = ['success' => true, 'message' => '✅ وضعیت رشته تغییر کرد'];
                break;
                
            case 'delete_course':
                $stmt = $pdo->prepare("DELETE FROM courses WHERE id = ?");
                $stmt->execute([$_POST['course_id']]);
                $response = ['success' => true, 'message' => '✅ رشته تحصیلی با موفقیت حذف شد'];
                break;
        }
    } catch(PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $response = ['success' => false, 'message' => '❌ خطا: ' . $e->getMessage()];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// ============================================================
// پردازش فرم‌های غیر Ajax
// ============================================================
$message = '';
$messageType = '';

// افزودن فیلد
if (isset($_POST['add_field'])) {
    $stmt = $pdo->prepare("INSERT INTO dynamic_fields (field_name, label, section, required, sort_order) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['field_name'],
        $_POST['label'],
        $_POST['section'],
        isset($_POST['required']) ? 1 : 0,
        $_POST['sort_order']
    ]);
    $message = '✅ فیلد با موفقیت اضافه شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// ویرایش فیلد
if (isset($_POST['edit_field'])) {
    $stmt = $pdo->prepare("UPDATE dynamic_fields SET field_name = ?, label = ?, section = ?, required = ?, sort_order = ? WHERE id = ?");
    $stmt->execute([
        $_POST['field_name'],
        $_POST['label'],
        $_POST['section'],
        isset($_POST['required']) ? 1 : 0,
        $_POST['sort_order'],
        $_POST['field_id']
    ]);
    $message = '✅ فیلد با موفقیت ویرایش شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// تغییر وضعیت فیلد
if (isset($_POST['toggle_field'])) {
    $stmt = $pdo->prepare("UPDATE dynamic_fields SET status = ? WHERE id = ?");
    $stmt->execute([$_POST['status'], $_POST['field_id']]);
    $message = '✅ وضعیت فیلد تغییر کرد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// حذف فیلد
if (isset($_POST['delete_field'])) {
    $stmt = $pdo->prepare("DELETE FROM dynamic_fields WHERE id = ?");
    $stmt->execute([$_POST['field_id']]);
    $message = '✅ فیلد با موفقیت حذف شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// افزودن مقطع
if (isset($_POST['add_education'])) {
    $stmt = $pdo->prepare("INSERT INTO educations (name, sort_order) VALUES (?, ?)");
    $stmt->execute([$_POST['edu_name'], $_POST['edu_sort']]);
    $message = '✅ مقطع تحصیلی با موفقیت اضافه شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// ویرایش مقطع
if (isset($_POST['edit_education'])) {
    $stmt = $pdo->prepare("UPDATE educations SET name = ?, sort_order = ? WHERE id = ?");
    $stmt->execute([$_POST['edu_name'], $_POST['edu_sort'], $_POST['edu_id']]);
    $message = '✅ مقطع تحصیلی با موفقیت ویرایش شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// تغییر وضعیت مقطع
if (isset($_POST['toggle_education'])) {
    $stmt = $pdo->prepare("UPDATE educations SET status = ? WHERE id = ?");
    $stmt->execute([$_POST['status'], $_POST['edu_id']]);
    $message = '✅ وضعیت مقطع تغییر کرد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// حذف مقطع
if (isset($_POST['delete_education'])) {
    $stmt = $pdo->prepare("DELETE FROM educations WHERE id = ?");
    $stmt->execute([$_POST['edu_id']]);
    $message = '✅ مقطع تحصیلی با موفقیت حذف شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// افزودن روش معرف
if (isset($_POST['add_referral'])) {
    $stmt = $pdo->prepare("INSERT INTO referrals (name, sort_order) VALUES (?, ?)");
    $stmt->execute([$_POST['ref_name'], $_POST['ref_sort']]);
    $message = '✅ روش معرف با موفقیت اضافه شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// ویرایش روش معرف
if (isset($_POST['edit_referral'])) {
    $stmt = $pdo->prepare("UPDATE referrals SET name = ?, sort_order = ? WHERE id = ?");
    $stmt->execute([$_POST['ref_name'], $_POST['ref_sort'], $_POST['ref_id']]);
    $message = '✅ روش معرف با موفقیت ویرایش شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// تغییر وضعیت روش معرف
if (isset($_POST['toggle_referral'])) {
    $stmt = $pdo->prepare("UPDATE referrals SET status = ? WHERE id = ?");
    $stmt->execute([$_POST['status'], $_POST['ref_id']]);
    $message = '✅ وضعیت روش معرف تغییر کرد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// حذف روش معرف
if (isset($_POST['delete_referral'])) {
    $stmt = $pdo->prepare("DELETE FROM referrals WHERE id = ?");
    $stmt->execute([$_POST['ref_id']]);
    $message = '✅ روش معرف با موفقیت حذف شد';
    $messageType = 'success';
    header('Location: fields.php?msg=' . urlencode($message) . '&type=' . $messageType);
    exit;
}

// دریافت پیام از session
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
    $messageType = $_GET['type'] ?? 'success';
}
?>
<?php include '../includes/header.php'; ?>

<style>
/* ========== استایل بخش‌ها (همون حالت قبل) ========== */
.section-title {
    font-weight: 600;
    font-size: 1rem;
    color: #0f172a;
    margin-top: 25px;
    margin-bottom: 12px;
    padding: 10px 15px;
    background: #f8fafc;
    border-radius: 10px;
    border-right: 4px solid #4f46e5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    user-select: none;
    transition: all 0.2s ease;
}
.section-title:hover {
    background: #f1f5f9;
}
.section-title i {
    color: #4f46e5;
    margin-left: 8px;
}
.section-title .badge-count {
    background: #4f46e5;
    color: white;
    padding: 1px 10px;
    border-radius: 20px;
    font-size: 0.7rem;
}
.section-title .toggle-icon {
    font-size: 0.8rem;
    color: #94a3b8;
    transition: transform 0.3s ease;
}
.section-title.open .toggle-icon {
    transform: rotate(180deg);
}

/* ========== بخش‌های جمع‌شونده ========== */
.section-body {
    display: none;
    padding: 15px 0;
}
.section-body.open {
    display: block !important;
}

/* ========== فرم‌ها و جداول ========== */
.add-form {
    background: #f8fafc;
    border-radius: 12px;
    padding: 15px 18px;
    border: 1px solid #e9edf2;
    margin-bottom: 15px;
}
.add-form .form-control, .add-form .form-select {
    height: 40px;
    border-radius: 8px;
    font-size: 0.85rem;
}
.table-wrapper {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e9edf2;
    border-radius: 10px;
}
.table-wrapper::-webkit-scrollbar {
    width: 6px;
}
.table-wrapper::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 10px;
}
.table-wrapper::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 10px;
}
.table-modern {
    font-size: 0.82rem;
    margin-bottom: 0;
}
.table-modern thead th {
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    padding: 8px 12px;
    border-bottom: 2px solid #e9edf2;
    position: sticky;
    top: 0;
    z-index: 10;
}
.table-modern tbody td {
    padding: 8px 12px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}
.table-modern tbody tr:hover {
    background: #f8fafc;
}
.table-modern .badge {
    font-size: 0.65rem;
    padding: 2px 10px;
}
.btn-action {
    width: 30px;
    height: 30px;
    padding: 0;
    border-radius: 6px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
}
.table-search {
    margin-bottom: 12px;
}
.table-search input {
    border-radius: 8px;
    border: 1px solid #d1d5db;
    padding: 6px 12px;
    font-size: 0.85rem;
    width: 100%;
    max-width: 300px;
    background: #ffffff;
}
.table-search input:focus {
    border-color: #4f46e5;
    outline: none;
    box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
}

/* ========== پیام‌ها ========== */
.section-message {
    padding: 10px 15px;
    border-radius: 10px;
    margin-bottom: 12px;
    font-size: 0.85rem;
    display: none;
    animation: fadeIn 0.3s ease;
}
.section-message.success {
    background: #dcfce7;
    color: #16a34a;
    border: 1px solid #bbf7d0;
    display: block;
}
.section-message.error {
    background: #fee2e2;
    color: #dc2626;
    border: 1px solid #fecaca;
    display: block;
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* ========== ریسپانسیو ========== */
@media (max-width: 768px) {
    .add-form .row > div {
        margin-bottom: 6px;
    }
    .table-wrapper {
        max-height: 300px;
    }
}
</style>

<!-- نمایش پیام -->
<?php if ($message): ?>
<div class="section-message <?php echo $messageType; ?>" style="display:block;">
    <?php echo $message; ?>
</div>
<?php endif; ?>

<!-- ============================================================
بخش ۱: فیلدهای داینامیک
============================================================ -->
<div class="section-title" onclick="toggleSection(this)">
    <span>
        <i class="bi bi-layout-text-window"></i>
        فیلدهای داینامیک فرم ثبت‌نام
        <span class="badge-count"><?php echo count($fields); ?></span>
    </span>
    <span class="toggle-icon"><i class="bi bi-chevron-down"></i></span>
</div>
<div class="section-body">
    <div class="add-form">
        <form method="POST" class="row g-2">
            <div class="col-md-3">
                <input type="text" name="field_name" class="form-control" placeholder="نام انگلیسی" required>
            </div>
            <div class="col-md-3">
                <input type="text" name="label" class="form-control" placeholder="لیبل فارسی" required>
            </div>
            <div class="col-md-2">
                <select name="section" class="form-select" required>
                    <option value="personal">اطلاعات شخصی</option>
                    <option value="educational">اطلاعات تحصیلی</option>
                    <option value="status">وضعیت‌ها</option>
                    <option value="referral">معرف</option>
                </select>
            </div>
            <div class="col-md-1">
                <div class="form-check mt-2">
                    <input type="checkbox" name="required" class="form-check-input" value="1" id="requiredCheck">
                    <label class="form-check-label" for="requiredCheck" style="font-size:0.85rem;">اجباری</label>
                </div>
            </div>
            <div class="col-md-2">
                <input type="number" name="sort_order" class="form-control" placeholder="ترتیب" value="0">
            </div>
            <div class="col-md-1">
                <button type="submit" name="add_field" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i></button>
            </div>
        </form>
    </div>
    
    <div class="table-search">
        <input type="text" id="searchFields" placeholder="🔍 جستجو در فیلدها..." onkeyup="filterTable('searchFields', 'tableFields')">
    </div>
    <div class="table-wrapper">
        <table class="table table-modern" id="tableFields">
            <thead>
                <tr>
                    <th>نام فیلد</th>
                    <th>لیبل فارسی</th>
                    <th>بخش</th>
                    <th>اجباری</th>
                    <th>وضعیت</th>
                    <th>عملیات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($fields as $field): ?>
                <tr>
                    <td><?php echo htmlspecialchars($field['field_name']); ?></td>
                    <td><?php echo htmlspecialchars($field['label'] ?? '-'); ?></td>
                    <td><?php echo $sections[$field['section']] ?? $field['section']; ?></td>
                    <td><?php echo $field['required'] ? '✅' : '❌'; ?></td>
                    <td>
                        <span class="badge bg-<?php echo $field['status'] == 'active' ? 'success' : 'danger'; ?>">
                            <?php echo $field['status'] == 'active' ? 'فعال' : 'غیرفعال'; ?>
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary btn-action" data-bs-toggle="collapse" data-bs-target="#editField<?php echo $field['id']; ?>"><i class="bi bi-pencil"></i></button>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="field_id" value="<?php echo $field['id']; ?>">
                            <input type="hidden" name="status" value="<?php echo $field['status'] == 'active' ? 'inactive' : 'active'; ?>">
                            <button type="submit" name="toggle_field" class="btn btn-sm btn-<?php echo $field['status'] == 'active' ? 'warning' : 'success'; ?> btn-action">
                                <i class="bi bi-<?php echo $field['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                            </button>
                        </form>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از حذف این فیلد مطمئن هستید؟');">
                            <input type="hidden" name="field_id" value="<?php echo $field['id']; ?>">
                            <button type="submit" name="delete_field" class="btn btn-sm btn-danger btn-action"><i class="bi bi-trash"></i></button>
                        </form>
                        <div class="collapse mt-2" id="editField<?php echo $field['id']; ?>">
                            <form method="POST" class="row g-1">
                                <input type="hidden" name="field_id" value="<?php echo $field['id']; ?>">
                                <div class="col-md-3"><input type="text" name="field_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($field['field_name']); ?>" required></div>
                                <div class="col-md-3"><input type="text" name="label" class="form-control form-control-sm" value="<?php echo htmlspecialchars($field['label'] ?? ''); ?>" required></div>
                                <div class="col-md-2">
                                    <select name="section" class="form-select form-select-sm" required>
                                        <option value="personal" <?php echo ($field['section'] ?? 'personal') == 'personal' ? 'selected' : ''; ?>>اطلاعات شخصی</option>
                                        <option value="educational" <?php echo ($field['section'] ?? '') == 'educational' ? 'selected' : ''; ?>>اطلاعات تحصیلی</option>
                                        <option value="status" <?php echo ($field['section'] ?? '') == 'status' ? 'selected' : ''; ?>>وضعیت‌ها</option>
                                        <option value="referral" <?php echo ($field['section'] ?? '') == 'referral' ? 'selected' : ''; ?>>معرف</option>
                                    </select>
                                </div>
                                <div class="col-md-1"><input type="checkbox" name="required" class="form-check-input" value="1" <?php echo $field['required'] ? 'checked' : ''; ?>></div>
                                <div class="col-md-2"><input type="number" name="sort_order" class="form-control form-control-sm" value="<?php echo $field['sort_order']; ?>"></div>
                                <div class="col-md-1"><button type="submit" name="edit_field" class="btn btn-sm btn-success w-100">ذخیره</button></div>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ============================================================
بخش ۲: مدیریت مقاطع تحصیلی
============================================================ -->
<div class="section-title" onclick="toggleSection(this)">
    <span>
        <i class="bi bi-mortarboard"></i>
        مدیریت مقاطع تحصیلی
        <span class="badge-count"><?php echo count($educations); ?></span>
    </span>
    <span class="toggle-icon"><i class="bi bi-chevron-down"></i></span>
</div>
<div class="section-body">
    <div class="add-form">
        <form method="POST" class="row g-2">
            <div class="col-md-6">
                <input type="text" name="edu_name" class="form-control" placeholder="نام مقطع جدید" required>
            </div>
            <div class="col-md-3">
                <input type="number" name="edu_sort" class="form-control" placeholder="ترتیب" value="0">
            </div>
            <div class="col-md-3">
                <button type="submit" name="add_education" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i> افزودن مقطع</button>
            </div>
        </form>
    </div>
    <div class="table-wrapper">
        <table class="table table-modern">
            <thead><tr><th>نام</th><th>وضعیت</th><th>عملیات</th></tr></thead>
            <tbody>
                <?php foreach($educations as $edu): ?>
                <tr>
                    <td><?php echo htmlspecialchars($edu['name']); ?></td>
                    <td>
                        <span class="badge bg-<?php echo $edu['status'] == 'active' ? 'success' : 'danger'; ?>">
                            <?php echo $edu['status'] == 'active' ? 'فعال' : 'غیرفعال'; ?>
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary btn-action" data-bs-toggle="collapse" data-bs-target="#editEdu<?php echo $edu['id']; ?>"><i class="bi bi-pencil"></i></button>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="edu_id" value="<?php echo $edu['id']; ?>">
                            <input type="hidden" name="status" value="<?php echo $edu['status'] == 'active' ? 'inactive' : 'active'; ?>">
                            <button type="submit" name="toggle_education" class="btn btn-sm btn-<?php echo $edu['status'] == 'active' ? 'warning' : 'success'; ?> btn-action">
                                <i class="bi bi-<?php echo $edu['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                            </button>
                        </form>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از حذف این مقطع مطمئن هستید؟');">
                            <input type="hidden" name="edu_id" value="<?php echo $edu['id']; ?>">
                            <button type="submit" name="delete_education" class="btn btn-sm btn-danger btn-action"><i class="bi bi-trash"></i></button>
                        </form>
                        <div class="collapse mt-2" id="editEdu<?php echo $edu['id']; ?>">
                            <form method="POST" class="row g-1">
                                <input type="hidden" name="edu_id" value="<?php echo $edu['id']; ?>">
                                <div class="col-md-6"><input type="text" name="edu_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($edu['name']); ?>" required></div>
                                <div class="col-md-4"><input type="number" name="edu_sort" class="form-control form-control-sm" value="<?php echo $edu['sort_order']; ?>"></div>
                                <div class="col-md-2"><button type="submit" name="edit_education" class="btn btn-sm btn-success w-100">ذخیره</button></div>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ============================================================
بخش ۳: مدیریت رشته‌های تحصیلی (با Ajax)
============================================================ -->
<div class="section-title" onclick="toggleSection(this)">
    <span>
        <i class="bi bi-book"></i>
        مدیریت رشته‌های تحصیلی
        <span class="badge-count" id="courseCount"><?php echo count($courses); ?></span>
    </span>
    <span class="toggle-icon"><i class="bi bi-chevron-down"></i></span>
</div>
<div class="section-body" id="courseSection">
    
    <div id="courseMessage" class="section-message"></div>
    
    <div class="add-form">
        <form id="addCourseForm" class="row g-2" onsubmit="submitCourseForm('add', this); return false;">
            <div class="col-md-4">
                <input type="text" name="course_name" class="form-control" placeholder="نام رشته جدید" required>
            </div>
            <div class="col-md-3">
                <select name="course_education_id" class="form-select" required>
                    <option value="">انتخاب مقطع...</option>
                    <?php foreach($educations as $edu): ?>
                        <option value="<?php echo $edu['id']; ?>"><?php echo htmlspecialchars($edu['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <input type="number" name="course_sort" class="form-control" placeholder="ترتیب" value="0">
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i> افزودن رشته</button>
            </div>
        </form>
    </div>
    
    <div class="table-search">
        <input type="text" id="searchCourses" placeholder="🔍 جستجو در رشته‌ها..." onkeyup="filterTable('searchCourses', 'tableCourses')">
    </div>
    <div class="table-wrapper">
        <table class="table table-modern" id="tableCourses">
            <thead>
                <tr>
                    <th style="width:25%;">نام رشته</th>
                    <th style="width:25%;">مقطع مرتبط</th>
                    <th style="width:15%;">وضعیت</th>
                    <th style="width:35%;">عملیات</th>
                </tr>
            </thead>
            <tbody id="coursesTableBody">
                <?php foreach($courses as $course): ?>
                <tr id="courseRow_<?php echo $course['id']; ?>">
                    <td><?php echo htmlspecialchars($course['name']); ?></td>
                    <td><?php echo htmlspecialchars($course['education_name'] ?? 'نامشخص'); ?></td>
                    <td>
                        <span class="badge bg-<?php echo $course['status'] == 'active' ? 'success' : 'danger'; ?>" id="courseStatus_<?php echo $course['id']; ?>">
                            <?php echo $course['status'] == 'active' ? 'فعال' : 'غیرفعال'; ?>
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary btn-action" onclick="toggleEditForm(<?php echo $course['id']; ?>)"><i class="bi bi-pencil"></i></button>
                        <button class="btn btn-sm btn-<?php echo $course['status'] == 'active' ? 'warning' : 'success'; ?> btn-action" onclick="toggleCourse(<?php echo $course['id']; ?>, '<?php echo $course['status']; ?>')">
                            <i class="bi bi-<?php echo $course['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                        </button>
                        <button class="btn btn-sm btn-danger btn-action" onclick="deleteCourse(<?php echo $course['id']; ?>)"><i class="bi bi-trash"></i></button>
                        
                        <div class="collapse mt-2" id="editForm_<?php echo $course['id']; ?>">
                            <form class="row g-1" onsubmit="submitCourseForm('edit', this, <?php echo $course['id']; ?>); return false;">
                                <input type="hidden" name="course_id" value="<?php echo $course['id']; ?>">
                                <div class="col-md-4"><input type="text" name="course_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($course['name']); ?>" required></div>
                                <div class="col-md-3">
                                    <select name="course_education_id" class="form-select form-select-sm" required>
                                        <?php foreach($educations as $edu): ?>
                                            <option value="<?php echo $edu['id']; ?>" <?php echo $course['education_id'] == $edu['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($edu['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3"><input type="number" name="course_sort" class="form-control form-control-sm" value="<?php echo $course['sort_order']; ?>"></div>
                                <div class="col-md-2"><button type="submit" class="btn btn-sm btn-success w-100">ذخیره</button></div>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ============================================================
بخش ۴: مدیریت روش‌های معرف
============================================================ -->
<div class="section-title" onclick="toggleSection(this)">
    <span>
        <i class="bi bi-share"></i>
        مدیریت روش‌های معرف (نحوه آشنایی)
        <span class="badge-count"><?php echo count($referrals); ?></span>
    </span>
    <span class="toggle-icon"><i class="bi bi-chevron-down"></i></span>
</div>
<div class="section-body">
    <div class="add-form">
        <form method="POST" class="row g-2">
            <div class="col-md-6">
                <input type="text" name="ref_name" class="form-control" placeholder="نام روش جدید" required>
            </div>
            <div class="col-md-3">
                <input type="number" name="ref_sort" class="form-control" placeholder="ترتیب" value="0">
            </div>
            <div class="col-md-3">
                <button type="submit" name="add_referral" class="btn btn-pastel w-100"><i class="bi bi-plus-lg"></i> افزودن روش</button>
            </div>
        </form>
    </div>
    <div class="table-wrapper">
        <table class="table table-modern">
            <thead><tr><th>نام</th><th>وضعیت</th><th>عملیات</th></tr></thead>
            <tbody>
                <?php foreach($referrals as $ref): ?>
                <tr>
                    <td><?php echo htmlspecialchars($ref['name']); ?></td>
                    <td>
                        <span class="badge bg-<?php echo $ref['status'] == 'active' ? 'success' : 'danger'; ?>">
                            <?php echo $ref['status'] == 'active' ? 'فعال' : 'غیرفعال'; ?>
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary btn-action" data-bs-toggle="collapse" data-bs-target="#editRef<?php echo $ref['id']; ?>"><i class="bi bi-pencil"></i></button>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="ref_id" value="<?php echo $ref['id']; ?>">
                            <input type="hidden" name="status" value="<?php echo $ref['status'] == 'active' ? 'inactive' : 'active'; ?>">
                            <button type="submit" name="toggle_referral" class="btn btn-sm btn-<?php echo $ref['status'] == 'active' ? 'warning' : 'success'; ?> btn-action">
                                <i class="bi bi-<?php echo $ref['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                            </button>
                        </form>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از حذف این روش معرف مطمئن هستید؟');">
                            <input type="hidden" name="ref_id" value="<?php echo $ref['id']; ?>">
                            <button type="submit" name="delete_referral" class="btn btn-sm btn-danger btn-action"><i class="bi bi-trash"></i></button>
                        </form>
                        <div class="collapse mt-2" id="editRef<?php echo $ref['id']; ?>">
                            <form method="POST" class="row g-1">
                                <input type="hidden" name="ref_id" value="<?php echo $ref['id']; ?>">
                                <div class="col-md-6"><input type="text" name="ref_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($ref['name']); ?>" required></div>
                                <div class="col-md-4"><input type="number" name="ref_sort" class="form-control form-control-sm" value="<?php echo $ref['sort_order']; ?>"></div>
                                <div class="col-md-2"><button type="submit" name="edit_referral" class="btn btn-sm btn-success w-100">ذخیره</button></div>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
// ============================================================
// توابع جمع‌شدنی (همون نسخه درست شده)
// ============================================================
function toggleSection(element) {
    element.classList.toggle('open');
    
    var body = element.nextElementSibling;
    if (body && body.classList.contains('section-body')) {
        body.classList.toggle('open');
    }
    
    var icon = element.querySelector('.toggle-icon i');
    if (icon) {
        if (element.classList.contains('open')) {
            icon.className = 'bi bi-chevron-up';
        } else {
            icon.className = 'bi bi-chevron-down';
        }
    }
}

// ============================================================
// جستجوی داخل جدول
// ============================================================
function filterTable(searchInputId, tableId) {
    var input = document.getElementById(searchInputId);
    var filter = input.value.toLowerCase();
    var table = document.getElementById(tableId);
    var rows = table.getElementsByTagName('tr');
    
    for (var i = 1; i < rows.length; i++) {
        var cells = rows[i].getElementsByTagName('td');
        var found = false;
        for (var j = 0; j < cells.length; j++) {
            var text = cells[j].textContent.toLowerCase();
            if (text.indexOf(filter) > -1) {
                found = true;
                break;
            }
        }
        rows[i].style.display = found ? '' : 'none';
    }
}

// ============================================================
// نمایش/مخفی کردن فرم ویرایش
// ============================================================
function toggleEditForm(courseId) {
    var form = document.getElementById('editForm_' + courseId);
    if (form) {
        form.classList.toggle('show');
    }
}

// ============================================================
// نمایش پیام در بخش رشته‌ها
// ============================================================
function showCourseMessage(message, type) {
    var msgDiv = document.getElementById('courseMessage');
    msgDiv.className = 'section-message ' + type;
    msgDiv.innerHTML = message;
    msgDiv.style.display = 'block';
    
    document.getElementById('courseSection').scrollIntoView({ behavior: 'smooth', block: 'center' });
    
    setTimeout(function() {
        msgDiv.style.display = 'none';
    }, 4000);
}

// ============================================================
// افزودن/ویرایش رشته با Ajax
// ============================================================
function submitCourseForm(action, form, courseId) {
    var formData = new FormData(form);
    formData.append('ajax_action', action == 'add' ? 'add_course' : 'edit_course');
    
    var btn = form.querySelector('button[type="submit"]');
    var originalText = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span>';
    btn.disabled = true;
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        btn.innerHTML = originalText;
        btn.disabled = false;
        
        if (data.success) {
            showCourseMessage(data.message, 'success');
            setTimeout(function() {
                location.reload();
            }, 800);
        } else {
            showCourseMessage(data.message, 'error');
        }
    })
    .catch(error => {
        btn.innerHTML = originalText;
        btn.disabled = false;
        showCourseMessage('❌ خطا در ارتباط با سرور', 'error');
    });
    
    return false;
}

// ============================================================
// تغییر وضعیت رشته (فعال/غیرفعال)
// ============================================================
function toggleCourse(courseId, currentStatus) {
    var newStatus = currentStatus == 'active' ? 'inactive' : 'active';
    
    if (!confirm('آیا از تغییر وضعیت این رشته مطمئن هستید؟')) {
        return;
    }
    
    var formData = new FormData();
    formData.append('ajax_action', 'toggle_course');
    formData.append('course_id', courseId);
    formData.append('status', newStatus);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showCourseMessage(data.message, 'success');
            var badge = document.getElementById('courseStatus_' + courseId);
            var btn = badge.parentElement.nextElementSibling.querySelector('button');
            if (newStatus == 'active') {
                badge.className = 'badge bg-success';
                badge.textContent = 'فعال';
                btn.className = 'btn btn-sm btn-warning btn-action';
                btn.innerHTML = '<i class="bi bi-pause"></i>';
            } else {
                badge.className = 'badge bg-danger';
                badge.textContent = 'غیرفعال';
                btn.className = 'btn btn-sm btn-success btn-action';
                btn.innerHTML = '<i class="bi bi-play"></i>';
            }
            btn.setAttribute('onclick', "toggleCourse(" + courseId + ", '" + newStatus + "')");
        } else {
            showCourseMessage(data.message, 'error');
        }
    })
    .catch(error => {
        showCourseMessage('❌ خطا در ارتباط با سرور', 'error');
    });
}

// ============================================================
// حذف رشته
// ============================================================
function deleteCourse(courseId) {
    if (!confirm('آیا از حذف این رشته مطمئن هستید؟ این عملیات غیرقابل بازگشت است.')) {
        return;
    }
    
    var formData = new FormData();
    formData.append('ajax_action', 'delete_course');
    formData.append('course_id', courseId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showCourseMessage(data.message, 'success');
            var row = document.getElementById('courseRow_' + courseId);
            if (row) {
                row.style.transition = 'all 0.3s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    var countSpan = document.getElementById('courseCount');
                    var currentCount = parseInt(countSpan.textContent);
                    countSpan.textContent = currentCount - 1;
                }, 300);
            }
        } else {
            showCourseMessage(data.message, 'error');
        }
    })
    .catch(error => {
        showCourseMessage('❌ خطا در ارتباط با سرور', 'error');
    });
}
</script>

<?php include '../includes/footer.php'; ?>