<?php

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/invoice_error.log');

// Create logs directory if it doesn't exist
if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

try {
    // Include database connection
    require_once __DIR__ . '/config/db.php';
    
    // Get POST data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('No input data received');
    }

    $orderId = $input['orderId'] ?? null;
    $paymentId = $input['paymentId'] ?? null;
    $razorpayOrderId = $input['razorpayOrderId'] ?? null;

    // Validate inputs
    if (!$orderId && !$razorpayOrderId) {
        throw new Exception('Order ID or Razorpay Order ID is required');
    }

    // Fetch order details from database
    $query = "SELECT o.*, u.email, u.first_name, u.last_name, u.phone 
              FROM orders o 
              LEFT JOIN users u ON o.user_id = u.id 
              WHERE (o.id = ? OR o.razorpay_order_id = ?)
              LIMIT 1";
    
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }

    $stmt->bind_param('ss', $orderId, $razorpayOrderId);
    if (!$stmt->execute()) {
        throw new Exception('Database execute error: ' . $stmt->error);
    }

    $orderResult = $stmt->get_result();
    if ($orderResult->num_rows === 0) {
        throw new Exception('Order not found');
    }

    $order = $orderResult->fetch_assoc();
    $stmt->close();

    // Fetch order items
    $itemsQuery = "SELECT oi.*, p.name, p.description 
                   FROM order_items oi 
                   LEFT JOIN products p ON oi.product_id = p.id 
                   WHERE oi.order_id = ?";
    
    $itemsStmt = $conn->prepare($itemsQuery);
    if (!$itemsStmt) {
        throw new Exception('Database prepare error for items: ' . $conn->error);
    }

    $itemsStmt->bind_param('s', $order['id']);
    if (!$itemsStmt->execute()) {
        throw new Exception('Database execute error for items: ' . $itemsStmt->error);
    }

    $itemsResult = $itemsStmt->get_result();
    $items = [];
    while ($item = $itemsResult->fetch_assoc()) {
        $items[] = $item;
    }
    $itemsStmt->close();

    // Generate invoice HTML
    $invoiceHtml = generateInvoiceHTML($order, $items);

    // Return response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Invoice generated successfully',
        'html' => $invoiceHtml,
        'orderId' => $order['id'],
        'amount' => $order['amount']
    ]);

} catch (Exception $e) {
    error_log('Invoice generation error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to generate invoice: ' . $e->getMessage(),
        'error' => $e->getMessage()
    ]);
}

