<?php
// admin/transactions-content-new.php - محتوای مدیریت تراکنش‌ها با جستجوی Ajax
?>

<!-- ============================================================
     پیام‌ها
     ============================================================ -->
<?php if ($message): ?>
<div class="alert alert-<?= strpos($message, '❌') !== false ? 'alert-danger' : 'alert-success' ?>">
    <i class="fas <?= strpos($message, '❌') !== false ? 'fa-exclamation-circle' : 'fa-check-circle' ?>"></i>
    <?= $message ?>
</div>
<?php endif; ?>

<!-- ============================================================
     بخش جستجو و فیلتر
     ============================================================ -->
<div class="filter-section" style="margin-bottom:20px;padding:16px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;">
        
        <!-- جستجوی استاد -->
        <div style="flex:2;min-width:200px;position:relative;">
            <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-user-search"></i> جستجوی استاد
            </label>
            <input type="text" id="searchTeacher" class="form-control" 
                   placeholder="نام، نام خانوادگی یا کد ملی..." 
                   autocomplete="off"
                   style="width:100%;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;">
            <input type="hidden" id="selected_teacher_id" value="<?= $selected_teacher_id ?>">
            <div id="searchResults" style="position:absolute;top:100%;right:0;left:0;background:white;border:2px solid #355C9C;border-radius:8px;max-height:250px;overflow-y:auto;display:none;z-index:1000;box-shadow:0 8px 25px rgba(0,0,0,0.15);margin-top:4px;"></div>
        </div>

        <!-- فیلتر ترم -->
        <div style="flex:1;min-width:130px;">
            <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-calendar-alt"></i> ترم
            </label>
            <select id="filterTerm" class="form-control" style="width:100%;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;background:white;">
                <option value="0">همه ترم‌ها</option>
                <?php foreach ($allTerms as $term): ?>
                <option value="<?= $term['id'] ?>" <?= ($selected_term_id == $term['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($term['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- دکمه‌ها -->
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <button type="submit" class="btn btn-primary" id="searchBtn" style="padding:10px 24px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;background:#1a237e;color:white;transition:all 0.3s;">
                <i class="fas fa-search"></i> جستجو
            </button>
            <a href="transactions.php" class="btn btn-outline" style="padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;text-decoration:none;background:transparent;color:#6b7280;border:2px solid #e5e7eb;transition:all 0.3s;display:inline-flex;align-items:center;gap:6px;">
                <i class="fas fa-redo"></i> بازنشانی
            </a>
        </div>
    </div>
</div>

<!-- ============================================================
     اسکریپت جستجوی Ajax
     ============================================================ -->
<script>
$(document).ready(function() {
    let searchTimer;
    const searchInput = $('#searchTeacher');
    const resultsDiv = $('#searchResults');
    const selectedTeacherId = $('#selected_teacher_id');

    searchInput.on('input', function() {
        clearTimeout(searchTimer);
        const query = $(this).val().trim();
        const termId = $('#filterTerm').val();

        if (query.length < 2) {
            resultsDiv.hide();
            return;
        }

        searchTimer = setTimeout(function() {
            $.ajax({
                url: 'ajax-search-transactions.php',
                type: 'GET',
                data: { search: query, term_id: termId },
                dataType: 'json',
                success: function(response) {
                    if (response.error) {
                        resultsDiv.html('<div style="padding:14px;color:#e74c3c;text-align:center;">' + response.error + '</div>').show();
                        return;
                    }
                    
                    if (response.teachers && response.teachers.length > 0) {
                        let html = '<div style="padding:10px 14px;font-weight:700;color:#1a237e;border-bottom:2px solid #e8eaf6;font-size:13px;">نتایج جستجو (' + response.total + '):</div>';
                        $.each(response.teachers, function(index, teacher) {
                            html += `<div class="search-item" data-id="${teacher.id}" data-name="${teacher.name} ${teacher.family}" style="padding:10px 14px;cursor:pointer;border-bottom:1px solid #f5f5f5;transition:all 0.2s;display:flex;justify-content:space-between;align-items:center;">
                                <span style="font-weight:600;color:#333;">${teacher.name} ${teacher.family}</span>
                                <span style="color:#888;font-size:12px;">${teacher.national_code}</span>
                            </div>`;
                        });
                        resultsDiv.html(html).show();
                    } else {
                        resultsDiv.html('<div style="padding:14px;color:#999;text-align:center;">نتیجه‌ای یافت نشد.</div>').show();
                    }
                },
                error: function() {
                    resultsDiv.html('<div style="padding:14px;color:#e74c3c;text-align:center;">خطا در ارتباط با سرور.</div>').show();
                }
            });
        }, 400);
    });

    $(document).on('click', '.search-item', function() {
        const teacherId = $(this).data('id');
        const teacherName = $(this).data('name');
        const termId = $('#filterTerm').val();
        
        searchInput.val(teacherName);
        resultsDiv.hide();
        
        window.location.href = 'transactions.php?teacher_id=' + teacherId + '&term_id=' + termId;
    });

    $('#searchBtn').on('click', function() {
        const query = searchInput.val().trim();
        const termId = $('#filterTerm').val();
        
        if (query === '') {
            window.location.href = 'transactions.php?term_id=' + termId;
        } else {
            $.ajax({
                url: 'ajax-search-transactions.php',
                type: 'GET',
                data: { search: query, term_id: termId },
                dataType: 'json',
                success: function(response) {
                    if (response.teachers && response.teachers.length > 0) {
                        if (response.teachers.length === 1) {
                            window.location.href = 'transactions.php?teacher_id=' + response.teachers[0].id + '&term_id=' + termId;
                        } else {
                            let html = '<div style="padding:10px 14px;font-weight:700;color:#1a237e;border-bottom:2px solid #e8eaf6;font-size:13px;">نتایج جستجو (' + response.total + '):</div>';
                            $.each(response.teachers, function(index, teacher) {
                                html += `<div class="search-item" data-id="${teacher.id}" data-name="${teacher.name} ${teacher.family}" style="padding:10px 14px;cursor:pointer;border-bottom:1px solid #f5f5f5;transition:all 0.2s;display:flex;justify-content:space-between;align-items:center;">
                                    <span style="font-weight:600;color:#333;">${teacher.name} ${teacher.family}</span>
                                    <span style="color:#888;font-size:12px;">${teacher.national_code}</span>
                                </div>`;
                            });
                            resultsDiv.html(html).show();
                        }
                    } else {
                        resultsDiv.html('<div style="padding:14px;color:#999;text-align:center;">نتیجه‌ای یافت نشد.</div>').show();
                    }
                }
            });
        }
    });

    $(document).on('click', function(e) {
        if (!$(e.target).closest('#searchTeacher, #searchResults, #searchBtn').length) {
            resultsDiv.hide();
        }
    });

    $(document).on('mouseenter', '.search-item', function() {
        $(this).css('background', '#e8eaf6');
    });
    $(document).on('mouseleave', '.search-item', function() {
        $(this).css('background', '');
    });
});
</script>

<!-- ============================================================
     نمایش داده‌ها
     ============================================================ -->

<?php if (!$selected_teacher_id): ?>
    
    <!-- ===== پیام انتخاب استاد ===== -->
    <div class="card" style="text-align:center;padding:60px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
        <i class="fas fa-user-search" style="font-size:64px;color:#9ca3af;display:block;margin-bottom:20px;opacity:0.2;"></i>
        <h3 style="font-size:20px;color:#6b7280;margin-bottom:12px;">برای مدیریت تراکنش‌ها، استاد را جستجو کنید</h3>
        <p style="font-size:14px;color:#9ca3af;max-width:500px;margin:0 auto;">
            از بخش جستجو در بالا، نام استاد مورد نظر را وارد کنید و سپس تراکنش‌های او را مدیریت کنید.
        </p>
        <div style="display:flex;gap:12px;justify-content:center;margin-top:24px;flex-wrap:wrap;">
            <span style="padding:8px 20px;background:#dbeafe;border-radius:8px;color:#1a237e;font-size:13px;">
                <i class="fas fa-user"></i> جستجو بر اساس نام استاد
            </span>
            <span style="padding:8px 20px;background:#dbeafe;border-radius:8px;color:#1a237e;font-size:13px;">
                <i class="fas fa-calendar"></i> فیلتر بر اساس ترم
            </span>
        </div>
    </div>

<?php elseif ($selected_teacher_id > 0 && $selectedTeacher): ?>

    <!-- ===== اطلاعات استاد انتخاب شده ===== -->
    <div class="card" style="margin-bottom:20px;padding:16px 20px;background:linear-gradient(135deg, #355C9C, #2FA7A3);color:white;border-radius:12px;">
        <div style="display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;">
            <div>
                <h3 style="font-size:18px;font-weight:700;margin:0;">
                    <i class="fas fa-user-graduate"></i> 
                    <?= htmlspecialchars($selectedTeacher['name'] . ' ' . $selectedTeacher['family']) ?>
                </h3>
                <div style="font-size:13px;opacity:0.9;margin-top:4px;">
                    کد ملی: <?= $selectedTeacher['national_code'] ?> | 
                    <?php if (!empty($selected_term_id)): ?>
                        ترم: <?= htmlspecialchars(getTermName($selected_term_id)) ?>
                    <?php else: ?>
                        همه ترم‌ها
                    <?php endif; ?>
                </div>
            </div>
            <div style="text-align:left;background:rgba(255,255,255,0.15);padding:8px 18px;border-radius:12px;">
                <div style="font-size:12px;opacity:0.8;">جمع کل واریزی</div>
                <div style="font-size:20px;font-weight:700;"><?= formatPrice($totalAmount) ?></div>
                <div style="font-size:11px;opacity:0.7;"><?= count($transactions) ?> تراکنش</div>
            </div>
        </div>
    </div>

    <!-- ===== دکمه ثبت تراکنش ===== -->
    <div style="display:flex;justify-content:flex-end;margin-bottom:16px;">
        <button class="btn btn-success" onclick="toggleAddForm()" style="padding:10px 24px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;background:#10b981;color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:8px;">
            <i class="fas fa-plus-circle"></i> ثبت تراکنش جدید
        </button>
    </div>

    <!-- ===== فرم ثبت تراکنش (مخفی) ===== -->
    <div id="addForm" style="display:none;margin-bottom:20px;padding:20px 24px;background:#f8fafc;border-radius:12px;border:1px solid #e5e7eb;">
        <h5 style="font-size:16px;font-weight:700;color:#1f2937;margin-bottom:16px;">📝 ثبت تراکنش جدید</h5>
        <form method="POST" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;">
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="teacher_id" value="<?= $selected_teacher_id ?>">
            
            <div>
                <label style="display:block;font-weight:600;color:#374151;margin-bottom:5px;font-size:13px;">مبلغ (ریال)</label>
                <input type="number" name="amount" placeholder="مبلغ" class="form-control" style="width:100%;padding:10px 14px;border:2px solid #e5e7eb;border-radius:8px;font-size:14px;" required>
            </div>
            <div>
                <label style="display:block;font-weight:600;color:#374151;margin-bottom:5px;font-size:13px;">تاریخ واریز</label>
                <input type="text" name="payment_date" placeholder="1404/07/01" class="form-control" style="width:100%;padding:10px 14px;border:2px solid #e5e7eb;border-radius:8px;font-size:14px;" required>
            </div>
            <div>
                <label style="display:block;font-weight:600;color:#374151;margin-bottom:5px;font-size:13px;">ترم</label>
                <select name="term_id" class="form-control" style="width:100%;padding:10px 14px;border:2px solid #e5e7eb;border-radius:8px;font-size:14px;background:white;">
                    <option value="0">بدون ترم</option>
                    <?php foreach ($allTerms as $term): ?>
                    <option value="<?= $term['id'] ?>"><?= htmlspecialchars($term['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;font-weight:600;color:#374151;margin-bottom:5px;font-size:13px;">توضیحات</label>
                <input type="text" name="description" placeholder="اختیاری" class="form-control" style="width:100%;padding:10px 14px;border:2px solid #e5e7eb;border-radius:8px;font-size:14px;">
            </div>
            <div style="display:flex;align-items:flex-end;">
                <button type="submit" class="btn btn-success" style="width:100%;padding:10px 24px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;background:#10b981;color:white;transition:all 0.3s;">
                    <i class="fas fa-save"></i> ثبت
                </button>
            </div>
        </form>
    </div>

    <!-- ===== لیست تراکنش‌ها ===== -->
    <?php if (empty($transactions)): ?>
        <div class="card" style="text-align:center;padding:40px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
            <i class="fas fa-coins" style="font-size:48px;color:#9ca3af;display:block;margin-bottom:16px;opacity:0.3;"></i>
            <p style="font-size:18px;color:#6b7280;">هیچ تراکنشی برای این استاد ثبت نشده است.</p>
        </div>
    <?php else: ?>

        <!-- ===== کارت‌های خلاصه ترم ===== -->
        <?php if (!empty($termTotals)): ?>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:24px;">
            <?php foreach ($termTotals as $termId => $termData): ?>
            <div class="stat-card" style="text-align:center;padding:16px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;transition:all 0.3s;">
                <div style="font-size:14px;color:#6b7280;"><?= htmlspecialchars($termData['name']) ?></div>
                <div style="font-size:22px;font-weight:800;color:#355C9C;margin-top:4px;"><?= formatPrice($termData['total']) ?></div>
                <div style="font-size:12px;color:#9ca3af;"><?= $termData['count'] ?> تراکنش</div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- ===== جدول تراکنش‌ها ===== -->
        <div class="card" style="padding:0;overflow:hidden;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
            <div class="table-responsive" style="overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;font-size:14px;">
                    <thead>
                        <tr style="background:#f8fafc;border-bottom:2px solid #e5e7eb;">
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;width:50px;">#</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">تاریخ واریز</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">مبلغ (ریال)</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">ترم</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;">منبع</th>
                            <th style="padding:12px 16px;text-align:right;color:#6b7280;font-weight:600;font-size:13px;">توضیحات</th>
                            <th style="padding:12px 16px;text-align:center;color:#6b7280;font-weight:600;font-size:13px;width:180px;">عملیات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; foreach ($transactions as $transaction): ?>
                        <tr style="border-bottom:1px solid #f3f4f6;" class="table-row-hover">
                            <form method="POST" style="display:contents;">
                                <input type="hidden" name="action" value="edit">
                                <input type="hidden" name="id" value="<?= $transaction['id'] ?>">
                                
                                <td style="padding:10px 16px;text-align:center;"><?= $i++ ?></td>
                                
                                <td style="padding:10px 16px;text-align:center;">
                                    <input type="text" name="payment_date" 
                                           value="<?= jalaliDate($transaction['payment_date']) ?>" 
                                           class="form-control" style="width:120px;padding:6px 10px;border:2px solid #e5e7eb;border-radius:6px;font-size:13px;text-align:center;display:inline-block;background:transparent;transition:all 0.2s;">
                                </td>
                                
                                <td style="padding:10px 16px;text-align:center;">
                                    <input type="text" name="amount" 
                                           value="<?= number_format(round($transaction['amount'])) ?>" 
                                           class="form-control" style="width:130px;padding:6px 10px;border:2px solid #e5e7eb;border-radius:6px;font-size:13px;text-align:center;display:inline-block;background:transparent;transition:all 0.2s;" 
                                           dir="ltr">
                                </td>
                                
                                <td style="padding:10px 16px;text-align:center;">
                                    <select name="term_id" class="form-control" style="width:130px;padding:6px 10px;border:2px solid #e5e7eb;border-radius:6px;font-size:13px;background:white;display:inline-block;">
                                        <option value="0">بدون ترم</option>
                                        <?php foreach ($allTerms as $term): ?>
                                        <option value="<?= $term['id'] ?>" <?= $transaction['term_id'] == $term['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($term['name']) ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                
                                <td style="padding:10px 16px;text-align:center;">
                                    <?php if (isset($transaction['source']) && $transaction['source'] == 'excel'): ?>
                                        <span style="background:#fef3c7;color:#92400e;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:500;">📤 اکسل</span>
                                    <?php else: ?>
                                        <span style="background:#d1fae5;color:#065f46;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:500;">🖥️ دستی</span>
                                    <?php endif; ?>
                                </td>
                                
                                <td style="padding:10px 16px;">
                                    <input type="text" name="description" value="<?= htmlspecialchars($transaction['description'] ?? '') ?>" 
                                           class="form-control" style="width:100%;padding:6px 10px;border:2px solid #e5e7eb;border-radius:6px;font-size:13px;background:transparent;transition:all 0.2s;" placeholder="توضیحات">
                                </td>
                                
                                <td style="padding:10px 16px;text-align:center;white-space:nowrap;">
                                    <button type="submit" class="btn-action btn-action-edit" title="ذخیره">
                                        <i class="fas fa-save"></i>
                                    </button>
                                    <button type="submit" class="btn-action btn-action-delete" title="حذف"
                                            onclick="this.form.action.value='delete'; return confirm('آیا از حذف این تراکنش مطمئن هستید؟')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </form>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ===== جمع کل ===== -->
        <div class="card" style="margin-top:20px;padding:14px 20px;background:#f0fdf4;border-radius:12px;border:2px solid #bbf7d0;">
            <div style="display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;">
                <span style="font-weight:700;color:#1f2937;font-size:16px;">
                    <i class="fas fa-calculator" style="color:#059669;"></i> جمع کل همه تراکنش‌ها
                    <span style="font-size:13px;color:#9ca3af;font-weight:400;">(<?= count($transactions) ?> تراکنش)</span>
                </span>
                <span style="font-weight:800;font-size:22px;color:#059669;"><?= formatPrice($totalAmount) ?></span>
            </div>
        </div>

    <?php endif; ?>

<?php endif; ?>

<!-- ============================================================
     اسکریپت نمایش/مخفی کردن فرم
     ============================================================ -->
<script>
function toggleAddForm() {
    const form = document.getElementById('addForm');
    if (form.style.display === 'none' || form.style.display === '') {
        form.style.display = 'block';
    } else {
        form.style.display = 'none';
    }
}
</script>