<?php 
include('includes/session.php');
$ViewTopic = "Inventory";// Filename's id in ManualContents.php's TOC.
$BookMark = "StockLocatorTransfers";// Anchor's id in the manual's html document.
include('includes/SQL_CommonFunctions.inc');

if ($_SESSION['StockLocatorIntegrated'] == '0')
{
    $Title = _('Warehouse Stock Integration Not Enabled');
	include('includes/header.php');
	echo '<p class="page_title_text"><img alt="" src="', $RootPath, '/css/', $Theme,
		'/images/error.png" title="', // Icon image.
		$Title, '" /> ', // Icon title.
		$Title, '</p>';// Page title.
	echo '<br />';
	prnMsg(_('The system is not configured for warehouse stock integration. A configuration parameter is required for warehouse stock integration. Please consult your system administrator.'), 'info');
	include('includes/footer.php');
	exit;
}

$Title = _('Stock Placement');// Screen identification.
include('includes/header.php');

if(isset($_GET['Location'])) {
	$_POST['StockLocation']=$_GET['Location'];
    $_POST['SelectStockID']=$_GET['StockID'];
}

if (isset($_POST['ProcessStockLocationTransfer']))
{
    $is_from_receiving = false;
    if($_POST['from'] == "")
    {
        $is_from_receiving = true;

        $SQL = "SELECT SUM(quantity) FROM stock_locators WHERE stockid = '".$_POST['stockid']."' AND loccode = '".$_POST['location']."' AND active = 1";
        
        $ErrMsg =  _('Could not retrieve the total quantity at the sending location because');
        $DbgMsg =  _('The SQL that failed was');
        $Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
        if(DB_num_rows($Result)==1) {
            $LocQtyRow = DB_fetch_row($Result);
            $QtyOnHand = $LocQtyRow[0];
        } else {
            // There must actually be some error this should never happen
            $QtyOnHand = 0;
        }

        $from_location[0] = "";
        $from_location[1] = "";
        $from_location[2] = "";
        $max_allowed_qty = $_POST['total_quantity'] - $QtyOnHand;
    }
    else
    {
        $from_location = explode(";", $_POST['from']);
        $max_allowed_qty = $from_location[3];
    }
    
    $to_location = explode(";", $_POST['to']);

    if($from_location[0] == $to_location[0] && 
        $from_location[1] == $to_location[1] &&
        $from_location[2] == $to_location[2])
    {
        echo '<br />';
		prnMsg( _('The locations to transfer from and to must be different'), 'error');
    }
    else if ($max_allowed_qty >= $_POST['transfer_quantity'] && $_POST['transfer_quantity'] > 0)
    {
        $TransferNumber = GetNextTransNo(99);
		$PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']));
        $SQLTransferDate = FormatDateForSQL(Date($_SESSION['DefaultDateFormat']));
        
        $Result = DB_Txn_Begin();

        // first, process the stock going out of the from location
        if(!$is_from_receiving)
        {
            // need to get the current location quantity will need it later for the stock movement
            $SQL = "SELECT quantity
                    FROM stock_locators
                    WHERE stockid = '".$_POST['stockid']."' AND loccode = '".$_POST['location']."' AND rack = '".$from_location[0]."' AND row = '".$from_location[1]."' AND bin = '".$from_location[2]."' AND active = 1";
            
            $ErrMsg =  _('Could not retrieve the quantity at the sending location because');
            $DbgMsg =  _('The SQL that failed was');
            $Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
            if(DB_num_rows($Result)==1) {
                $LocQtyRow = DB_fetch_row($Result);
                $QtyOnHandPrior = $LocQtyRow[0];
            } else {
                // There must actually be some error this should never happen
                $QtyOnHandPrior = 0;
            }
            
            // Insert the stock movement for the stock going out of the from location
            $SQL = "INSERT INTO stock_locator_moves(stockid,
                                                    type,
                                                    transno,
                                                    loccode,
                                                    rack,
                                                    row,
                                                    bin,
                                                    trandate,
                                                    userid,
                                                    prd,
                                                    reference,
                                                    qty,
                                                    newqoh)
                                            VALUES (
                                            '" . $_POST['stockid'] . "',
                                            99,
                                            '" . $TransferNumber . "',
                                            '" . $_POST['location'] . "',
                                            '" . $from_location[0] . "',
                                            '" . $from_location[1] . "',
                                            '" . $from_location[2] . "',
                                            '" . $SQLTransferDate . "',
                                            '" . $_SESSION['UserID'] . "',
                                            '" . $PeriodNo . "',
                                            'To " . $_POST['location'] . " [" . $to_location[0] . "-" . $to_location[1] . "-" . $to_location[2] ."]',
                                            '" . round(-$_POST['transfer_quantity'], 0)  . "',
                                            '" . ($QtyOnHandPrior - round($_POST['transfer_quantity'], 0)) . "'
                                            )";

            $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
            $DbgMsg =  _('The following SQL to insert the stock movement record was used');
            $Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
        }

        // then process the stock movement for the stock coming into the to location

        // need to get the current location quantity will need it later for the stock movement
        $SQL = "SELECT quantity
                FROM stock_locators
                WHERE stockid = '".$_POST['stockid']."' AND loccode = '".$_POST['location']."' AND rack = '".$to_location[0]."' AND row = '".$to_location[1]."' AND bin = '".$to_location[2]."' AND active = 1";

        $ErrMsg =  _('Could not retrieve the quantity at the destination because');
        $DbgMsg =  _('The SQL that failed was');
        $Result = DB_query($SQL, $ErrMsg, $DbgMsg,true);
        if(DB_num_rows($Result)==1) {
            $LocQtyRow = DB_fetch_row($Result);
            $QtyOnHandPrior = $LocQtyRow[0];
        } else {
            // There must actually be some error this should never happen
            $QtyOnHandPrior = 0;
        }

        // Insert the stock movement for the stock coming into the to location
		$SQL = "INSERT INTO stock_locator_moves (stockid,
                                                type,
                                                transno,
                                                loccode,
                                                rack,
                                                row,
                                                bin,
                                                trandate,
                                                userid,
                                                prd,
                                                reference,
                                                qty,
                                                newqoh)
                                        VALUES ('" . $_POST['stockid'] . "',
                                                99,
                                                '" . $TransferNumber . "',
                                                '" . $_POST['location'] . "',
                                                '" . $to_location[0] . "',
                                                '" . $to_location[1] . "',
                                                '" . $to_location[2] . "',
                                                '" . $SQLTransferDate . "',
                                                '" . $_SESSION['UserID'] . "',
                                                '" . $PeriodNo . "',
                                                'From " . $_POST['location'] . " [" . $from_location[0] . "-" . $from_location[1] . "-" . $from_location[2] ."]',
                                                '" . $_POST['transfer_quantity'] . "',
                                                '" . round($QtyOnHandPrior + $_POST['transfer_quantity'], 0) . "')";

        $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The stock movement record cannot be inserted because');
        $DbgMsg = _('The following SQL to insert the stock movement record was used');
        $Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);

        if(!$is_from_receiving)
        {
            $SQL = "UPDATE stock_locators
                    SET quantity = quantity - '" . round($_POST['transfer_quantity'], 0) . "'
                    WHERE stockid='" . $_POST['stockid'] . "'
                    AND loccode='" . $_POST['location'] . "'
                    AND rack='".$from_location[0]."'
                    AND row='".$from_location[1]."'
                    AND bin='".$from_location[2]."'
                    AND active=1";

            $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The location stock record could not be updated because');
            $DbgMsg = _('The following SQL to update the location stock record was used');
            $Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
        }

		$SQL = "UPDATE stock_locators
				SET quantity = quantity + '" . round($_POST['transfer_quantity'], 0) . "', stockid='" . $_POST['stockid'] . "'
				WHERE loccode='" . $_POST['location'] . "'
                AND rack='".$to_location[0]."'
                AND row='".$to_location[1]."'
                AND bin='".$to_location[2]."'
                AND active=1";

		$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The location stock record could not be updated because');
		$DbgMsg = _('The following SQL to update the location stock record was used');
		$Result = DB_query($SQL,$ErrMsg, $DbgMsg, true);

        $Result = DB_Txn_Commit();
        prnMsg('An inventory transfer of stock item ' . $_POST['stockid'] . ' has been created', 'success');
    }
    else
    {
        prnMsg('Stock allocated quantity must be more than zero and cannot be more than total available quantity', 'error');
    }
    
}

