<?php
// File: api/price_updates/dashboard.php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

try {
    $pdo = Database::getInstance()->getConnection();
    $user_id = $_SESSION['user_id'] ?? null;
    
    if (!$user_id) {
        echo json_encode(['success' => false, 'message' => 'User not authenticated']);
        exit;
    }
    
    // Check if price_update_logs table exists
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'price_update_logs'")->fetch();
    
    if (!$tableCheck) {
        // Table doesn't exist, return empty data
        echo json_encode([
            'success' => true,
            'recent_updates' => [],
            'stats' => [
                'total_ingredients_updated' => 0,
                'total_recipes_affected' => 0,
                'last_update' => null
            ]
        ]);
        exit;
    }
    
    // Check table structure
    $columns = $pdo->query("SHOW COLUMNS FROM price_update_logs")->fetchAll(PDO::FETCH_COLUMN);
    $hasRequiredColumns = in_array('ingredient_id', $columns) && 
                         in_array('recipe_id', $columns) && 
                         in_array('old_price', $columns) && 
                         in_array('new_price', $columns);
    
    if (!$hasRequiredColumns) {
        echo json_encode([
            'success' => true,
            'recent_updates' => [],
            'stats' => [
                'total_ingredients_updated' => 0,
                'total_recipes_affected' => 0,
                'last_update' => null
            ]
        ]);
        exit;
    }
    
    // Get recent price updates with user-bound data
    $query = "
        SELECT 
            pul.*,
            i.name as ingredient_name,
            rc.recipe_name,
            DATE_FORMAT(pul.updated_at, '%Y-%m-%d %H:%i') as formatted_date
        FROM price_update_logs pul
        JOIN ingredients i ON pul.ingredient_id = i.id
        JOIN recipe_costings rc ON pul.recipe_id = rc.id
    ";
    
    // Check if recipe_costings has user_id or created_by column
    $recipeColumns = $pdo->query("SHOW COLUMNS FROM recipe_costings")->fetchAll(PDO::FETCH_COLUMN);
    
    if (in_array('user_id', $recipeColumns)) {
        $query .= " WHERE rc.user_id = ?";
    } elseif (in_array('created_by', $recipeColumns)) {
        $query .= " WHERE rc.created_by = ?";
    } else {
        // If no user column, fallback to showing all data (not ideal but works)
        $query .= " WHERE 1=1";
    }
    
    $query .= " ORDER BY pul.updated_at DESC LIMIT 10";
    
    if (in_array('user_id', $recipeColumns) || in_array('created_by', $recipeColumns)) {
        $stmt = $pdo->prepare($query);
        $stmt->execute([$user_id]);
    } else {
        $stmt = $pdo->query($query);
    }
    
    $recentUpdates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get price update statistics with user-bound data
    $statsQuery = "
        SELECT 
            COUNT(DISTINCT pul.ingredient_id) as total_ingredients_updated,
            COUNT(DISTINCT pul.recipe_id) as total_recipes_affected,
            DATE_FORMAT(MAX(pul.updated_at), '%Y-%m-%d %H:%i') as last_update
        FROM price_update_logs pul
        JOIN recipe_costings rc ON pul.recipe_id = rc.id
    ";
    
    if (in_array('user_id', $recipeColumns)) {
        $statsQuery .= " WHERE rc.user_id = ?";
    } elseif (in_array('created_by', $recipeColumns)) {
        $statsQuery .= " WHERE rc.created_by = ?";
    } else {
        $statsQuery .= " WHERE 1=1";
    }
    
    if (in_array('user_id', $recipeColumns) || in_array('created_by', $recipeColumns)) {
        $stmt = $pdo->prepare($statsQuery);
        $stmt->execute([$user_id]);
    } else {
        $stmt = $pdo->query($statsQuery);
    }
    
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Ensure stats are set to 0 if null
    $stats['total_ingredients_updated'] = $stats['total_ingredients_updated'] ?? 0;
    $stats['total_recipes_affected'] = $stats['total_recipes_affected'] ?? 0;
    $stats['last_update'] = $stats['last_update'] ?? null;
    
    echo json_encode([
        'success' => true,
        'recent_updates' => $recentUpdates,
        'stats' => $stats
    ]);
    
} catch (Exception $e) {
    error_log('Price updates API error: ' . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred while fetching price updates',
        'debug' => DEBUG_MODE ? $e->getMessage() : null
    ]);
}
?>