<?php
require_once 'config.php';

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

if (!$order_id) {
    header('Location: index.php');
    exit;
}

// Get order details
$stmt = $pdo->prepare("
    SELECT o.*, c.full_name, c.phone, c.email, c.address, c.city, c.state, c.country
    FROM orders o
    JOIN customers c ON o.customer_id = c.id
    WHERE o.id = ?
");
$stmt->execute([$order_id]);
$order = $stmt->fetch();

if (!$order) {
    die("Order not found");
}

// Get order items
$stmt = $pdo->prepare("
    SELECT oi.*, e.name
    FROM order_items oi
    JOIN equipment e ON oi.equipment_id = e.id
    WHERE oi.order_id = ?
");
$stmt->execute([$order_id]);
$order_items = $stmt->fetchAll();

// Get bank details
$bank_details = $order['bank_account_details'] ? json_decode($order['bank_account_details'], true) : null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Invoice - EliteEquip</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        :root {
            --primary: #0f1535;
            --primary-dark: #0a0e27;
            --secondary: #ff6b35;
            --secondary-dark: #e55a2b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --text-dark: #1e293b;
            --text-gray: #64748b;
            --text-light: #94a3b8;
            --bg-light: #f8fafc;
            --white: #ffffff;
            --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.07);
            --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
            --shadow-xl: 0 20px 25px -5px rgba(0,0,0,0.1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            min-height: 100vh;
        }
        
        .invoice-wrapper {
            max-width: 900px;
            margin: 0 auto;
            animation: slideUp 0.5s ease;
        }
        
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .invoice {
            background: white;
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }
        
        /* Invoice Header */
        .invoice-header {
            background: linear-gradient(135deg, #0f1535 0%, #1a2352 100%);
            color: white;
            padding: 2rem;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .invoice-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 70%);
            animation: pulse 4s ease-in-out infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.5; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        
        .invoice-header .logo-icon {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, var(--secondary), #ff8c42);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            position: relative;
            z-index: 1;
        }
        
        .invoice-header .logo-icon i {
            font-size: 1.8rem;
        }
        
        .invoice-header h1 {
            font-size: 1.8rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
            position: relative;
            z-index: 1;
        }
        
        .invoice-header p {
            opacity: 0.8;
            font-size: 0.9rem;
            position: relative;
            z-index: 1;
        }
        
        /* Invoice Body */
        .invoice-body {
            padding: 2rem;
        }
        
        .invoice-title {
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #f1f5f9;
        }
        
        .invoice-title h2 {
            color: var(--secondary);
            font-size: 1.5rem;
            font-weight: 800;
            letter-spacing: 2px;
            margin-bottom: 0.5rem;
        }
        
        .invoice-title p {
            color: var(--text-gray);
            font-size: 0.85rem;
        }
        
        /* Info Grid */
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .info-box {
            background: var(--bg-light);
            padding: 1.25rem;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
        }
        
        .info-box h5 {
            font-size: 0.85rem;
            font-weight: 700;
            color: var(--text-gray);
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 1rem;
        }
        
        .info-box p {
            font-size: 0.9rem;
            line-height: 1.5;
            color: var(--text-dark);
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-pending {
            background: #fed7aa;
            color: #92400e;
        }
        
        .status-paid {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-failed {
            background: #fee2e2;
            color: #991b1b;
        }
        
       /* Invoice Table Container - Ensure everything fits */
.invoice-table-container {
    overflow-x: visible;
    margin: 1.5rem 0;
    border-radius: 16px;
    border: 1px solid #e2e8f0;
    background: white;
}

.invoice-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

.invoice-table th {
    background: #f8fafc;
    padding: 12px;
    text-align: left;
    font-weight: 600;
    font-size: 0.8rem;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid #e2e8f0;
}

.invoice-table th:first-child {
    width: 50%;
    border-radius: 16px 0 0 0;
}

.invoice-table th:nth-child(2) {
    width: 15%;
}

.invoice-table th:nth-child(3) {
    width: 17.5%;
}

.invoice-table th:last-child {
    width: 17.5%;
}

.invoice-table td {
    padding: 12px;
    border-bottom: 1px solid #e2e8f0;
    font-size: 0.85rem;
    word-break: break-word;
    white-space: normal;
}

.invoice-table td:first-child {
    word-break: break-word;
    white-space: normal;
}

.invoice-table td:nth-child(2),
.invoice-table td:nth-child(3),
.invoice-table td:nth-child(4) {
    white-space: nowrap;
}

.invoice-table tr:last-child td {
    border-bottom: none;
}

.total-row td {
    border-top: 1px solid #e2e8f0;
}

/* Mobile Responsive - Ensure table fits when downloading */
@media print {
    .invoice-table-container {
        overflow: visible !important;
        page-break-inside: avoid;
    }
    
    .invoice-table {
        width: 100%;
        table-layout: fixed;
    }
    
    .invoice-table td,
    .invoice-table th {
        word-break: break-word;
        white-space: normal;
    }
}

/* For screen sizes that need horizontal scroll */
@media (max-width: 600px) {
    .invoice-table-container {
        overflow-x: auto;
    }
    
    .invoice-table {
        min-width: 500px;
    }
    
    .invoice-table td,
    .invoice-table th {
        white-space: nowrap;
    }
    
    .invoice-table td:first-child {
        white-space: normal;
        min-width: 150px;
    }
}
        
        /* Bank Details */
        .bank-details {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            padding: 1.5rem;
            border-radius: 16px;
            margin: 1.5rem 0;
        }
        
        .bank-details h5 {
            font-size: 1rem;
            font-weight: 700;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .bank-details p {
            font-size: 0.85rem;
            line-height: 1.6;
        }
        
        .bank-details .reference {
            background: rgba(0,0,0,0.05);
            padding: 0.5rem;
            border-radius: 8px;
            margin-top: 0.5rem;
            font-family: monospace;
            font-size: 0.8rem;
        }
        
        /* Thank You Section */
        .thank-you {
            text-align: center;
            padding-top: 1.5rem;
            margin-top: 1.5rem;
            border-top: 1px solid #e2e8f0;
        }
        
        .thank-you p {
            color: var(--text-gray);
            font-size: 0.9rem;
        }
        
        /* Buttons */
        .btn-download {
            background: linear-gradient(135deg, var(--secondary), #ff8c42);
            color: white;
            border: none;
            padding: 12px 28px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 2rem;
            margin-right: 1rem;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-download:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(255,107,53,0.3);
        }
        
        .btn-home {
            background: var(--text-gray);
            color: white;
            border: none;
            padding: 12px 28px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 2rem;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-home:hover {
            background: #475569;
            color: white;
            transform: translateY(-2px);
        }
        
        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 9999;
            display: none;
            justify-content: center;
            align-items: center;
        }
        
        .loading-overlay.active {
            display: flex;
        }
        
        /* Print Styles */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            
            .no-print {
                display: none;
            }
            
            .invoice {
                box-shadow: none;
                border-radius: 0;
            }
            
            .invoice-header {
                background: #0f1535;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .bank-details {
                background: #fef3c7;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            body {
                padding: 12px;
            }
            
            .invoice-body {
                padding: 1.5rem;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
            
            .info-box {
                padding: 1rem;
            }
            
            .info-box p {
                font-size: 0.85rem;
            }
            
            .invoice-table th,
            .invoice-table td {
                padding: 0.75rem;
                font-size: 0.8rem;
            }
            
            .bank-details {
                padding: 1rem;
            }
            
            .bank-details p {
                font-size: 0.8rem;
                word-break: break-word;
            }
            
            .btn-download,
            .btn-home {
                padding: 10px 20px;
                font-size: 0.8rem;
                margin-top: 1rem;
            }
            
            .invoice-title h2 {
                font-size: 1.3rem;
            }
        }
        
        @media (max-width: 480px) {
            .invoice-header {
                padding: 1.5rem;
            }
            
            .invoice-header h1 {
                font-size: 1.4rem;
            }
            
            .invoice-body {
                padding: 1rem;
            }
            
            .invoice-table th,
            .invoice-table td {
                padding: 0.5rem;
                font-size: 0.7rem;
            }
            
            .info-box h5 {
                font-size: 0.75rem;
            }
            
            .info-box p {
                font-size: 0.75rem;
            }
            
            .bank-details h5 {
                font-size: 0.9rem;
            }
            
            .btn-download,
            .btn-home {
                padding: 8px 16px;
                font-size: 0.7rem;
                margin: 0.5rem 0;
            }
            
            .text-center.no-print {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 0.5rem;
            }
        }
    </style>
</head>
<body>

<div id="loadingOverlay" class="loading-overlay">
    <div class="spinner-border text-warning" style="width: 3rem; height: 3rem;"></div>
</div>

<div class="invoice-wrapper">
    <div id="invoiceContent" class="invoice">
        <div class="invoice-header">
            <div class="logo-icon">
                <i class="fas fa-microchip"></i>
            </div>
            <h1>EliteEquip</h1>
            <p>Premium Industrial Equipment Marketplace</p>
        </div>
        
        <div class="invoice-body">
            <div class="invoice-title">
                <h2>INVOICE</h2>
                <p><strong>#<?php echo htmlspecialchars($order['invoice_number']); ?></strong></p>
                <p><?php echo date('F j, Y', strtotime($order['order_date'])); ?></p>
            </div>
            
            <div class="info-grid">
                <div class="info-box">
                    <h5><i class="fas fa-user"></i> Bill To:</h5>
                    <p>
                        <strong><?php echo htmlspecialchars($order['full_name']); ?></strong><br>
                        <i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($order['phone']); ?><br>
                        <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($order['email']); ?><br>
                        <i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($order['address']); ?><br>
                        <?php echo htmlspecialchars($order['city'] . ', ' . $order['state'] . ', ' . $order['country']); ?>
                    </p>
                </div>
                <div class="info-box">
                    <h5><i class="fas fa-info-circle"></i> Order Details:</h5>
                    <p>
                        <strong>Order Status:</strong><br>
                        <span class="status-badge status-<?php echo $order['payment_status']; ?>">
                            <i class="fas <?php echo $order['payment_status'] == 'paid' ? 'fa-check-circle' : ($order['payment_status'] == 'pending' ? 'fa-clock' : 'fa-times-circle'); ?>"></i>
                            <?php echo strtoupper($order['payment_status']); ?>
                        </span>
                    </p>
                </div>
            </div>
            
           <div class="invoice-table-container">
    <table class="invoice-table">
        <thead>
            <tr>
                <th style="width: 50%;">Item Description</th>
                <th style="width: 15%;">Qty</th>
                <th style="width: 17.5%;">Unit Price</th>
                <th style="width: 17.5%;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($order_items as $item): ?>
            <tr>
                <td style="word-break: break-word; white-space: normal;">
                    <strong><?php echo htmlspecialchars($item['name']); ?></strong>
                </td>
                <td style="text-align: center;"><?php echo $item['quantity']; ?></td>
                <td>$<?php echo number_format($item['price_at_time'], 2); ?></td>
                <td>$<?php echo number_format($item['price_at_time'] * $item['quantity'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
            <tr class="total-row">
                <td colspan="3" style="text-align: right; padding: 12px;"><strong>Subtotal:</strong></td>
                <td style="padding: 12px;"><strong>$<?php echo number_format($order['total_amount'], 2); ?></strong></td>
            </tr>
            <tr class="total-row">
                <td colspan="3" style="text-align: right; padding: 8px;"><strong>Shipping:</strong></td>
                <td style="padding: 8px;"><strong>FREE</strong></td>
            </tr>
            <tr class="total-row" style="background: #f8fafc;">
                <td colspan="3" style="text-align: right; padding: 15px; font-size: 1rem; font-weight: 800;">
                    <strong>Total Amount:</strong>
                </td>
                <td style="padding: 15px; font-size: 1.2rem; font-weight: 800; color: var(--secondary);">
                    <strong>$<?php echo number_format($order['total_amount'], 2); ?></strong>
                </td>
            </tr>
        </tbody>
    </table>
</div>
            
            <?php if ($bank_details): ?>
            <div class="bank-details">
                <h5><i class="fas fa-university"></i> Payment Instructions</h5>
                <p>Please transfer the total amount to the following bank account:</p>
                <p>
                    <strong>Bank:</strong> <?php echo htmlspecialchars($bank_details['bank_name']); ?><br>
                    <strong>Account Name:</strong> <?php echo htmlspecialchars($bank_details['account_name']); ?><br>
                    <strong>Account Number:</strong> <?php echo htmlspecialchars($bank_details['account_number']); ?><br>
                    <?php if (!empty($bank_details['sort_code'])): ?>
                    <strong>Sort Code:</strong> <?php echo htmlspecialchars($bank_details['sort_code']); ?><br>
                    <?php endif; ?>
                    <?php if (!empty($bank_details['swift_code'])): ?>
                    <strong>SWIFT Code:</strong> <?php echo htmlspecialchars($bank_details['swift_code']); ?><br>
                    <?php endif; ?>
                    <?php if (!empty($bank_details['iban'])): ?>
                    <strong>IBAN:</strong> <?php echo htmlspecialchars($bank_details['iban']); ?>
                    <?php endif; ?>
                </p>
                <div class="reference">
                    <i class="fas fa-hashtag"></i> Reference: <?php echo $order['invoice_number']; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="thank-you">
                <p>Thank you for your business!<br>For any inquiries, please contact us at sales@eliteequip.com</p>
            </div>
        </div>
    </div>
    
    <div class="text-center no-print" style="margin-top: 20px;">
        <button class="btn-download" onclick="downloadInvoice()">
            <i class="fas fa-download"></i> Download as Image
        </button>
        <a href="index.php" class="btn-home">
            <i class="fas fa-home"></i> Return to Home
        </a>
    </div>
</div>

<script>
function downloadInvoice() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    const invoiceElement = document.getElementById('invoiceContent');
    
    loadingOverlay.classList.add('active');
    
    // Temporarily adjust table for better capture
    const container = document.querySelector('.invoice-table-container');
    const originalOverflow = container.style.overflow;
    container.style.overflow = 'visible';
    
    html2canvas(invoiceElement, {
        scale: 2.5,
        backgroundColor: '#ffffff',
        logging: false,
        useCORS: true,
        windowWidth: invoiceElement.scrollWidth,
        windowHeight: invoiceElement.scrollHeight,
        onclone: function(clonedDoc, element) {
            // Ensure table widths are preserved in clone
            const clonedTable = clonedDoc.querySelector('.invoice-table');
            if (clonedTable) {
                clonedTable.style.width = '100%';
                clonedTable.style.tableLayout = 'fixed';
            }
        }
    }).then(canvas => {
        const link = document.createElement('a');
        const invoiceNumber = '<?php echo $order['invoice_number']; ?>';
        link.download = `invoice_${invoiceNumber}.png`;
        link.href = canvas.toDataURL('image/png');
        link.click();
        container.style.overflow = originalOverflow;
        loadingOverlay.classList.remove('active');
    }).catch(error => {
        console.error('Error:', error);
        container.style.overflow = originalOverflow;
        loadingOverlay.classList.remove('active');
        alert('Error generating invoice. Please try again.');
    });
}
</script>
</body>
</html>