echo '<p class="page_title_text">
		<img src="'.$RootPath.'/css/'.$Theme.'/images/supplier.png" title="' . _('Dispatch') . '" alt="" />' . ' ' . $Title . '
	  </p>';

echo '<form action="'. htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

if(isset($_POST['CheckCode'])) {

    $sql="SELECT stockid,
            description
        FROM stockmaster
        WHERE stockid " . LIKE . " '%" . $_POST['StockID']."%'";

    $ErrMsg=_('The stock information cannot be retrieved because');
    $DbgMsg=_('The SQL to get the stock description was');
    $result = DB_query($sql,$ErrMsg,$DbgMsg);
    
    echo '<table class="selection">
        <thead>
            <tr>
                <th class="ascending">' . _('Stock Code') . '</th>
                <th class="ascending">' . _('Stock Description') . '</th>
            </tr>
        </thead>
        <tbody>';
    while($myrow = DB_fetch_array($result)) {
        echo '<tr>
                <td>'.$myrow['stockid'].'</td>
                <td>' . $myrow['description'] . '</td>
                <td><a href="' . $RootPath . '/emp_StockLocatorTransfer.php?StockID='.$myrow['stockid'].'&amp;Location='.$_POST['StockLocation'].'">'
                ._('Transfer') . '</a>
            </tr>';

    }
    echo '</tbody></table>';
    include('includes/footer.php');
    exit;
}
else if(isset($_POST['SelectStockID'])) {
    echo '<table class="selection">
            <tr>
                <td>' .  _('Stock Code'). ':</td>
                <td>' . $_POST['SelectStockID'] . '</td>
            </tr>
            <tr>
                <td>' . _('Location').':</td>
                <td>' . $_POST['StockLocation'] . '</td>
            </tr>';


    $sql = "SELECT quantity FROM locstock WHERE loccode = '".$_POST['StockLocation']."' AND stockid = '".$_POST['SelectStockID']."'";
    $result = DB_query($sql);
    if(DB_num_rows($result) == 1) {
        $total_quantity_at_location = 0;
        while($myrow=DB_fetch_array($result)) {
            $total_quantity_at_location = $myrow['quantity'];
        }

        echo '<tr>
                <td>' . _('Quantity on Hand').':</td>
                <td><input type="hidden" name="total_quantity" value="' . $total_quantity_at_location . '" />' . $total_quantity_at_location . '</td>
            </tr>';

        $table = "";
        $sql = "SELECT rack, row, bin, quantity FROM stock_locators WHERE loccode = '" . $_POST['StockLocation'] . "' AND stockid = '" . $_POST['SelectStockID'] . "' AND quantity > 0 AND active = 1 ORDER BY rack, row, bin";
        $result = DB_query($sql);
        $table .= '<tr><td>' . _('From Stock Location').':</td>';
        $temp = '';
        if(DB_num_rows($result) > 0) {
            while($myrow=DB_fetch_array($result)) {
                $total_quantity_at_location -= $myrow['quantity'];
                $temp .= '<option value="' . $myrow['rack'] . ';' . $myrow['row'] . ';' . $myrow['bin'] . ';' . $myrow['quantity'] . '" />' . $myrow['rack'] . '-' . $myrow['row'] . '-' . $myrow['bin'] . ' ('.$myrow['quantity'].')</option>';
            }
        }
        $table .= '<td><select name="from">
                        <option value="">Receive ('.$total_quantity_at_location.')</option>';
        $table .= $temp;
        $table .= '</select></td>';
        $table .= '</tr>';

        $sql = "SELECT rack, row, bin, stockid, quantity FROM stock_locators WHERE (stockid IS NULL OR stockid = '".$_POST['SelectStockID']."' OR quantity = 0) AND loccode = '" . $_POST['StockLocation'] . "' AND active = 1 ORDER BY rack, row, bin";
        $result = DB_query($sql);
        if(DB_num_rows($result) > 0) {
            $table .= '<tr><td>' . _('To Stock Location').':</td>';
            $table .= '<td><select name="to">';
            
            while($myrow=DB_fetch_array($result)) {
                if($_POST['SelectStockID'] == $myrow['stockid'])
                {
                    $table .= '<option value="' . $myrow['rack'] . ';' . $myrow['row'] . ';' . $myrow['bin'] . '" />' . $myrow['rack'] . '-' . $myrow['row'] . '-' . $myrow['bin'] . ($myrow['stockid'] != '' ? ' ('.$myrow['quantity'].')': '') . '</option>';
                }
                else
                {
                    $table .= '<option value="' . $myrow['rack'] . ';' . $myrow['row'] . ';' . $myrow['bin'] . '" />' . $myrow['rack'] . '-' . $myrow['row'] . '-' . $myrow['bin'] . ($myrow['stockid'] != '' ? ' ['.$myrow['stockid'].']': '') . '</option>';
                }
            }

            $table .= '</select></td></tr>';
            $table .= '<tr><td>' . _('Transfer Quantity').':</td><td><input type="number" name="transfer_quantity" value="" min="0" /></td></tr>';
            $table .= '</tbody></table>';
        }
        if($table != '') {
            echo $table;
            echo '<input type="hidden" name="stockid" value="' . $_POST['SelectStockID'] . '" />
                <input type="hidden" name="location" value="' . $_POST['StockLocation'] . '" />
                <input type="submit" value="Process Stock Transfer" name="ProcessStockLocationTransfer" />';
        }
        else {
            prnMsg('No warehouse racking information defined for  ' . mb_strtoupper($_POST['StockLocation']), 'warn');    
        }
        echo '<input type="submit" value="Cancel" name="cancel" formnovalidate="formnovalidate" />';
    }
    else {
        // failed to retrieve stock quantity
        prnMsg('Unable to locate Stock Code ' . mb_strtoupper($_POST['SelectStockID']), 'error');
    }
}
else {
    echo '<table class="selection">
            <tr>
                <td>' .  _('Stock Code'). ':</td>
                <td><input type="text" name="StockID" size="21" value="" maxlength="20" /></td>
            </tr>
            <tr>
                <td></td>
                
            </tr>';

    echo '<tr>
            <td>' . _('Location').':</td>
            <td><select name="StockLocation">';

    $sql = "SELECT locations.loccode, locationname FROM locations INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canupd=1";
    $resultStkLocs = DB_query($sql);
    while($myrow=DB_fetch_array($resultStkLocs)) {
        if($myrow['loccode']==$_SESSION['UserStockLocation']) {
            echo '<option selected="selected" value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
        } else {
            echo '<option value="' . $myrow['loccode'] . '">' . $myrow['locationname'] . '</option>';
        }
    }
    echo '</select></td>
        </tr>
        <tr>
            <td></td><td><input type="submit" name="CheckCode" value="'._('Check Part').'" /></td>
        </tr>
    </table>';
}

echo '</div></form>';
    
include('includes/footer.php');
?>