如何在成本上应用自定义属性值

I am new to Magento. I am trying to achieve a simple way to apply custom margin at cost and then get its sale price. I want to put only cost then some function to calculate 20% VAT (TAX) and custom attributes margin which suppose I set 15%.

Example:

I have three fields when adding or editing product :

Cost = 100 
Price = 0 
margin_percentage: 15 (means 15%) 

After user add 100 and margin percentage 15, system first calculate 20% VAT then on resulting amount add 15% margin so I get this case

cost + vat + margin = 138 after saving

Cost = 100 
Price = 138 
margin_percentage: 15

I have write a module and tried to achieve this using Event Observer - catalog_product_save_before and catalog_product_save_after here is a function. If this code works I may apply formula's, but I try to update db tables nothing happened. I don't know what is going wrong. I am trying to update this table catalog_product_flat_1

class SmashingMagazine_LogProductUpdate_Model_Observer
{
/**
 * Magento passes a Varien_Event_Observer object as
 * the first parameter of dispatched events.
 */
public function logUpdate(Varien_Event_Observer $observer)
{
    $product = $observer->getEvent()->getProduct();
    $cost = $product->getCost();

    $_product = Mage::getModel('catalog/product')->load($product->getId());
    $_product->setPrice($cost); // or an other price field
    $_product->save();

    Mage::log(
        "cost {$cost} Price {$price} ",
        null, 
        'product-updates.log'
    );
}

}

I follow this tutorial for making this module http://coding.smashingmagazine.com/2012/03/01/basics-creating-magento-module/ ... now what is wrong with the above code? Also give me execution time out error. My server current execution time is 300000

Hope someone guide me to a right direction

Best Regards

Why don't you write the price in the Magento catalog/price mobel object?

$_product = Mage::getModel('catalog/product')->load($product->getId());
$_product->setPrice($cost); // or an other price field
$_product->save();

instead of:

$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->beginTransaction();
$fields = array();
$fields['price'] = $cost;
$where = $connection->quoteInto('entity_id =?', $id);
$connection->update('catalog_product_flat_1', $fields, $where);
$connection->commit();

my problem is solved .. one thing i want to share in above code. problem in above code i reload model 2 time. after removing this model

 $_product = Mage::getModel('catalog/product')->load($product->getId());

now problem solved

Thanks all

Best Regards