<?php
// api/ingredients/update.php
error_reporting(0);
ini_set('display_errors', 0);

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

try {
    // Get POST data
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id']) || !isset($data['name']) || !isset($data['price'])) {
        throw new Exception('Missing required fields');
    }
    
    $pdo = Database::getInstance()->getConnection();
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Get current ingredient data
    $stmt = $pdo->prepare("SELECT price, previous_price FROM ingredients WHERE id = ?");
    $stmt->execute([$data['id']]);
    $current = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$current) {
        throw new Exception('Ingredient not found');
    }
    
    $currentPrice = floatval($current['price']);
    $newPrice = floatval($data['price']);
    
    // Update ingredient
    $updateSql = "UPDATE ingredients SET 
                  name = ?,
                  unit = ?,
                  price = ?,
                  category = ?,
                  supplier_info = ?,
                  updated_at = NOW()";
    
    // Only update previous_price and price_updated_at if price changed
    if ($currentPrice != $newPrice) {
        $updateSql .= ", previous_price = ?, price_updated_at = NOW()";
    }
    
    $updateSql .= " WHERE id = ?";
    
    $stmt = $pdo->prepare($updateSql);
    
    if ($currentPrice != $newPrice) {
        $stmt->execute([
            $data['name'],
            $data['unit'],
            $newPrice,
            $data['category'] ?? null,
            $data['supplier_info'] ?? null,
            $currentPrice, // Set previous_price to old price
            $data['id']
        ]);
        
        // Log to price history table
        $historySql = "INSERT INTO ingredient_price_history 
                      (ingredient_id, ingredient_name, old_price, new_price, changed_by) 
                      VALUES (?, ?, ?, ?, ?)";
        $historyStmt = $pdo->prepare($historySql);
        $historyStmt->execute([
            $data['id'],
            $data['name'],
            $currentPrice,
            $newPrice,
            1 // TODO: Get actual user ID from session
        ]);
    } else {
        $stmt->execute([
            $data['name'],
            $data['unit'],
            $newPrice,
            $data['category'] ?? null,
            $data['supplier_info'] ?? null,
            $data['id']
        ]);
    }
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Ingredient updated successfully'
    ]);
    
} catch (Exception $e) {
    if (isset($pdo)) {
        $pdo->rollBack();
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error updating ingredient: ' . $e->getMessage()
    ]);
}