<?php
require_once '../../includes/config.php';
require_once '../../includes/database.php';

header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid input data');
    }
    
    $pdo = Database::getInstance()->getConnection();
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Check if we're updating or inserting
    $isUpdate = isset($input['meal_id']) && !empty($input['meal_id']);
    
    if ($isUpdate) {
        // Update existing meal
        $stmt = $pdo->prepare("
            UPDATE meals 
            SET name = ?, description = ?, category = ?, meal_type = ?, 
                people_count = ?, selling_price = ?, total_cost = ?, profit = ?, gp_percentage = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ? AND created_by = ?
        ");
        
        $stmt->execute([
            $input['name'],
            $input['description'] ?? '',
            $input['category'] ?? '',
            $input['meal_type'] ?? '',
            $input['people_count'],
            $input['selling_price'],
            $input['total_cost'],
            $input['profit'],
            $input['gp_percentage'],
            $input['meal_id'],
            $input['user_id']
        ]);
        
        $mealId = $input['meal_id'];
        
        // Delete existing meal costings
        $deleteStmt = $pdo->prepare("DELETE FROM meal_costings WHERE meal_id = ?");
        $deleteStmt->execute([$mealId]);
        
    } else {
        // Insert new meal
        $stmt = $pdo->prepare("
            INSERT INTO meals 
            (name, description, category, meal_type, people_count, selling_price, 
             total_cost, profit, gp_percentage, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $input['name'],
            $input['description'] ?? '',
            $input['category'] ?? '',
            $input['meal_type'] ?? '',
            $input['people_count'],
            $input['selling_price'],
            $input['total_cost'],
            $input['profit'],
            $input['gp_percentage'],
            $input['user_id']
        ]);
        
        $mealId = $pdo->lastInsertId();
    }
    
    // Insert meal costings
    if (isset($input['costings']) && is_array($input['costings'])) {
        $costingStmt = $pdo->prepare("
            INSERT INTO meal_costings (meal_id, costing_sheet_id, servings) 
            VALUES (?, ?, ?)
        ");
        
        foreach ($input['costings'] as $costing) {
            $costingStmt->execute([
                $mealId,
                $costing['id'],
                $costing['servings']
            ]);
        }
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => $isUpdate ? 'Meal updated successfully!' : 'Meal saved successfully!',
        'meal_id' => $mealId
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Error saving meal: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Error saving meal: ' . $e->getMessage()
    ]);
}