<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendResponse(false, 'Only GET method allowed', null, 405);
}

try {
    $user = validateToken($conn);
    
    $invoice_id = intval($_GET['invoice_id'] ?? 0);
    
    if (empty($invoice_id)) {
        sendResponse(false, 'Invoice ID is required', null, 400);
    }
    
    // Get invoice details
    $stmt = $conn->prepare("SELECT * FROM invoices WHERE id = ?");
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if (!$invoice = $result->fetch_assoc()) {
        sendResponse(false, 'Invoice not found', null, 404);
    }
    
    // Get customer details
    $customerTable = ($invoice['customer_type'] === 'temporary') ? 'customers' : 'permanentcustomer';
    $customerStmt = $conn->prepare("SELECT * FROM $customerTable WHERE id = ?");
    $customerStmt->bind_param("i", $invoice['customer_id']);
    $customerStmt->execute();
    $customer = $customerStmt->get_result()->fetch_assoc();
    
    // Get invoice items
    $itemsStmt = $conn->prepare("
        SELECT 
            ii.*, 
            p.name as product_name, 
            p.sell_price as product_price,
            p.distributor,
            p.hsn_code
        FROM invoice_items ii 
        LEFT JOIN products p ON ii.product_id = p.id 
        WHERE ii.invoice_id = ?
    ");
    $itemsStmt->bind_param("i", $invoice_id);
    $itemsStmt->execute();
    $itemsResult = $itemsStmt->get_result();
    
    $items = [];
    while ($item = $itemsResult->fetch_assoc()) {
        $item['item_total'] = $item['quantity'] * $item['price'];
        $items[] = $item;
    }
    
    // Generate PDF content (simplified version)
    $pdfContent = generateInvoicePDF($invoice, $customer, $items);
    
    // Save PDF file
    $pdfDir = __DIR__ . '/../../kumawat/uploads/invoices/';
    if (!is_dir($pdfDir)) {
        mkdir($pdfDir, 0777, true);
    }
    
    $filename = 'invoice_' . $invoice_id . '_' . date('Y-m-d') . '.pdf';
    $filepath = $pdfDir . $filename;
    
    file_put_contents($filepath, $pdfContent);
    
    $pdfUrl = 'uploads/invoices/' . $filename;
    
    sendResponse(true, 'PDF generated successfully', [
        'invoice_id' => $invoice_id,
        'pdf_url' => $pdfUrl,
        'filename' => $filename
    ]);
    
} catch (Exception $e) {
    sendResponse(false, 'Failed to generate PDF: ' . $e->getMessage(), null, 500);
}

function generateInvoicePDF($invoice, $customer, $items) {
    // This is a simplified PDF generation
    // In a real application, you would use a proper PDF library like TCPDF or FPDF
    
    $html = "
    <!DOCTYPE html>
    <html>
    <head>
        <title>Invoice #{$invoice['id']}</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            .header { text-align: center; margin-bottom: 30px; }
            .invoice-details { margin-bottom: 20px; }
            .customer-details { margin-bottom: 20px; }
            table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            .total { text-align: right; font-weight: bold; }
        </style>
    </head>
    <body>
        <div class='header'>
            <h1>Kumawat Computer</h1>
            <h2>Invoice #{$invoice['id']}</h2>
        </div>
        
        <div class='invoice-details'>
            <p><strong>Invoice Date:</strong> " . date('Y-m-d', strtotime($invoice['created_at'])) . "</p>
            <p><strong>Status:</strong> " . ucfirst($invoice['status']) . "</p>
        </div>
        
        <div class='customer-details'>
            <h3>Customer Details</h3>
            <p><strong>Name:</strong> {$customer['name']}</p>
            <p><strong>Type:</strong> " . ucfirst($invoice['customer_type']) . "</p>
        </div>
        
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>HSN Code</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>";
    
    foreach ($items as $item) {
        $html .= "
                <tr>
                    <td>{$item['product_name']}</td>
                    <td>{$item['hsn_code']}</td>
                    <td>{$item['quantity']}</td>
                    <td>₹{$item['price']}</td>
                    <td>₹{$item['item_total']}</td>
                </tr>";
    }
    
    $html .= "
            </tbody>
        </table>
        
        <div class='total'>
            <p><strong>Subtotal:</strong> ₹{$invoice['subtotal']}</p>
            <p><strong>Tax (18%):</strong> ₹{$invoice['tax_amount']}</p>
            <p><strong>Total Amount:</strong> ₹{$invoice['total_amount']}</p>
        </div>
        
        <div style='margin-top: 30px;'>
            <p>Thank you for your business!</p>
        </div>
    </body>
    </html>";
    
    return $html;
}
?>
