<?php
// admin/payment-calculate-content.php - محتوای فیش پرداخت با نمایش ترم‌های جداگانه

$searchValue = isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '';
$teacherIdValue = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
$termIdValue = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;
$selectedTeacherName = isset($selectedTeacher) ? htmlspecialchars($selectedTeacher['name'] . ' ' . $selectedTeacher['family']) : '';
$printAll = isset($_GET['print_all']) ? (int)$_GET['print_all'] : 0;

// ===== دریافت تنظیمات سامانه =====
$settings = getSettings();
$siteName = $settings['site_name'] ?? 'سامانه مدیریت اساتید';
$institutionName = $settings['institution_name'] ?? 'دانشگاه علوم و فناوری';
$logoPath = !empty($settings['logo']) ? '../' . $settings['logo'] : '';
$footerDeveloper = $settings['footer_developer'] ?? '';

// ===== جمع کل همه ترم‌ها =====
$grandTotalAmount = 0;
$grandTotalTax = 0;
$grandTotalInsurance = 0;
$grandTotalNet = 0;
?>

<!-- ============================================================
     بخش جستجو و فیلتر
     ============================================================ -->
<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="payment-calculate.php" style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;">
        
        <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="<?= $selectedTeacherName ?: $searchValue ?>" 
                       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="<?= $teacherIdValue ?>">
                <input type="hidden" name="search" id="search_input" value="<?= $searchValue ?>">
            </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;">
            <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="payment-calculate.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>

