<?php
// admin/report-payment-content.php - گزارش پرداخت حرفه‌ای (جدول یکپارچه)
?>

<!-- ============================================================
     بخش جستجو و فیلتر
     ============================================================ -->
<div class="filter-section" style="margin-bottom:20px;padding:16px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <form id="searchForm" method="GET" action="report-payment.php" style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;">
        
        <div style="flex:1;min-width:130px;">
            <label for="term_id" style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-calendar-alt"></i> ترم
            </label>
            <select name="term_id" id="term_id" 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 $t): ?>
                    <option value="<?= $t['id'] ?>" <?= ($term_id == $t['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($t['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div style="flex:1;min-width:130px;">
            <label for="degree" style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-graduation-cap"></i> مدرک تحصیلی
            </label>
            <select name="degree" id="degree" class="form-control" style="width:100%;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;background:white;">
                <option value="0">همه مقاطع</option>
                <option value="1" <?= ($degree == 1) ? 'selected' : '' ?>>کارشناسی</option>
                <option value="2" <?= ($degree == 2) ? 'selected' : '' ?>>کارشناسی ارشد</option>
                <option value="3" <?= ($degree == 3) ? 'selected' : '' ?>>دکتری</option>
            </select>
        </div>

        <div style="flex:2;min-width:200px;position:relative;">
            <label for="teacherSearch" style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;color:#6b7280;">
                <i class="fas fa-user-search"></i> جستجوی استاد
            </label>
            <div style="display:flex;gap:8px;">
                <input type="text" id="teacherSearch" class="form-control" 
                       placeholder="نام، نام خانوادگی یا کد ملی..." 
                       value="<?= $search ?? '' ?>" 
                       autocomplete="off"
                       style="flex:1;padding:8px 12px;border-radius:8px;border:2px solid #e5e7eb;">
                <input type="hidden" name="teacher_id" id="teacher_id" value="<?= $teacher_id ?>">
                <input type="hidden" name="search" id="search_input" value="<?= $search ?? '' ?>">
            </div>
            <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="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
            <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:linear-gradient(135deg, #355C9C, #2FA7A3);color:white;transition:all 0.3s;">
                <i class="fas fa-search"></i> نمایش گزارش
            </button>
            <a href="report-payment.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>
    </form>
</div>

<!-- ============================================================
     اسکریپت جستجوی Ajax
     ============================================================ -->
<script>
$(document).ready(function() {
    let searchTimer;
    const searchInput = $('#teacherSearch');
    const resultsDiv = $('#searchResults');
    const teacherIdInput = $('#teacher_id');
    const searchHiddenInput = $('#search_input');
    const searchForm = $('#searchForm');

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

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

        searchTimer = setTimeout(function() {
            $.ajax({
                url: 'ajax-search-teachers.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');
        
        teacherIdInput.val(teacherId);
        searchInput.val(teacherName);
        searchHiddenInput.val(teacherName);
        resultsDiv.hide();
        searchForm.submit();
    });

    $('#searchBtn').on('click', function(e) {
        e.preventDefault();
        const searchVal = searchInput.val().trim();
        const termId = $('#term_id').val();
        const degree = $('#degree').val();
        
        if (searchVal === '') {
            teacherIdInput.val(0);
            searchHiddenInput.val('');
        } else {
            searchHiddenInput.val(searchVal);
        }
        searchForm.submit();
    });

    searchInput.on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('#searchBtn').click();
        }
    });

    $(document).on('click', function(e) {
        if (!$(e.target).closest('#teacherSearch, #searchResults').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 (!$hasSearch): ?>

<div class="card" style="text-align:center;padding:80px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <i class="fas fa-search" style="font-size:64px;color:#9ca3af;display:block;margin-bottom:20px;opacity:0.2;"></i>
    <h3 style="font-size:22px;color:#6b7280;margin-bottom:12px;">برای مشاهده گزارش، جستجو کنید</h3>
    <p style="font-size:15px;color:#9ca3af;max-width:500px;margin:0 auto;">
        با استفاده از بخش جستجو در بالا، استاد مورد نظر را پیدا کنید یا با انتخاب ترم، گزارش را مشاهده کنید.
    </p>
</div>

<?php elseif (empty($reportData)): ?>

<div class="card" style="text-align:center;padding:60px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <i class="fas fa-file-invoice" style="font-size:48px;color:#9ca3af;display:block;margin-bottom:16px;opacity:0.3;"></i>
    <p style="font-size:18px;color:#6b7280;">هیچ داده‌ای برای نمایش وجود ندارد.</p>
    <p style="font-size:14px;color:#9ca3af;">لطفاً فیلترهای جستجو را تغییر دهید.</p>
</div>

<?php else: ?>

<!-- ============================================================
     جمع کل کلی (کارت‌های آماری)
     ============================================================ -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:20px;">
    <div style="text-align:center;padding:14px 16px;background:#fff;border-radius:10px;border:1px solid #e5e7eb;">
        <div style="font-size:12px;color:#6b7280;">جمع کل حق التدریس</div>
        <div style="font-size:20px;font-weight:800;color:#355C9C;"><?= formatPrice($totalAmount) ?></div>
    </div>
    <div style="text-align:center;padding:14px 16px;background:#fff;border-radius:10px;border:1px solid #e5e7eb;">
        <div style="font-size:12px;color:#6b7280;">جمع کل مالیات</div>
        <div style="font-size:20px;font-weight:800;color:#dc2626;"><?= formatPrice($totalTax) ?></div>
    </div>
    <div style="text-align:center;padding:14px 16px;background:#fff;border-radius:10px;border:1px solid #e5e7eb;">
        <div style="font-size:12px;color:#6b7280;">جمع کل بیمه</div>
        <div style="font-size:20px;font-weight:800;color:#d97706;"><?= formatPrice($totalInsurance) ?></div>
    </div>
    <div style="text-align:center;padding:14px 16px;background:#e8f0fe;border-radius:10px;border:2px solid #355C9C;">
        <div style="font-size:12px;color:#6b7280;">مبلغ قابل پرداخت</div>
        <div style="font-size:20px;font-weight:800;color:#355C9C;"><?= formatPrice($totalNet) ?></div>
    </div>
</div>

<!-- ============================================================
     جدول یکپارچه گزارش
     ============================================================ -->
<div style="margin-bottom:16px;">
    <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:10px;">
        <h4 style="font-size:15px;font-weight:700;color:#1f2937;margin:0;">
            <i class="fas fa-table" style="color:#355C9C;"></i> گزارش تفصیلی اساتید
            <span style="font-size:12px;color:#9ca3af;font-weight:400;">(<?= count($reportData) ?> استاد - <?= $totalCourses ?? 0 ?> درس)</span>
        </h4>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <button onclick="window.print()" class="btn btn-primary" style="padding:6px 16px;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:linear-gradient(135deg, #355C9C, #2FA7A3);color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:4px;">
                <i class="fas fa-print"></i> چاپ
            </button>
            <a href="export-payment-excel.php?teacher_id=<?= $teacher_id ?>&term_id=<?= $term_id ?>&degree=<?= $degree ?>&search=<?= urlencode($search ?? '') ?>" 
               class="btn btn-success" style="padding:6px 16px;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:#10b981;color:white;transition:all 0.3s;text-decoration:none;display:inline-flex;align-items:center;gap:4px;">
                <i class="fas fa-file-excel"></i> اکسل
            </a>
            <a href="export-payment-pdf.php?teacher_id=<?= $teacher_id ?>&term_id=<?= $term_id ?>&degree=<?= $degree ?>&search=<?= urlencode($search ?? '') ?>" 
               class="btn btn-danger" style="padding:6px 16px;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;background:#dc2626;color:white;transition:all 0.3s;text-decoration:none;display:inline-flex;align-items:center;gap:4px;">
                <i class="fas fa-file-pdf"></i> PDF
            </a>
        </div>
    </div>
    
    <div style="overflow-x:auto;border-radius:10px;border:1px solid #e5e7eb;">
        <table style="width:100%;border-collapse:collapse;font-size:12px;">
            <thead>
                <tr style="background:#f1f5f9;border-bottom:2px solid #e5e7eb;">
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">#</th>
                    <th style="padding:8px 10px;text-align:right;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">نام استاد</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">کد ملی</th>
                    <th style="padding:8px 10px;text-align:right;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">نام درس</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">ترم</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">نوع</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">جلسات</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">دانشجویان</th>
                    <th style="padding:8px 10px;text-align:center;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">مبلغ واحد</th>
                    <th style="padding:8px 10px;text-align:left;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">مبلغ کل</th>
                    <th style="padding:8px 10px;text-align:left;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">مالیات</th>
                    <th style="padding:8px 10px;text-align:left;color:#6b7280;font-weight:700;font-size:11px;white-space:nowrap;">بیمه</th>
                    <th style="padding:8px 10px;text-align:left;color:#355C9C;font-weight:700;font-size:11px;white-space:nowrap;">مبلغ نهایی</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $rowNum = 1;
                $totalCourses = 0;
                foreach ($reportData as $teacherId => $teacher):
                    foreach ($teacher['terms'] as $termId => $term):
                        foreach ($term['courses'] as $course):
                            $totalCourses++;
                ?>
                <tr style="border-bottom:1px solid #f3f4f6;">
                    <td style="padding:6px 10px;text-align:center;"><?= $rowNum++ ?></td>
                    <td style="padding:6px 10px;font-weight:600;color:#1f2937;white-space:nowrap;">
                        <?= htmlspecialchars($teacher['name'] . ' ' . $teacher['family']) ?>
                    </td>
                    <td style="padding:6px 10px;text-align:center;color:#6b7280;"><?= $teacher['national_code'] ?></td>
                    <td style="padding:6px 10px;font-weight:500;color:#1f2937;"><?= htmlspecialchars($course['course_name']) ?></td>
                    <td style="padding:6px 10px;text-align:center;font-size:11px;color:#6b7280;">
                        <?= htmlspecialchars($term['term_name'] ?? '-') ?>
                    </td>
                    <td style="padding:6px 10px;text-align:center;">
                        <span style="background:<?= ($course['course_type'] == 'theoretical') ? '#dbeafe' : '#fef3c7' ?>;color:<?= ($course['course_type'] == 'theoretical') ? '#1e40af' : '#92400e' ?>;padding:1px 8px;border-radius:3px;font-size:10px;font-weight:500;white-space:nowrap;">
                            <?= getCourseTypeName($course['course_type']) ?>
                        </span>
                    </td>
                    <td style="padding:6px 10px;text-align:center;"><?= $course['sessions_count'] ?></td>
                    <td style="padding:6px 10px;text-align:center;"><?= $course['student_count'] ?></td>
                    <td style="padding:6px 10px;text-align:center;font-size:11px;white-space:nowrap;">
                        <?= formatPrice($course['amount_per_hour'] ?: $course['amount_per_student']) ?>
                    </td>
                    <td style="padding:6px 10px;text-align:left;font-weight:600;color:#1f2937;white-space:nowrap;"><?= formatPrice($course['amount']) ?></td>
                    <td style="padding:6px 10px;text-align:left;color:#dc2626;white-space:nowrap;"><?= formatPrice($course['tax']) ?></td>
                    <td style="padding:6px 10px;text-align:left;color:#d97706;white-space:nowrap;"><?= formatPrice($course['insurance']) ?></td>
                    <td style="padding:6px 10px;text-align:left;font-weight:700;color:#059669;white-space:nowrap;"><?= formatPrice($course['net']) ?></td>
                </tr>
                <?php 
                        endforeach;
                    endforeach;
                endforeach; 
                ?>
            </tbody>
            <tfoot>
                <tr style="background:#f1f5f9;border-top:2px solid #e5e7eb;font-weight:700;">
                    <td colspan="9" style="padding:8px 12px;text-align:left;color:#1f2937;">جمع کل</td>
                    <td style="padding:8px 12px;text-align:left;color:#355C9C;"><?= formatPrice($totalAmount) ?></td>
                    <td style="padding:8px 12px;text-align:left;color:#dc2626;"><?= formatPrice($totalTax) ?></td>
                    <td style="padding:8px 12px;text-align:left;color:#d97706;"><?= formatPrice($totalInsurance) ?></td>
                    <td style="padding:8px 12px;text-align:left;font-size:15px;color:#059669;"><?= formatPrice($totalNet) ?></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- ============================================================
     تاریخ چاپ
     ============================================================ -->
<div style="text-align:center;color:#9ca3af;font-size:12px;margin-top:16px;padding-top:12px;border-top:1px solid #e5e7eb;">
    تاریخ چاپ: <?= jalaliDate(date('Y-m-d H:i:s')) ?>
</div>

<?php endif; ?>

<!-- ============================================================
     استایل‌های چاپ
     ============================================================ -->
<style>
@media print {
    .filter-section, .btn, .no-print { display: none !important; }
    body { background: white !important; }
    .card, .stat-card, [style*="border"] { 
        box-shadow: none !important; 
        border-color: #d1d5db !important;
    }
    .footer-bar, .top-header, .sidebar, .sidebar-overlay { display: none !important; }
    .main-content { margin: 0 !important; padding: 5px !important; }
    table { font-size: 9px !important; }
    table td, table th { padding: 3px 5px !important; }
    [style*="background:linear-gradient"] { background: #355C9C !important; }
    .table-responsive { overflow: visible !important; }
}
</style>