<?php
/**
 * ============================================================================
 * ajax/get-current-price.php - Get Current Average Price for Product
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

// Get product from request
$product = $_GET['product'] ?? '';

if (empty($product)) {
    echo json_encode([
        'success' => false,
        'message' => 'Product type is required'
    ]);
    exit;
}

try {
    // Get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    // Get average price for the last 7 days
    $sql = "SELECT 
                AVG(price) as avg_price,
                MIN(price) as min_price,
                MAX(price) as max_price,
                COUNT(*) as price_count,
                MAX(price_date) as last_updated
            FROM market_prices
            WHERE product_type = ?
            AND price_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$product]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result && $result['price_count'] > 0) {
        echo json_encode([
            'success' => true,
            'data' => [
                'avg_price' => round($result['avg_price'], 2),
                'min_price' => round($result['min_price'], 2),
                'max_price' => round($result['max_price'], 2),
                'price_count' => intval($result['price_count']),
                'last_updated' => $result['last_updated']
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No recent price data available for this product'
        ]);
    }
    
} catch (PDOException $e) {
    error_log("Error fetching current price: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?>