<?php
include_once '../root.class.php';
$db = new db_safeguard();

////////////////////////////////////////////////
// NOTE SCRYPT RUNNUING ON SERVER IN HOUSE
////////////////////////////////////////////////


$stock_res = $db->query("stock", "SELECT * FROM stock WHERE 1");
while ($stock = $stock_res->fetch_assoc()) {
    $stock_id = $stock['record_id'];
    $cost_price = $stock['cost_price'] ? $stock['cost_price'] : 0;
    // get latest price from order_items
    $order_items_res = $db->query("order_items", "SELECT * FROM order_items WHERE stock_id = $stock_id AND (purchase_price_ex != 0 AND purchase_price_ex !=   $cost_price )  ORDER BY record_id DESC LIMIT 1");
    if ($order_items_res->num_rows > 0) {
        $order_item = $order_items_res->fetch_assoc();
        $order_item_price = (isset($order_item['purchase_price_ex'])) ? (float) $order_item['purchase_price_ex'] : 0;
        // echo "ID : " . $stock_id;
        // echo "STOCK : " . $stock['description'];
        // echo "<br>";
        // echo "PRICE : " . (float) $stock['cost_price'];
        // echo "<br>";
        // echo "ORDER ITEM PRICE : " . (float) $order_item_price;
        // echo "<br>";
        // echo "DIFFERENCE : " . ((float) $order_item_price - (float) $stock['cost_price']);
        if (((float) $order_item_price - (float) $stock['cost_price']) != 0) {
            $db->query("stock", "UPDATE stock SET cost_price = $order_item_price WHERE record_id = $stock_id");
            // echo "UPDATED";
        }
        // echo "<br>";
        // echo "<hr>";
    }
}
