<?php
switch ($_REQUEST ['job']) {
    case 'searchComponents' :
        searchComponents ( $_REQUEST ['searchText'] );
        break;
    case 'getItemsComponents' :
        getItemsComponents ( $_REQUEST ['prod_id'] );
        break;
    case 'saveItemsComponents' :
        saveItemsComponents ( $_REQUEST ['items'], $_REQUEST ['prod_id'] );
        break;
    case 'searchActions' :
        searchActions ( $_REQUEST ['searchText'] );
        break;
    case 'getItemsActions' :
        getItemsActions ( $_REQUEST ['prod_id'] );
        break;
    case 'saveItemsActions' :
        saveItemsActions ( $_REQUEST ['items'], $_REQUEST ['prod_id'] );
        break;
    case 'searchProduct' :
        searchProduct ( $_REQUEST ['searchText'] );
        break;
}
function saveItemsComponents($items, $prod_id) {
    $items = json_decode ( base64_decode ( $items ) );
    $db = $GLOBALS ['db'];
    global $current_user;
    // delete old positions
    $db->query ( "DELETE FROM ecmproductcomponents WHERE ecmproduct_id='$prod_id'" );
    // save new positions
    $res = array ();
    $pos = 0;
    foreach ( $items as $i ) {
        $q = "INSERT INTO ecmproductcomponents VALUES (
               '" . create_guid () . "',
                NOW(),
                NOW(),
                '" . $current_user->id . "',
                '" . $current_user->id . "',
                '" . $current_user->id . "',
                '0',
                '$prod_id',
                '" . $i->product_id . "',
                '$pos',
                '" . $i->product_code . "',
                '" . $i->name . "',
                '" . $i->quantity . "',
                '',
				'" . $i->divider. "',
				'" . $i->quantity_recipe. "'
                );";
        $pos ++;
        
        echo $q;
        $db->query ( $q );
    }
    return true;
}
function getItemsComponents($prod_id) {
    $db = $GLOBALS ['db'];
    global $app_list_strings;
    $res = $db->query ( "SELECT ecmcomponent_id, quantity,divider,quantity_recipe FROM ecmproductcomponents WHERE ecmproduct_id='$prod_id' AND deleted='0' order by position" );
    $result = array ();
    while ( $row = $db->fetchByAssoc ( $res ) ) {
        // get component info
        $p = $db->fetchByAssoc ( $db->query ( "SELECT code, name, unit_id, ems_price FROM ecmproducts WHERE id='" . $row ['ecmcomponent_id'] . "'" ) );
        $tmp = array ();
        $tmp ['product_id'] = $row ['ecmcomponent_id'];
        $tmp ['product_code'] = $p ['code'];
        $tmp ['quantity'] = $row ['quantity'];
        $tmp ['divider'] = $row ['divider'];
        $tmp ['quantity_recipe'] = $row ['quantity_recipe'];
        $tmp ['name'] = $p ['name'];
        $tmp ['product_link'] = '<a href="index.php?module=EcmProducts&action=DetailView&record=' . $row ['ecmcomponent_id'] . '" target="new">' . $p ['code'] . '</a>';
        $tmp ['unit'] = $app_list_strings ['ecmproducts_unit_dom'] [$p ['unit_id']];
        // get avg purchase price
        // get ems price
		
        $tmp ['purchase_price'] = $p ['ems_price'];
        if (! $p || $p ['ems_price'] == 0) {
            $pz = $db->fetchByAssoc ( $db->query ( "
					SELECT price, parent_name FROM ecmstockoperations WHERE
						product_id= '" . $tmp ['product_id'] . "' AND
						parent_type = 'EcmStockDocIns'
						ORDER BY date_entered DESC
						LIMIT 0,1
					" ) );
					
            $tmp ['purchase_price'] = $pz['parent_name'];//$pz ['price'];
            $tmp['purchase_price_document'] = $pz['parent_name'];
        }
		//var_dump($tmp);
        $tmp['total'] = $tmp['purchase_price'] * $tmp['quantity'];
        $result [] = $tmp;
    }
    echo json_encode ( $result );
    return;
}
function searchComponents($st) {
    $db = $GLOBALS ['db'];
    $res = $db->query ( "
            SELECT id, code, name, unit_id, ems_price FROM ecmproducts WHERE
            (code LIKE '%$st%' OR
            name LIKE '%$st%')
            AND deleted='0'
            " );
    $result = array ();
    global $app_list_strings;
    while ( $row = $db->fetchByAssoc ( $res ) ) {
        $item = array ();
        $item ['value'] = "<b>" . $row ['code'] . "</b>&nbsp;&nbsp;&nbsp;" . $row ['name'];
        $tmp = array ();
        $tmp ['product_code'] = $row ['code'];
        $tmp ['product_link'] = '<a href="index.php?module=EcmProducts&action=DetailView&record=' . $row ['id'] . '" target="new">' . $row ['code'] . '</a>';
        $tmp ['name'] = $row ['name'];
        $tmp ['product_id'] = $row ['id'];
        $tmp ['unit'] = $app_list_strings ['ecmproducts_unit_dom'] [$row ['unit_id']];
        $tmp ['quantity'] = 1;
        $tmp ['divider'] = 1;
        $tmp ['quantity_recipe'] =1;
        // get avg purchase price
        // get ems price
        $tmp ['purchase_price'] = $row ['ems_price'];
        if (! $row ['ems_price'] || $row ['ems_price'] == 0) {
            $pz = $db->fetchByAssoc ( $db->query ( "
					SELECT price FROM ecmstockoperations WHERE
product_id= '" . $tmp ['product_id'] . "' AND
parent_type = 'EcmStockDocIns'
ORDER BY date_entered DESC
LIMIT 0,1
					" ) );
            $tmp ['purchase_price'] = $pz ['price'];
        }
        $item ['fields'] = json_encode ( $tmp );
        $result [] = $item;
    }
    echo json_encode ( $result );
    return;
}
function saveItemsActions($items, $prod_id) {
    $items = json_decode ( base64_decode ( $items ) );
    $db = $GLOBALS ['db'];
    global $current_user;
    // delete old positions
    $db->query ( "DELETE FROM ecmproductactions WHERE ecmproduct_id='$prod_id'" );
    // save new positions
    $res = array ();
    $pos = 0;
    foreach ( $items as $i ) {
        $q = "INSERT INTO ecmproductactions VALUES (
               '" . create_guid () . "',
               '" . $current_user->id . "',
                NOW(),
                '$prod_id',
                '" . $i->action_id . "',
                '" . $i->quantity . "',
                '$pos'                
                );";
        $pos ++;
        $db->query ( $q );
    }
    return true;
}
function getItemsActions($prod_id) {
    $db = $GLOBALS ['db'];
    global $app_list_strings;
    $res = $db->query ( "SELECT ecmaction_id, quantity FROM ecmproductactions WHERE ecmproduct_id='$prod_id' order by position" );
    $result = array ();
    while ( $row = $db->fetchByAssoc ( $res ) ) {
        // get action info
        $p = $db->fetchByAssoc ( $db->query ( "SELECT indeks, name, cost_action, cost_other FROM ecmactions WHERE id='" . $row ['ecmaction_id'] . "'" ) );
        $tmp = array ();
        $tmp ['action_id'] = $row ['ecmaction_id'];
        $tmp ['action_code'] = $p ['indeks'];
        $tmp ['quantity'] = $row ['quantity'];
        $tmp ['name'] = $p ['name'];
        $tmp ['action_link'] = '<a href="index.php?module=EcmActions&action=DetailView&record=' . $row ['ecmaction_id'] . '" target="new">' . $p ['indeks'] . '</a>';
        $tmp ['price_netto'] = $p ['cost_other'];
        $tmp ['price_brutto'] = $p ['cost_action'];
        $tmp['total_netto'] = $tmp['quantity'] * $tmp['price_netto'];
        $tmp['total_brutto'] = $tmp['quantity'] * $tmp['price_brutto'];
        $result [] = $tmp;
    }
    echo json_encode ( $result );
    return;
}
function searchActions($st) {
    $db = $GLOBALS ['db'];
    $res = $db->query ( "
            SELECT id, indeks, name, time, cost_action, cost_other FROM ecmactions WHERE
            (indeks LIKE '%$st%' OR
            name LIKE '%$st%')
            AND deleted='0'
            " );
    $result = array ();
    global $app_list_strings;
    while ( $row = $db->fetchByAssoc ( $res ) ) {
        $item = array ();
        $item ['value'] = "<b>" . $row ['indeks'] . "</b>&nbsp;&nbsp;&nbsp;" . $row ['name'].' ('.$row['cost_other'].')';
        $tmp = array ();
        $tmp ['action_code'] = $row ['indeks'];
        $tmp ['action_link'] = '<a href="index.php?module=EcmActions&action=DetailView&record=' . $row ['id'] . '" target="new">' . $row ['indeks'] . '</a>';
        $tmp ['name'] = $row ['name'];
        $tmp ['action_id'] = $row ['id'];
        $tmp ['quantity'] = 1;
        $tmp ['price_brutto'] = $row ['cost_action'];
        $tmp ['price_netto'] = $row ['cost_other'];
        $item ['fields'] = json_encode ( $tmp );
        $result [] = $item;
    }
    echo json_encode ( $result );
    return;
}

function searchProduct($st) {
    $db = $GLOBALS ['db'];
    $res = $db->query ( "
            SELECT id, code FROM ecmproducts WHERE
            (code LIKE '%$st%' OR
            name LIKE '%$st%')
            AND deleted='0'
            " );
    $result = array ();
    global $app_list_strings;
    while ( $row = $db->fetchByAssoc ( $res ) ) {
        $item = array ();
        $item ['value'] = "<b>" . $row ['code'] . "</b>";
        $tmp = array ();
        $tmp ['product_code'] = $row ['code'];
        $tmp ['product_id'] = $row['id'];
        $item ['fields'] = json_encode ( $tmp );
        $result [] = $item;
    }
    echo json_encode ( $result );
    return;
}