<script>
$(document).ready(function() {
    let searchTimer;
    const searchInput = $('#teacherSearch');
    const resultsDiv = $('#searchResults');
    const teacherIdInput = $('#teacher_id');
    const searchHiddenInput = $('#search_input');

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

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

        searchTimer = setTimeout(function() {
            $.ajax({
                url: 'ajax-search-payment.php',
                type: 'GET',
                data: { search: query },
                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();
    });

    $(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 ($teacher_id > 0 && !empty($teacherTerms)): ?>

<!-- ===== اطلاعات استاد ===== -->
<div class="card" style="margin-bottom:20px;padding:16px 20px;background:linear-gradient(135deg, #1a237e, #283593);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'] ?> | 
                مدرک: <?= getDegreeName($selectedTeacher['degree']) ?>
            </div>
        </div>
        <div style="text-align:left;background:rgba(255,255,255,0.15);padding:6px 16px;border-radius:12px;">
            <div style="font-size:12px;opacity:0.8;">تعداد ترم‌ها</div>
            <div style="font-size:18px;font-weight:700;"><?= count($teacherTerms) ?></div>
        </div>
    </div>
</div>

<!-- ===== دکمه خروجی همه ترم‌ها ===== -->
<?php if (count($teacherTerms) > 1): ?>
<div style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:20px;padding:12px 16px;background:#f8fafc;border-radius:12px;border:1px solid #e5e7eb;">
    <span style="font-weight:600;color:#1f2937;font-size:14px;display:flex;align-items:center;gap:8px;">
        <i class="fas fa-file-pdf" style="color:#dc2626;"></i> خروجی همه ترم‌ها:
    </span>
    <form method="GET" action="export-payment-pdf.php" style="display:inline-block;" target="_blank">
        <input type="hidden" name="teacher_id" value="<?= $teacher_id ?>">
        <input type="hidden" name="term_id" value="0">
        <input type="hidden" name="all_terms" value="1">
        <button type="submit" class="btn btn-danger" style="padding:6px 18px;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;background:#dc2626;color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:6px;">
            <i class="fas fa-file-pdf"></i> PDF همه ترم‌ها
        </button>
    </form>
    <button onclick="window.print()" class="btn btn-success" style="padding:6px 18px;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;background:#10b981;color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:6px;">
        <i class="fas fa-print"></i> چاپ همه ترم‌ها
    </button>
</div>
<?php endif; ?>

<!-- ============================================================
     نمایش هر ترم به صورت کارت جداگانه
     ============================================================ -->
<?php 
$termData = [];
$grandTotalAmount = 0;
$grandTotalTax = 0;
$grandTotalInsurance = 0;
$grandTotalNet = 0;

foreach ($teacherTerms as $t):
    $termId = $t['id'];
    
    // ===== دریافت دروس این ترم =====
    $courses = fetchAll(
        "SELECT c.*, 
                cs.sessions_count, cs.student_count,
                u.degree
         FROM courses c
         LEFT JOIN course_sessions cs ON c.id = cs.course_id AND c.term_id = cs.term_id
         LEFT JOIN users u ON c.teacher_id = u.id
         WHERE c.teacher_id = ? AND c.term_id = ?",
        [$teacher_id, $termId]
    );
    
    $termTotal = 0;
    $termTax = 0;
    $termInsurance = 0;
    $termNet = 0;
    $termCourses = [];
    
    $degree = $selectedTeacher['degree'] ?? 1;
    
    foreach ($courses as $course) {
        $courseType = $course['course_type'] ?? 'theoretical';
        $salarySetting = getSalaryAmount($degree, $courseType);
        
        if ($salarySetting) {
            if ($courseType == 'theoretical') {
                $sessions = $course['sessions_count'] ?? 0;
                $hoursPerSession = $course['hours'] ?? 1;
                $amountPerHour = $salarySetting['amount_per_hour'] ?? 0;
                $courseTotal = $sessions * $hoursPerSession * $amountPerHour;
                $unitPrice = $amountPerHour;
                $unitLabel = 'ساعتی';
            } else {
                $students = $course['student_count'] ?? 0;
                $amountPerStudent = $salarySetting['amount_per_student'] ?? 0;
                $courseTotal = $students * $amountPerStudent;
                $unitPrice = $amountPerStudent;
                $unitLabel = 'دانشجویی';
            }
            
            $courseTax = $courseTotal * ($taxPercent / 100);
            $courseInsurance = $courseTotal * ($insurancePercent / 100);
            $courseNet = $courseTotal - $courseTax - $courseInsurance;
            
            $termCourses[] = [
                'course_name' => $course['name'],
                'course_type' => $courseType,
                'sessions' => $course['sessions_count'] ?? 0,
                'students' => $course['student_count'] ?? 0,
                'unit_price' => $unitPrice,
                'unit_label' => $unitLabel,
                'total' => $courseTotal,
                'tax' => $courseTax,
                'insurance' => $courseInsurance,
                'net' => $courseNet
            ];
            
            $termTotal += $courseTotal;
            $termTax += $courseTax;
            $termInsurance += $courseInsurance;
            $termNet += $courseNet;
        }
    }
    
    $grandTotalAmount += $termTotal;
    $grandTotalTax += $termTax;
    $grandTotalInsurance += $termInsurance;
    $grandTotalNet += $termNet;
    
    $termData[] = [
        'term' => $t,
        'courses' => $termCourses,
        'total' => $termTotal,
        'tax' => $termTax,
        'insurance' => $termInsurance,
        'net' => $termNet
    ];
endforeach;
?>

<!-- ============================================================
     نمایش کارت‌های هر ترم
     ============================================================ -->
<?php foreach ($termData as $index => $data): 
    $term = $data['term'];
    $courses = $data['courses'];
    $termTotal = $data['total'];
    $termTax = $data['tax'];
    $termInsurance = $data['insurance'];
    $termNet = $data['net'];
?>

<div class="card" style="margin-bottom:24px;padding:0;overflow:hidden;border:1px solid #e5e7eb;">
    
    <!-- ===== هدر ترم ===== -->
    <div style="padding:12px 20px;background:linear-gradient(135deg, #f8fafc, #eef2ff);border-bottom:2px solid #e5e7eb;display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;">
        <div style="display:flex;align-items:center;gap:10px;">
            <span style="font-size:18px;font-weight:700;color:#1a237e;">
                <?= htmlspecialchars($term['name']) ?>
            </span>
            <span style="font-size:13px;color:#6b7280;">(<?= htmlspecialchars($term['code']) ?>)</span>
            <span style="font-size:12px;color:#9ca3af;background:#f3f4f6;padding:2px 12px;border-radius:12px;">
                <?= count($courses) ?> درس
            </span>
        </div>
        <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
            <span style="font-size:13px;color:#6b7280;">
                قابل پرداخت: <strong style="color:#059669;font-size:15px;"><?= formatPrice($termNet) ?></strong>
            </span>
            <form method="GET" action="export-payment-pdf.php" style="display:inline-block;" target="_blank">
                <input type="hidden" name="teacher_id" value="<?= $teacher_id ?>">
                <input type="hidden" name="term_id" value="<?= $term['id'] ?>">
                <button type="submit" class="btn btn-danger btn-sm" style="padding:4px 12px;font-size:12px;border-radius:6px;border:none;cursor:pointer;background:#dc2626;color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:4px;">
                    <i class="fas fa-file-pdf"></i> PDF
                </button>
            </form>
            <button onclick="printTerm(<?= $term['id'] ?>)" class="btn btn-success btn-sm" style="padding:4px 12px;font-size:12px;border-radius:6px;border:none;cursor:pointer;background:#10b981;color:white;transition:all 0.3s;display:inline-flex;align-items:center;gap:4px;">
                <i class="fas fa-print"></i> چاپ
            </button>
        </div>
    </div>
    
    <!-- ===== محتوای ترم ===== -->
    <div style="padding:16px 20px;">
        <?php if (empty($courses)): ?>
            <div style="text-align:center;padding:20px;color:#9ca3af;">هیچ درسی برای این ترم ثبت نشده است.</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table" style="width:100%;border-collapse:collapse;font-size:13px;">
                    <thead>
                        <tr style="background:#f8fafc;border-bottom:2px solid #e5e7eb;">
                            <th style="padding:8px 12px;text-align:center;color:#6b7280;font-weight:600;">#</th>
                            <th style="padding:8px 12px;text-align:right;color:#6b7280;font-weight:600;">نام درس</th>
                            <th style="padding:8px 12px;text-align:center;color:#6b7280;font-weight:600;">نوع</th>
                            <th style="padding:8px 12px;text-align:center;color:#6b7280;font-weight:600;">جلسات</th>
                            <th style="padding:8px 12px;text-align:center;color:#6b7280;font-weight:600;">دانشجویان</th>
                            <th style="padding:8px 12px;text-align:center;color:#6b7280;font-weight:600;">مبلغ واحد</th>
                            <th style="padding:8px 12px;text-align:left;color:#6b7280;font-weight:600;">مبلغ کل</th>
                            <th style="padding:8px 12px;text-align:left;color:#6b7280;font-weight:600;">مالیات</th>
                            <th style="padding:8px 12px;text-align:left;color:#6b7280;font-weight:600;">بیمه</th>
                            <th style="padding:8px 12px;text-align:left;color:#059669;font-weight:700;">مبلغ نهایی</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; foreach ($courses as $course): ?>
                        <tr style="border-bottom:1px solid #f3f4f6;">
                            <td style="padding:6px 10px;text-align:center;"><?= $i++ ?></td>
                            <td style="padding:6px 10px;"><?= htmlspecialchars($course['course_name']) ?></td>
                            <td style="padding:6px 10px;text-align:center;">
                                <span style="background:#dbeafe;color:#1e40af;padding:2px 10px;border-radius:4px;font-size:11px;font-weight:500;">
                                    <?= getCourseTypeName($course['course_type']) ?>
                                </span>
                            </td>
                            <td style="padding:6px 10px;text-align:center;"><?= $course['sessions'] ?></td>
                            <td style="padding:6px 10px;text-align:center;"><?= $course['students'] ?></td>
                            <td style="padding:6px 10px;text-align:center;">
                                <?= formatPrice($course['unit_price']) ?> (<?= $course['unit_label'] ?>)
                            </td>
                            <td style="padding:6px 10px;text-align:left;font-weight:600;color:#1f2937;"><?= formatPrice($course['total']) ?></td>
                            <td style="padding:6px 10px;text-align:left;color:#dc2626;"><?= formatPrice($course['tax']) ?></td>
                            <td style="padding:6px 10px;text-align:left;color:#d97706;"><?= formatPrice($course['insurance']) ?></td>
                            <td style="padding:6px 10px;text-align:left;font-weight:700;color:#059669;"><?= formatPrice($course['net']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background:#f8fafc;border-top:2px solid #e5e7eb;font-weight:700;">
                            <td colspan="6" style="padding:8px 12px;text-align:left;color:#1f2937;">جمع ترم</td>
                            <td style="padding:8px 12px;text-align:left;color:#355C9C;"><?= formatPrice($termTotal) ?></td>
                            <td style="padding:8px 12px;text-align:left;color:#dc2626;"><?= formatPrice($termTax) ?></td>
                            <td style="padding:8px 12px;text-align:left;color:#d97706;"><?= formatPrice($termInsurance) ?></td>
                            <td style="padding:8px 12px;text-align:left;font-size:15px;color:#059669;"><?= formatPrice($termNet) ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>

<!-- ============================================================
     جمع کل همه ترم‌ها
     ============================================================ -->
<?php if (count($termData) > 1): ?>
<div class="card" style="padding:16px 20px;background:linear-gradient(135deg, #1a237e, #283593);color:white;border-radius:12px;margin-top:8px;">
    <div style="display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;">
        <span style="font-weight:700;font-size:17px;">
            <i class="fas fa-calculator"></i> جمع کل همه ترم‌ها
        </span>
        <div style="display:flex;flex-wrap:wrap;gap:16px;align-items:center;font-size:14px;">
            <span>حق التدریس: <strong style="color:#93c5fd;"><?= formatPrice($grandTotalAmount) ?></strong></span>
            <span>مالیات: <strong style="color:#fca5a5;"><?= formatPrice($grandTotalTax) ?></strong></span>
            <span>بیمه: <strong style="color:#fcd34d;"><?= formatPrice($grandTotalInsurance) ?></strong></span>
            <span style="font-size:18px;font-weight:800;">قابل پرداخت: <strong style="color:#6ee7b7;"><?= formatPrice($grandTotalNet) ?></strong></span>
        </div>
    </div>
</div>
<?php endif; ?>

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

<?php elseif ($teacher_id > 0 && empty($teacherTerms)): ?>

<div class="card" style="text-align:center;padding:60px 20px;background:#fff;border-radius:12px;border:1px solid #e5e7eb;">
    <i class="fas fa-calendar-alt" style="font-size:48px;color:#9ca3af;display:block;margin-bottom:16px;opacity:0.3;"></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>

<?php else: ?>

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

<?php endif; ?>

<!-- ============================================================
     اسکریپت چاپ ترم
     ============================================================ -->
<script>
function printTerm(termId) {
    const url = 'export-payment-pdf.php?teacher_id=<?= $teacher_id ?>&term_id=' + termId + '&print=1';
    window.open(url, '_blank');
}
</script>

<style>
@media print {
    .btn, .card .btn, .no-print, .filter-section { display: none !important; }
    .card { box-shadow: none !important; border: 1px solid #ddd !important; }
    body { background: white !important; }
    .stat-card { background: #f8f9fa !important; border: 1px solid #ddd !important; }
    .footer-bar, .top-header, .sidebar, .sidebar-overlay { display: none !important; }
    .main-content { margin: 0 !important; padding: 10px !important; }
}
.search-item:hover {
    background: #e8eaf6 !important;
}
.form-control:focus {
    border-color: #355C9C !important;
    box-shadow: 0 0 0 3px rgba(53, 92, 156, 0.1) !important;
    outline: none;
}
</style>