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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $pdo->beginTransaction();

    // Get the sheet ID to update
    $sheetId = intval($_POST['edit_id']);
    
    // Calculate totals
    $ingredients = json_decode($_POST['ingredients'], true);
    $totalCost = array_sum(array_column($ingredients, 'lineCost'));
    $yieldPortions = floatval($_POST['yield_portions']);
    
    $costPerPortion = $totalCost / $yieldPortions;

    // Add time estimates to preparation steps
    $prepSteps = $_POST['prep_steps'];
    if (!empty($prepSteps)) {
        $steps = explode("\n", $prepSteps);
        $timedSteps = [];
        $totalTime = 0;
        
        foreach ($steps as $index => $step) {
            if (trim($step)) {
                // Estimate time based on step content
                $timeEstimate = 5; // default 5 minutes
                if (strpos(strtolower($step), 'chop') !== false) $timeEstimate = 10;
                if (strpos(strtolower($step), 'cook') !== false) $timeEstimate = 15;
                if (strpos(strtolower($step), 'bake') !== false) $timeEstimate = 30;
                if (strpos(strtolower($step), 'marinate') !== false) $timeEstimate = 60;
                
                $totalTime += $timeEstimate;
                $timedSteps[] = "Step " . ($index + 1) . " (~{$timeEstimate}min): " . trim($step);
            }
        }
        
        $prepSteps = implode("\n", $timedSteps);
        $prepSteps .= "\n\nTotal estimated preparation time: " . $totalTime . " minutes";
    }

    // Update costing sheet
    $stmt = $pdo->prepare("UPDATE costing_sheets SET name = ?, category = ?, yield_portions = ?, prep_steps = ?, total_cost = ?, cost_per_portion = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt->execute([
        $_POST['name'],
        $_POST['category'],
        $yieldPortions,
        $prepSteps,
        $totalCost,
        $costPerPortion,
        $sheetId
    ]);

    // Delete existing costing lines
    $stmt = $pdo->prepare("DELETE FROM costing_lines WHERE costing_sheet_id = ?");
    $stmt->execute([$sheetId]);

    // Insert updated costing lines
    $stmt = $pdo->prepare("INSERT INTO costing_lines (costing_sheet_id, ingredient_name, quantity, unit_cost, line_cost) VALUES (?, ?, ?, ?, ?)");
    
    foreach ($ingredients as $ingredient) {
        $stmt->execute([
            $sheetId,
            $ingredient['name'],
            $ingredient['quantity'],
            $ingredient['unitCost'],
            $ingredient['lineCost']
        ]);
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'id' => $sheetId]);

} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>