<?php
require 'db.php';
require 'helpers.php';
require_committee();

$id = $_GET['id'] ?? 0;
$type = $_GET['type'] ?? '';

if (empty($id) || empty($type)) {
    die('Invalid request');
}

// Get detailed data based on type
$receipt_data = [];
$title = '';

switch($type) {
    case 'registration':
        $stmt = $mysqli1->prepare("
            SELECT r.*, s.student_name, s.student_id, sem.name as semester_name 
            FROM registrations r 
            LEFT JOIN students s ON r.student_id = s.student_id 
            LEFT JOIN semesters sem ON r.semester_id = sem.id 
            WHERE r.id = ?
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $receipt_data = $stmt->get_result()->fetch_assoc();
        $title = 'إيصال تسجيل';
        break;
        
    case 'payment':
        $stmt = $mysqli1->prepare("
            SELECT p.*, s.student_name, s.student_id, ft.name as fee_type_name, sem.name as semester_name 
            FROM payments p 
            LEFT JOIN students s ON p.student_id = s.student_id 
            LEFT JOIN fee_types ft ON p.fee_type_id = ft.id 
            LEFT JOIN semesters sem ON p.semester_id = sem.id 
            WHERE p.id = ?
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $receipt_data = $stmt->get_result()->fetch_assoc();
        $title = 'إيصال دفع';
        break;
        
    case 'other_fee':
        $stmt = $mysqli1->prepare("
            SELECT of.*, ft.name as fee_type_name 
            FROM other_fees of 
            LEFT JOIN fee_types ft ON of.fee_type_id = ft.id 
            WHERE of.id = ?
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $receipt_data = $stmt->get_result()->fetch_assoc();
        $title = 'إيصال رسوم أخرى';
        break;
        
    case 'other_payment':
        $stmt = $mysqli1->prepare("
            SELECT op.*, ft.name as fee_type_name, b.name as bank_name 
            FROM other_payments op 
            LEFT JOIN fee_types ft ON op.fee_type_id = ft.id 
            LEFT JOIN banks b ON op.bank_id = b.id 
            WHERE op.id = ?
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $receipt_data = $stmt->get_result()->fetch_assoc();
        $title = 'إيصال دفع رسوم أخرى';
        break;
}

// Generate QR code data
$reference_number = $receipt_data['payment_reference'] ?? $receipt_data['reference'] ?? $id;
$amount = $receipt_data['payment_amount'] ?? $receipt_data['amount'] ?? 0;
$student_name = $receipt_data['student_name'] ?? '';
$student_id = $receipt_data['student_id'] ?? '';

$qr_data = "Tanoub College\n";
$qr_data .= "Receipt: " . $reference_number . "\n";
$qr_data .= "Amount: " . number_format($amount) . " SDG\n";
$qr_data .= "Date: " . date('Y-m-d H:i:s');

// Generate QR code using a reliable service
$qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($qr_data);

// Alternative QR code using QuickChart
$qr_url_alt = "https://quickchart.io/qr?text=" . urlencode($qr_data) . "&size=150";

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title><?= e($title) ?></title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Cairo', Arial, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .receipt-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            max-width: 800px;
            width: 100%;
            position: relative;
        }
        
        .receipt-header {
            background: white;
            color: #1F3A2E;
            padding: 30px;
            text-align: center;
            position: relative;
            border-bottom: 3px solid #1F3A2E;
        }
        
        .banner-image {
            max-width: 100%;
            height: 120px;
            object-fit: contain;
            margin-bottom: 15px;
            border-radius: 10px;
        }
        
        .college-name {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 10px;
            color: #1F3A2E;
        }
        
        .receipt-title {
            font-size: 32px;
            font-weight: 800;
            margin: 20px 0;
            color: #1F3A2E;
            background: linear-gradient(135deg, #FFD700, #FFA500);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .receipt-number {
            background: linear-gradient(135deg, #1F3A2E, #3E6B54);
            color: white;
            padding: 12px 25px;
            border-radius: 50px;
            font-size: 18px;
            margin: 15px 0;
            display: inline-block;
            box-shadow: 0 4px 15px rgba(31, 58, 46, 0.3);
        }
        
        .receipt-body {
            padding: 40px;
        }
        
        .receipt-details {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            border: 2px dashed #dee2e6;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            font-weight: 600;
            color: #495057;
            font-size: 16px;
        }
        
        .detail-value {
            font-weight: 700;
            color: #1F3A2E;
            font-size: 16px;
            text-align: left;
        }
        
        .amount-highlight {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 20px 25px;
            border-radius: 15px;
            font-size: 26px;
            font-weight: 800;
            text-align: center;
            margin: 25px 0;
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
            border: 3px solid #fff;
        }
        
        .qr-section {
            text-align: center;
            padding: 25px;
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-radius: 15px;
            margin: 30px 0;
            border: 2px solid #dee2e6;
        }
        
        .qr-code {
            width: 160px;
            height: 160px;
            margin: 0 auto 15px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 8px 20px rgba(0,0,0,0.1);
            border: 3px solid #1F3A2E;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .qr-code img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        
        .qr-placeholder {
            text-align: center;
            color: #6c757d;
            font-size: 14px;
        }
        
        .receipt-footer {
            background: linear-gradient(135deg, #1F3A2E, #2d4f3e);
            color: white;
            padding: 30px;
            text-align: center;
            border-top: 5px solid #FFD700;
        }
        
        .footer-text {
            margin-bottom: 15px;
            font-size: 16px;
            opacity: 0.9;
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
        }
        
        .btn {
            padding: 14px 35px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        }
        
        .btn-print {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }
        
        .btn-close {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
        
        .stamp {
            position: absolute;
            top: 20px;
            left: 20px;
            background: linear-gradient(135deg, #FFD700, #FFA500);
            color: #1F3A2E;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 800;
            font-size: 16px;
            transform: rotate(-15deg);
            box-shadow: 0 6px 15px rgba(0,0,0,0.2);
            border: 3px solid #fff;
            z-index: 10;
        }
        
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 120px;
            font-weight: 900;
            color: rgba(31, 58, 46, 0.03);
            z-index: 0;
            white-space: nowrap;
            pointer-events: none;
        }
        
        @media print {
            body {
                background: white;
                padding: 0;
            }
            
            .receipt-container {
                box-shadow: none;
                border-radius: 0;
                max-width: none;
                margin: 0;
            }
            
            .no-print {
                display: none !important;
            }
            
            .action-buttons {
                display: none !important;
            }
            
            .watermark {
                display: none;
            }
        }
        
        @media (max-width: 768px) {
            .receipt-body {
                padding: 20px;
            }
            
            .detail-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
            
            .detail-value {
                text-align: right;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .receipt-title {
                font-size: 26px;
            }
            
            .college-name {
                font-size: 22px;
            }
        }
    </style>
</head>
<body>
    <div class="receipt-container">
        <div class="stamp no-print">مدفوع ✓</div>
        <div class="watermark no-print">كلية تانوب</div>
        
        <div class="receipt-header">
            <img src="img/222banar2.jpg" alt="كلية النهرين" class="banner-image" onerror="this.style.display='none'">
            <div class="college-name">كلية النهرين</div>
            <div class="receipt-title"><?= e($title) ?></div>
            <div class="receipt-number">
                رقم المرجع: <?= e($reference_number) ?>
            </div>
        </div>
        
        <div class="receipt-body">
            <div class="receipt-details">
                <?php if ($type === 'registration' || $type === 'payment'): ?>
                <div class="detail-row">
                    <span class="detail-label">اسم الطالب:</span>
                    <span class="detail-value"><?= e($receipt_data['student_name'] ?? '—') ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">رقم الطالب:</span>
                    <span class="detail-value"><?= e($receipt_data['student_id'] ?? '—') ?></span>
                </div>
                <?php endif; ?>
                
                <?php if ($type === 'registration' || $type === 'payment'): ?>
                <div class="detail-row">
                    <span class="detail-label">الفصل الدراسي:</span>
                    <span class="detail-value"><?= e($receipt_data['semester_name'] ?? '—') ?></span>
                </div>
                <?php endif; ?>
                
                <?php if ($type === 'payment' || $type === 'other_payment'): ?>
                <div class="detail-row">
                    <span class="detail-label">نوع الرسوم:</span>
                    <span class="detail-value"><?= e($receipt_data['fee_type_name'] ?? '—') ?></span>
                </div>
                <?php endif; ?>
                
                <div class="detail-row">
                    <span class="detail-label">رقم المعاملة:</span>
                    <span class="detail-value"><?= e($receipt_data['transaction_ref'] ?? '—') ?></span>
                </div>
                
                <div class="detail-row">
                    <span class="detail-label">تاريخ المعاملة:</span>
                    <span class="detail-value"><?= e($receipt_data['created_at'] ?? date('Y-m-d H:i:s')) ?></span>
                </div>
                
                <?php if ($type === 'other_payment' && isset($receipt_data['bank_name'])): ?>
                <div class="detail-row">
                    <span class="detail-label">البنك:</span>
                    <span class="detail-value"><?= e($receipt_data['bank_name']) ?></span>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="amount-highlight">
                المبلغ المدفوع: <?= number_format($amount) ?> SDG
            </div>
            
            <?php if (($receipt_data['discount'] ?? 0) > 0): ?>
            <div class="detail-row" style="background: #d1fae5; padding: 12px; border-radius: 10px; margin: 15px 0; border: 2px solid #a7f3d0;">
                <span class="detail-label">الخصم:</span>
                <span class="detail-value" style="color: #065f46; font-size: 18px;"><?= number_format($receipt_data['discount']) ?> SDG</span>
            </div>
            <?php endif; ?>
            
            <?php if (($receipt_data['stamp'] ?? 0) > 0): ?>
            <div class="detail-row" style="background: #dbeafe; padding: 12px; border-radius: 10px; margin: 15px 0; border: 2px solid #93c5fd;">
                <span class="detail-label">الدمغة:</span>
                <span class="detail-value" style="color: #1e40af; font-size: 18px;"><?= number_format($receipt_data['stamp']) ?> SDG</span>
            </div>
            <?php endif; ?>
            
            <div class="qr-section">
                <div class="qr-code">
                    <?php if (function_exists('curl_init')): ?>
                        <!-- Try to load QR code with error handling -->
                        <img src="<?= e($qr_url) ?>" alt="QR Code" onerror="this.onerror=null; this.src='<?= e($qr_url_alt) ?>';">
                    <?php else: ?>
                        <div class="qr-placeholder">
                            <div>QR Code</div>
                            <div style="font-size: 12px; margin-top: 5px;"><?= e($reference_number) ?></div>
                        </div>
                    <?php endif; ?>
                </div>
                <div style="color: #6c757d; font-size: 14px; margin-top: 10px;">
                    <i class="fas fa-qrcode"></i> مسح رمز الاستجابة السريعة للتحقق
                </div>
                <div style="color: #8b9dc3; font-size: 12px; margin-top: 5px;">
                    المرجع: <?= e($reference_number) ?>
                </div>
            </div>
        </div>
        
        <div class="receipt-footer">
            <div class="footer-text">
                <i class="fas fa-shield-alt"></i> شكراً لثقتكم بكلية النهرين
            </div>
            <div class="footer-text" style="font-size: 14px; opacity: 0.8;">
                هذا الإيصال يؤكد استلام المبلغ المذكور أعلاه<br>
                للاستفسار: info@tanoub.edu | +249 XXX XXX XXX
            </div>
            <div class="footer-text" style="font-size: 12px; opacity: 0.6; margin-top: 10px;">
                تم الإنشاء في: <?= date('Y-m-d H:i:s') ?>
            </div>
        </div>
        
        <div class="action-buttons no-print">
            <button class="btn btn-print" onclick="window.print()">
                <i class="fas fa-print"></i> طباعة الإيصال
            </button>
            <button class="btn btn-close" onclick="window.close()">
                <i class="fas fa-times"></i> إغلاق النافذة
            </button>
        </div>
    </div>

    <!-- Font Awesome for icons -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    
    <script>
        // Auto-print option (optional)
        window.addEventListener('load', function() {
            // Uncomment the line below if you want auto-print
            // window.print();
        });

        // QR code fallback
        document.addEventListener('DOMContentLoaded', function() {
            const qrImg = document.querySelector('.qr-code img');
            if (qrImg) {
                qrImg.addEventListener('error', function() {
                    // If both QR services fail, show placeholder
                    this.style.display = 'none';
                    const qrContainer = this.closest('.qr-code');
                    qrContainer.innerHTML = `
                        <div class="qr-placeholder">
                            <div style="font-size: 16px; font-weight: bold; margin-bottom: 5px;">QR Code</div>
                            <div style="font-size: 12px;">كلية تانوب</div>
                            <div style="font-size: 10px; margin-top: 5px;"><?= e($reference_number) ?></div>
                        </div>
                    `;
                });
            }
        });
    </script>
</body>
</html>