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

$response = ['success' => false, 'message' => '', 'affected_recipes' => 0];

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['updates']) || !is_array($input['updates'])) {
        throw new Exception('Invalid input data');
    }
    
    // Get user ID from database session
    $user_id = null;
    $auth_token = $_COOKIE['rcp_auth'] ?? null;
    
    if ($auth_token) {
        $pdo = Database::getInstance()->getConnection();
        
        $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
        $stmt->execute([$auth_token]);
        $session_data = $stmt->fetchColumn();
        
        if ($session_data) {
            $user = json_decode($session_data, true);
            $user_id = $user['user_id'] ?? null;
        }
    }
    
    if (!$user_id) {
        throw new Exception('User not authenticated');
    }
    
    $pdo->beginTransaction();
    $totalAffectedRecipes = 0;
    
    foreach ($input['updates'] as $update) {
        if (!isset($update['id']) || !isset($update['price'])) {
            continue;
        }
        
        $ingredientId = intval($update['id']);
        $newPrice = floatval($update['price']);
        
        // Get old price
        $stmt = $pdo->prepare("SELECT price FROM ingredients WHERE id = ? AND user_id = ?");
        $stmt->execute([$ingredientId, $user_id]);
        $oldIngredient = $stmt->fetch();
        
        if (!$oldIngredient) {
            continue;
        }
        
        $oldPrice = floatval($oldIngredient['price']);
        
        if ($newPrice == $oldPrice) {
            continue;
        }
        
        // Update ingredient price
        $stmt = $pdo->prepare("UPDATE ingredients SET price = ? WHERE id = ? AND user_id = ?");
        $stmt->execute([$newPrice, $ingredientId, $user_id]);
        
        // Update recipe_ingredients for this ingredient
        $stmt = $pdo->prepare("
            UPDATE recipe_ingredients 
            SET unit_cost = ?, 
                line_cost = quantity * ? 
            WHERE ingredient_id = ?
        ");
        $stmt->execute([$newPrice, $newPrice, $ingredientId]);
        
        // Get all affected recipe IDs
        $stmt = $pdo->prepare("
            SELECT DISTINCT recipe_id 
            FROM recipe_ingredients 
            WHERE ingredient_id = ?
        ");
        $stmt->execute([$ingredientId]);
        $affectedRecipes = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
        
        // Recalculate totals for each affected recipe
        foreach ($affectedRecipes as $recipeId) {
            // Get total cost for this recipe
            $stmt = $pdo->prepare("
                SELECT SUM(line_cost) as total_cost 
                FROM recipe_ingredients 
                WHERE recipe_id = ?
            ");
            $stmt->execute([$recipeId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $totalCost = floatval($result['total_cost'] ?? 0);
            
            // Get recipe portions
            $stmt = $pdo->prepare("SELECT portions FROM recipe_costings WHERE id = ?");
            $stmt->execute([$recipeId]);
            $recipe = $stmt->fetch(PDO::FETCH_ASSOC);
            $portions = intval($recipe['portions'] ?? 1);
            
            // Calculate new cost per portion
            $costPerPortion = $portions > 0 ? $totalCost / $portions : 0;
            
            // Update recipe costing
            $stmt = $pdo->prepare("UPDATE recipe_costings SET total_cost = ?, cost_per_portion = ? WHERE id = ?");
            $stmt->execute([$totalCost, $costPerPortion, $recipeId]);
            
            // Add price update log
            $stmt = $pdo->prepare("
                INSERT INTO price_update_logs (recipe_id, ingredient_id, old_price, new_price, updated_at) 
                VALUES (?, ?, ?, ?, NOW())
            ");
            $stmt->execute([$recipeId, $ingredientId, $oldPrice, $newPrice]);
        }
        
        $totalAffectedRecipes += count($affectedRecipes);
    }
    
    $pdo->commit();
    
    $response['success'] = true;
    $response['affected_recipes'] = $totalAffectedRecipes;
    $response['message'] = 'Ingredient prices updated successfully and ' . $totalAffectedRecipes . ' recipe(s) were recalculated!';
    
} catch (Exception $e) {
    $pdo->rollBack();
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>