function generateInvoiceHTML($order, $items) {
    $invoiceDate = date('d M Y', strtotime($order['created_at']));
    $dueDate = date('d M Y', strtotime($order['created_at'] . ' +7 days'));
    
    $itemsHtml = '';
    $subtotal = 0;
    
    foreach ($items as $item) {
        $itemTotal = $item['price'] * $item['quantity'];
        $subtotal += $itemTotal;
        $itemsHtml .= "
            <tr>
                <td>{$item['name']}</td>
                <td style='text-align: center;'>{$item['quantity']}</td>
                <td style='text-align: right;'>₹" . number_format($item['price'], 2) . "</td>
                <td style='text-align: right;'>₹" . number_format($itemTotal, 2) . "</td>
            </tr>
        ";
    }
    
    $gst = $subtotal * 0.18;
    $total = $subtotal + $gst;
    
    $shippingAddress = json_decode($order['shipping_address'], true) ?? [];
    $addressString = implode(', ', array_filter([
        $shippingAddress['address'] ?? '',
        $shippingAddress['city'] ?? '',
        $shippingAddress['state'] ?? '',
        $shippingAddress['pinCode'] ?? ''
    ]));

    $html = <<<HTML
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Invoice - {$order['id']}</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                color: #333;
                background: white;
            }
            .invoice-container {
                max-width: 900px;
                margin: 0 auto;
                padding: 40px;
                background: white;
            }
            .invoice-header {
                display: flex;
                justify-content: space-between;
                align-items: start;
                margin-bottom: 40px;
                border-bottom: 3px solid #8B6F47;
                padding-bottom: 20px;
            }
            .company-info h1 {
                color: #8B6F47;
                font-size: 28px;
                margin-bottom: 5px;
            }
            .company-info p {
                color: #666;
                font-size: 13px;
            }
            .invoice-title {
                text-align: right;
            }
            .invoice-title h2 {
                font-size: 24px;
                color: #333;
                margin-bottom: 10px;
            }
            .invoice-meta {
                font-size: 13px;
                color: #666;
                line-height: 1.6;
            }
            .invoice-meta span {
                display: inline-block;
                width: 120px;
                font-weight: 600;
            }
            .content {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 40px;
                margin-bottom: 40px;
            }
            .section h3 {
                font-size: 14px;
                font-weight: 700;
                text-transform: uppercase;
                color: #333;
                margin-bottom: 15px;
                border-bottom: 2px solid #8B6F47;
                padding-bottom: 8px;
            }
            .section p {
                font-size: 13px;
                line-height: 1.8;
                color: #555;
            }
            .items-table {
                width: 100%;
                margin-bottom: 30px;
                border-collapse: collapse;
            }
            .items-table thead {
                background: #f5f5f5;
                border-bottom: 2px solid #8B6F47;
            }
            .items-table th {
                padding: 12px;
                text-align: left;
                font-weight: 600;
                font-size: 13px;
                color: #333;
            }
            .items-table td {
                padding: 12px;
                font-size: 13px;
                border-bottom: 1px solid #eee;
            }
            .summary {
                text-align: right;
                margin: 30px 0;
            }
            .summary-row {
                display: flex;
                justify-content: flex-end;
                margin-bottom: 8px;
                font-size: 13px;
            }
            .summary-row span:first-child {
                width: 150px;
                text-align: right;
                padding-right: 20px;
            }
            .summary-row span:last-child {
                width: 100px;
                text-align: right;
                font-weight: 600;
            }
            .summary-row.total {
                font-size: 16px;
                color: #8B6F47;
                margin-top: 15px;
                padding-top: 15px;
                border-top: 2px solid #8B6F47;
            }
            .payment-info {
                margin-top: 30px;
                padding: 20px;
                background: #f9f9f9;
                border-radius: 5px;
                font-size: 13px;
            }
            .footer {
                margin-top: 40px;
                padding-top: 20px;
                border-top: 1px solid #ddd;
                text-align: center;
                font-size: 12px;
                color: #999;
            }
            @media print {
                body { background: white; }
                .invoice-container { padding: 0; }
            }
        </style>
    </head>
    <body>
        <div class="invoice-container">
            <div class="invoice-header">
                <div class="company-info">
                    <h1>🍫 Anshul Food Products</h1>
                    <p>Premium Chocolate & Confectionery</p>
                    <p>Email: info@anshulfood.com</p>
                    <p>Phone: +91-XXXXXXXXXX</p>
                </div>
                <div class="invoice-title">
                    <h2>INVOICE</h2>
                    <div class="invoice-meta">
                        <div><span>Invoice #:</span> {$order['id']}</div>
                        <div><span>Invoice Date:</span> {$invoiceDate}</div>
                        <div><span>Due Date:</span> {$dueDate}</div>
                        <div><span>Payment ID:</span> {$order['razorpay_payment_id']}</div>
                    </div>
                </div>
            </div>

            <div class="content">
                <div>
                    <section class="section">
                        <h3>Bill To</h3>
                        <p>
                            {$order['first_name']} {$order['last_name']}<br>
                            {$addressString}<br>
                            Email: {$order['email']}<br>
                            Phone: {$order['phone']}
                        </p>
                    </section>
                </div>
                <div>
                    <section class="section">
                        <h3>Payment Method</h3>
                        <p>
                            Method: Razorpay Payment Gateway<br>
                            Status: {$order['payment_status']}<br>
                            Amount: ₹" . number_format($order['amount'], 2) . "<br>
                        </p>
                    </section>
                </div>
            </div>

            <table class="items-table">
                <thead>
                    <tr>
                        <th>Product Description</th>
                        <th style="text-align: center;">Quantity</th>
                        <th style="text-align: right;">Unit Price</th>
                        <th style="text-align: right;">Total</th>
                    </tr>
                </thead>
                <tbody>
                    {$itemsHtml}
                </tbody>
            </table>

            <div class="summary">
                <div class="summary-row">
                    <span>Subtotal:</span>
                    <span>₹" . number_format($subtotal, 2) . "</span>
                </div>
                <div class="summary-row">
                    <span>GST (18%):</span>
                    <span>₹" . number_format($gst, 2) . "</span>
                </div>
                <div class="summary-row">
                    <span>Shipping:</span>
                    <span>₹0.00</span>
                </div>
                <div class="summary-row total">
                    <span>TOTAL:</span>
                    <span>₹" . number_format($total, 2) . "</span>
                </div>
            </div>

            <div class="payment-info">
                <strong>Thank you for your purchase!</strong><br>
                <p>This is an electronic invoice. Please keep it for your records. For any queries, please contact our support team.</p>
            </div>

            <div class="footer">
                <p>© 2024 Anshul Food Products. All rights reserved.</p>
                <p>Generated on: " . date('d M Y H:i:s') . "</p>
            </div>
        </div>
    </body>
    </html>
    HTML;

    return $html;
}
?>