<?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();

    // Calculate totals
    $ingredients = json_decode($_POST['ingredients'], true);
    $totalCost = array_sum(array_column($ingredients, 'lineCost'));
    $yieldPortions = floatval($_POST['yield_portions']);
    
    $costPerPortion = $totalCost / $yieldPortions;

    // Save costing sheet
    $stmt = $pdo->prepare("INSERT INTO costing_sheets (name, category, yield_portions, prep_steps, total_cost, cost_per_portion) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['name'],
        $_POST['category'],
        $yieldPortions,
        $_POST['prep_steps'],
        $totalCost,
        $costPerPortion
    ]);

    $costingSheetId = $pdo->lastInsertId();

    // Save 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([
            $costingSheetId,
            $ingredient['name'],
            $ingredient['quantity'],
            $ingredient['unitCost'],
            $ingredient['lineCost']
        ]);
    }

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

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