<?php
/**
 * SMM Paket Satış Scripti - Makbuz Görüntüleme/İndirme
 * Kupon/İndirim ve KDV Desteği ile
 * @version 1.2.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

$orderId = (int)($_GET['id'] ?? 0);
$action = $_GET['action'] ?? 'view'; // view veya pdf

if ($orderId <= 0) {
    setFlash('error', 'Geçersiz sipariş.');
    redirect(SITE_URL . '/admin/siparisler.php');
    exit;
}

// Siparişi çek
$stmt = $db->prepare("
    SELECT o.*, p.name as package_name, p.quantity as package_quantity, p.price as original_price,
           c.name as category_name, c.icon as category_icon, c.color as category_color
    FROM orders o
    JOIN packages p ON o.package_id = p.id
    JOIN categories c ON p.category_id = c.id
    WHERE o.id = ?
");
$stmt->execute([$orderId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    setFlash('error', 'Sipariş bulunamadı.');
    redirect(SITE_URL . '/admin/siparisler.php');
    exit;
}

// Makbuz numarası yoksa oluştur
if (empty($order['invoice_number'])) {
    $invoiceNumber = 'MKB' . date('Ymd') . strtoupper(substr(uniqid(), -6));
    $db->prepare("UPDATE orders SET invoice_number = ?, completed_at = COALESCE(completed_at, NOW()) WHERE id = ?")
       ->execute([$invoiceNumber, $orderId]);
    $order['invoice_number'] = $invoiceNumber;
    if (empty($order['completed_at'])) {
        $order['completed_at'] = date('Y-m-d H:i:s');
    }
}

// KDV hesaplama
$kdvRate = floatval($order['kdv_rate'] ?? 0);
$kdvAmount = floatval($order['kdv_amount'] ?? 0);
$hasKdv = $kdvAmount > 0;

// İndirim hesaplama
$discountAmount = floatval($order['discount_amount'] ?? 0);
$couponCode = $order['coupon_code'] ?? null;
$hasDiscount = $discountAmount > 0;

// Fiyat hesaplamaları
$basePrice = floatval($order['original_price']); // Paket fiyatı
$subtotalWithKdv = $basePrice + $kdvAmount; // KDV dahil ara toplam
$finalAmount = floatval($order['amount']); // Ödenen tutar

// Site ayarları
$siteName = defined('SITE_NAME') ? SITE_NAME : 'SMM Panel';
$siteUrl = SITE_URL;

// PDF indirme
if ($action === 'pdf') {
    // HTML to PDF - Basit yöntem (tarayıcı print)
    header('Content-Type: text/html; charset=utf-8');
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Makbuz #<?php echo clean($order['invoice_number']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #0f172a;
            color: #f8fafc;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .actions {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
        }
        
        .btn-back {
            background: rgba(255,255,255,0.1);
            color: #fff;
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.15);
        }
        
        .btn-print {
            background: #3b82f6;
            color: #fff;
        }
        
        .btn-print:hover {
            background: #2563eb;
        }
        
        .btn-pdf {
            background: #10b981;
            color: #fff;
        }
        
        .btn-pdf:hover {
            background: #059669;
        }
        
        /* Makbuz */
        .invoice {
            background: #fff;
            color: #1e293b;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
        }
        
        .invoice-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            padding: 40px;
            text-align: center;
        }
        
        .invoice-logo {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .invoice-title {
            font-size: 14px;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        
        .invoice-body {
            padding: 40px;
        }
        
        .invoice-info {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
            margin-bottom: 40px;
        }
        
        .info-block h4 {
            font-size: 11px;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 12px;
            font-weight: 600;
        }
        
        .info-block p {
            font-size: 14px;
            line-height: 1.8;
            color: #334155;
        }
        
        .info-block strong {
            color: #0f172a;
            font-weight: 600;
        }
        
        .invoice-number-box {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border: 2px solid #0ea5e9;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            margin-bottom: 40px;
        }
        
        .invoice-number-label {
            font-size: 11px;
            color: #0369a1;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 8px;
        }
        
        .invoice-number-value {
            font-size: 24px;
            font-weight: 700;
            color: #0c4a6e;
            font-family: 'Courier New', monospace;
            letter-spacing: 2px;
        }
        
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        
        .invoice-table th {
            background: #f8fafc;
            padding: 14px 16px;
            text-align: left;
            font-size: 11px;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .invoice-table td {
            padding: 16px;
            border-bottom: 1px solid #f1f5f9;
            font-size: 14px;
            color: #334155;
        }
        
        .invoice-table tr:last-child td {
            border-bottom: none;
        }
        
        .invoice-table .product-name {
            font-weight: 600;
            color: #0f172a;
        }
        
        .invoice-table .product-category {
            font-size: 12px;
            color: #64748b;
            margin-top: 4px;
        }
        
        .invoice-totals {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            font-size: 14px;
            color: #475569;
        }
        
        .total-row.kdv {
            color: #d97706;
        }
        
        .total-row.kdv .label {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .total-row.kdv .kdv-badge {
            background: #fef3c7;
            color: #92400e;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .total-row.subtotal {
            border-top: 1px dashed #e2e8f0;
            margin-top: 5px;
            padding-top: 15px;
            font-weight: 600;
            color: #334155;
        }
        
        .total-row.discount {
            color: #059669;
        }
        
        .total-row.discount .label {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .total-row.discount .coupon-badge {
            background: #dcfce7;
            color: #166534;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .total-row.grand {
            border-top: 2px solid #e2e8f0;
            margin-top: 10px;
            padding-top: 20px;
            font-size: 18px;
            font-weight: 700;
            color: #0f172a;
        }
        
        .total-row.grand .amount {
            color: #059669;
        }
        
        .invoice-status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 30px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .status-completed {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-cancelled {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .invoice-footer {
            background: #f8fafc;
            padding: 30px 40px;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }
        
        .footer-text {
            font-size: 13px;
            color: #64748b;
            line-height: 1.8;
        }
        
        .footer-text strong {
            color: #334155;
        }
        
        .qr-section {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px dashed #cbd5e1;
        }
        
        .qr-code {
            width: 80px;
            height: 80px;
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            color: #94a3b8;
        }
        
        .qr-text {
            font-size: 12px;
            color: #64748b;
            text-align: left;
        }
        
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 100px;
            font-weight: 700;
            color: rgba(0,0,0,0.03);
            pointer-events: none;
            white-space: nowrap;
        }
        
        .invoice-body {
            position: relative;
        }
        
        /* Kupon Bilgi Kutusu */
        .coupon-info-box {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 2px solid #22c55e;
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .coupon-info-box i {
            font-size: 24px;
            color: #16a34a;
        }
        
        .coupon-info-box .coupon-details {
            flex: 1;
        }
        
        .coupon-info-box .coupon-code {
            font-family: 'Courier New', monospace;
            font-size: 16px;
            font-weight: 700;
            color: #166534;
            letter-spacing: 1px;
        }
        
        .coupon-info-box .coupon-savings {
            font-size: 13px;
            color: #15803d;
            margin-top: 2px;
        }
        
        /* KDV Bilgi Kutusu */
        .kdv-info-box {
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
            border: 2px solid #f59e0b;
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .kdv-info-box i {
            font-size: 24px;
            color: #d97706;
        }
        
        .kdv-info-box .kdv-details {
            flex: 1;
        }
        
        .kdv-info-box .kdv-rate {
            font-size: 16px;
            font-weight: 700;
            color: #92400e;
        }
        
        .kdv-info-box .kdv-amount {
            font-size: 13px;
            color: #b45309;
            margin-top: 2px;
        }
        
        /* Print Styles */
        @media print {
            body {
                background: #fff;
                padding: 0;
            }
            
            .actions {
                display: none !important;
            }
            
            .invoice {
                box-shadow: none;
                border-radius: 0;
            }
            
            .container {
                max-width: 100%;
            }
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .invoice-info {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .invoice-header {
                padding: 30px 20px;
            }
            
            .invoice-body {
                padding: 20px;
            }
            
            .invoice-footer {
                padding: 20px;
            }
            
            .invoice-table th,
            .invoice-table td {
                padding: 12px 10px;
                font-size: 12px;
            }
            
            .invoice-number-value {
                font-size: 18px;
            }
            
            .qr-section {
                flex-direction: column;
                text-align: center;
            }
            
            .qr-text {
                text-align: center;
            }
            
            .coupon-info-box,
            .kdv-info-box {
                flex-direction: column;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Actions -->
        <div class="actions">
            <a href="<?php echo SITE_URL; ?>/admin/siparisler.php" class="btn btn-back">
                <i class="fas fa-arrow-left"></i> Siparişlere Dön
            </a>
            <button onclick="window.print()" class="btn btn-print">
                <i class="fas fa-print"></i> Yazdır
            </button>
            <button onclick="downloadPDF()" class="btn btn-pdf">
                <i class="fas fa-file-pdf"></i> PDF İndir
            </button>
        </div>
        
        <!-- Invoice -->
        <div class="invoice" id="invoice">
            <div class="invoice-header">
                <div class="invoice-logo">
                    <i class="fas fa-bolt"></i> <?php echo clean($siteName); ?>
                </div>
                <div class="invoice-title">Sipariş Makbuzu</div>
            </div>
            
            <div class="invoice-body">
                <div class="watermark"><?php echo $order['status'] === 'completed' ? 'TAMAMLANDI' : ($order['status'] === 'cancelled' ? 'İPTAL' : ''); ?></div>
                
                <!-- Invoice Number -->
                <div class="invoice-number-box">
                    <div class="invoice-number-label">Makbuz Numarası</div>
                    <div class="invoice-number-value"><?php echo clean($order['invoice_number']); ?></div>
                </div>
                
                <!-- KDV Bilgisi (Eğer varsa) -->
                <?php if ($hasKdv): ?>
                <div class="kdv-info-box">
                    <i class="fas fa-percent"></i>
                    <div class="kdv-details">
                        <div class="kdv-rate">KDV Oranı: %<?php echo $kdvRate; ?></div>
                        <div class="kdv-amount">
                            <i class="fas fa-plus-circle"></i> 
                            <?php echo formatMoney($kdvAmount); ?> KDV eklendi
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Kupon Bilgisi (Eğer kullanılmışsa) -->
                <?php if ($hasDiscount && $couponCode): ?>
                <div class="coupon-info-box">
                    <i class="fas fa-ticket-alt"></i>
                    <div class="coupon-details">
                        <div class="coupon-code"><?php echo clean($couponCode); ?></div>
                        <div class="coupon-savings">
                            <i class="fas fa-check-circle"></i> 
                            <?php echo formatMoney($discountAmount); ?> indirim uygulandı
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Info -->
                <div class="invoice-info">
                    <div class="info-block">
                        <h4><i class="fas fa-user"></i> Müşteri Bilgileri</h4>
                        <p>
                            <strong><?php echo clean($order['customer_name']); ?></strong><br>
                            <?php echo clean($order['customer_email']); ?><br>
                            <?php if (!empty($order['customer_phone'])): ?>
                            <?php echo clean($order['customer_phone']); ?><br>
                            <?php endif; ?>
                        </p>
                    </div>
                    <div class="info-block" style="text-align: right;">
                        <h4><i class="fas fa-file-invoice"></i> Makbuz Detayları</h4>
                        <p>
                            <strong>Sipariş No:</strong> <?php echo clean($order['order_number']); ?><br>
                            <strong>Sipariş Tarihi:</strong> <?php echo date('d.m.Y H:i', strtotime($order['created_at'])); ?><br>
                            <?php if (!empty($order['completed_at'])): ?>
                            <strong>Tamamlanma:</strong> <?php echo date('d.m.Y H:i', strtotime($order['completed_at'])); ?><br>
                            <?php endif; ?>
                            <strong>Durum:</strong> 
                            <?php
                            $statusLabels = [
                                'pending' => 'Bekliyor',
                                'paid' => 'Ödendi',
                                'processing' => 'İşleniyor',
                                'completed' => 'Tamamlandı',
                                'cancelled' => 'İptal Edildi',
                                'refunded' => 'İade Edildi'
                            ];
                            echo $statusLabels[$order['status']] ?? $order['status'];
                            ?>
                        </p>
                    </div>
                </div>
                
                <!-- Table -->
                <table class="invoice-table">
                    <thead>
                        <tr>
                            <th style="width: 50%">Hizmet</th>
                            <th style="text-align: center;">Miktar</th>
                            <th style="text-align: right;">Tutar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <div class="product-name"><?php echo clean($order['package_name']); ?></div>
                                <div class="product-category"><?php echo clean($order['category_name']); ?></div>
                            </td>
                            <td style="text-align: center;">
                                <?php echo number_format($order['package_quantity'] ?? 1, 0, ',', '.'); ?>
                            </td>
                            <td style="text-align: right; font-weight: 600;">
                                <?php echo formatMoney($basePrice); ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- Totals -->
                <div class="invoice-totals">
                    <div class="total-row">
                        <span>Paket Fiyatı</span>
                        <span><?php echo formatMoney($basePrice); ?></span>
                    </div>
                    
                    <?php if ($hasKdv): ?>
                    <div class="total-row kdv">
                        <span class="label">
                            <i class="fas fa-percent"></i> 
                            KDV
                            <span class="kdv-badge">%<?php echo $kdvRate; ?></span>
                        </span>
                        <span>+<?php echo formatMoney($kdvAmount); ?></span>
                    </div>
                    
                    <div class="total-row subtotal">
                        <span>Ara Toplam</span>
                        <span><?php echo formatMoney($subtotalWithKdv); ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($hasDiscount): ?>
                    <div class="total-row discount">
                        <span class="label">
                            <i class="fas fa-tag"></i> 
                            Kupon İndirimi
                            <?php if ($couponCode): ?>
                            <span class="coupon-badge"><?php echo clean($couponCode); ?></span>
                            <?php endif; ?>
                        </span>
                        <span>-<?php echo formatMoney($discountAmount); ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <div class="total-row grand">
                        <span>Genel Toplam</span>
                        <span class="amount"><?php echo formatMoney($finalAmount); ?></span>
                    </div>
                </div>
                
                <!-- Status Badge -->
                <div style="text-align: center; margin-bottom: 20px;">
                    <?php
                    $statusClass = 'status-pending';
                    if ($order['status'] === 'completed') $statusClass = 'status-completed';
                    elseif (in_array($order['status'], ['cancelled', 'refunded'])) $statusClass = 'status-cancelled';
                    ?>
                    <span class="invoice-status <?php echo $statusClass; ?>">
                        <i class="fas fa-<?php echo $order['status'] === 'completed' ? 'check-circle' : ($order['status'] === 'cancelled' ? 'times-circle' : 'clock'); ?>"></i>
                        <?php echo $statusLabels[$order['status']] ?? $order['status']; ?>
                    </span>
                </div>
                
                <!-- Social Media Link -->
                <?php if (!empty($order['social_media_link'])): ?>
                <div style="background: #f1f5f9; border-radius: 8px; padding: 15px; margin-bottom: 20px;">
                    <div style="font-size: 11px; color: #64748b; text-transform: uppercase; margin-bottom: 5px;">
                        <i class="fas fa-link"></i> Hizmet Uygulanan Link
                    </div>
                    <div style="font-size: 13px; color: #334155; word-break: break-all;">
                        <?php echo clean($order['social_media_link']); ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="invoice-footer">
                <p class="footer-text">
                    Bu makbuz <strong><?php echo clean($siteName); ?></strong> tarafından otomatik olarak oluşturulmuştur.<br>
                    Sorularınız için: <strong><?php echo $siteUrl; ?></strong>
                </p>
                
                <div class="qr-section">
                    <div class="qr-code">
                        <i class="fas fa-qrcode" style="font-size: 40px;"></i>
                    </div>
                    <div class="qr-text">
                        <strong>Doğrulama Kodu</strong><br>
                        <?php echo clean($order['invoice_number']); ?><br>
                        <small><?php echo date('d.m.Y H:i'); ?></small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    function downloadPDF() {
        const element = document.getElementById('invoice');
        const opt = {
            margin: 10,
            filename: 'Makbuz_<?php echo $order['invoice_number']; ?>.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2, useCORS: true },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };
        
        // Butonları geçici olarak gizle
        document.querySelector('.actions').style.display = 'none';
        
        html2pdf().set(opt).from(element).save().then(function() {
            document.querySelector('.actions').style.display = 'flex';
        });
    }
    </script>
</body>
</html>
<?php exit; ?>