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

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

try {
    $user = validateToken($conn);
    
    $product_id = intval($_GET['product_id'] ?? 0);
    
    if (empty($product_id)) {
        sendResponse(false, 'Product ID is required', null, 400);
    }
    
    // Get product details
    $stmt = $conn->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($product = $result->fetch_assoc()) {
        // Decode images JSON
        $product['images'] = json_decode($product['images'], true) ?: [];
        
        // Get product statistics
        $statsStmt = $conn->prepare("
            SELECT 
                COUNT(*) as total_orders,
                SUM(quantity) as total_sold,
                AVG(price) as avg_selling_price
            FROM invoice_items 
            WHERE product_id = ?
        ");
        $statsStmt->bind_param("i", $product_id);
        $statsStmt->execute();
        $stats = $statsStmt->get_result()->fetch_assoc();
        
        $product['statistics'] = $stats;
        
        sendResponse(true, 'Product details retrieved successfully', $product);
    } else {
        sendResponse(false, 'Product not found', null, 404);
    }
    
    $stmt->close();
} catch (Exception $e) {
    sendResponse(false, 'Failed to get product details: ' . $e->getMessage(), null, 500);
}
?>
