<?php
// Use absolute paths to avoid any path issues
$base_path = $_SERVER['DOCUMENT_ROOT'] . '/rcp/includes/';
$config_path = $base_path . 'config.php';

// Include config first
if (file_exists($config_path)) {
    require_once $config_path;
} else {
    die("Config file not found at: " . $config_path);
}

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// SECURITY: Accept a secure token if calling from another page
$secure_token = $_POST['secure_token'] ?? '';
$expected_token = 'recipe_auto_update_' . date('Ymd'); // Simple daily token
if ($secure_token !== $expected_token) {
    die(json_encode(['success' => false, 'error' => 'Invalid security token']));
}

try {
    require_once __DIR__ . '/../includes/database.php';
    $pdo = Database::getInstance()->getConnection();
    
    // Get all ingredients with outdated prices in recipes
    $stmt = $pdo->prepare("
        SELECT DISTINCT ri.ingredient_id, i.name, i.price as current_price
        FROM recipe_ingredients ri
        JOIN ingredients i ON ri.ingredient_id = i.id
        WHERE ABS(ri.unit_cost - i.price) > 0.001
    ");
    $stmt->execute();
    $outdated_ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $updated_recipes = [];
    
    foreach ($outdated_ingredients as $ingredient) {
        $ingredient_id = $ingredient['ingredient_id'];
        $current_price = floatval($ingredient['current_price']);
        
        // Get all recipes using this ingredient
        $stmt = $pdo->prepare("
            SELECT DISTINCT ri.recipe_id, ri.unit_cost as stored_price
            FROM recipe_ingredients ri
            WHERE ri.ingredient_id = ?
        ");
        $stmt->execute([$ingredient_id]);
        $recipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($recipes as $recipe) {
            $recipe_id = $recipe['recipe_id'];
            $stored_price = floatval($recipe['stored_price']);
            
            // Check if price actually changed significantly
            if (abs($stored_price - $current_price) > 0.001) {
                // Update recipe_ingredients with current price
                $stmt = $pdo->prepare("
                    UPDATE recipe_ingredients 
                    SET unit_cost = ?, line_cost = quantity * ?
                    WHERE ingredient_id = ? AND recipe_id = ?
                ");
                $stmt->execute([$current_price, $current_price, $ingredient_id, $recipe_id]);
                
                // Recalculate total cost for this recipe
                $stmt = $pdo->prepare("
                    SELECT SUM(line_cost) as total_cost 
                    FROM recipe_ingredients 
                    WHERE recipe_id = ?
                ");
                $stmt->execute([$recipe_id]);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $total_cost = floatval($result['total_cost'] ?? 0);
                
                // Get portions
                $stmt = $pdo->prepare("SELECT portions FROM recipe_costings WHERE id = ?");
                $stmt->execute([$recipe_id]);
                $recipe_data = $stmt->fetch(PDO::FETCH_ASSOC);
                $portions = intval($recipe_data['portions'] ?? 1);
                
                $cost_per_portion = $portions > 0 ? $total_cost / $portions : 0;
                
                // Update recipe costing
                $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
                $stmt->execute([$total_cost, $cost_per_portion, $recipe_id]);
                
                // Add to updated recipes list
                if (!in_array($recipe_id, $updated_recipes)) {
                    $updated_recipes[] = $recipe_id;
                }
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Auto-update completed',
        'updated_recipes' => count($updated_recipes),
        'recipes' => $updated_recipes
    ]);
    
} catch (Exception $e) {
    error_log("Error in auto-update: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>