<?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()) {
        // 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 with product details
        $itemsStmt = $conn->prepare("
            SELECT 
                ii.*, 
                p.name as product_name, 
                p.sell_price as product_price,
                p.images as product_images,
                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['product_images'] = json_decode($item['product_images'], true) ?: [];
            $item['item_total'] = $item['quantity'] * $item['price'];
            $items[] = $item;
        }
        
        $invoice['customer'] = $customer;
        $invoice['items'] = $items;
        
        sendResponse(true, 'Invoice details retrieved successfully', $invoice);
    } else {
        sendResponse(false, 'Invoice not found', null, 404);
    }
    
    $stmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Failed to get invoice details: ' . $e->getMessage(), null, 500);
}
?>
