<?php
class eventclass_augmentation_request_allocation  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeEdit' => true,
	'BeforeDelete' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		$allocationId =
    intval($keys["allocation_id"]);

$requestId =
    intval($oldvalues["augmentation_request_id"]);

$requestItemId =
    intval($oldvalues["augmentation_request_item_id"]);

$itemId =
    intval($oldvalues["item_id"]);

$warehouseId =
    intval($oldvalues["warehouse_id"]);

$batchNo =
    trim((string)$oldvalues["batch_no"]);

$expiryDate =
    trim((string)$oldvalues["expiry_date"]);

$oldQty =
    floatval($oldvalues["allocated_qty"]);

$newQty =
    floatval($values["allocated_qty"]);


if ($oldvalues["allocation_status"] != "PENDING") {

    $message =
        "Only PENDING allocation records may be changed.";

    return false;
}


if ($newQty <= 0) {

    $message =
        "Allocated quantity must be greater than zero.";

    return false;
}


/* ============================================================
   HEADER MUST BE OPEN FOR ALLOCATION
   ============================================================ */

$sql = DB::PrepareSQL(
    "
    SELECT allocation_status
    FROM augmentation_request
    WHERE augmentation_request_id = :1
    ",
    $requestId
);

$requestStatus =
    DB::DBLookup($sql);

if ($requestStatus != "FOR_ALLOCATION") {

    $message =
        "This request cannot be edited because its current status is "
        . $requestStatus . ".";

    return false;
}


/* ============================================================
   LIVE STOCK
   ============================================================ */

$sql = DB::PrepareSQL(
    "
    SELECT
        requested_qty,
        available_qty

    FROM vw_augmentation_item_available_stock

    WHERE augmentation_request_item_id = :1

      AND available_item_id = :2

      AND warehouse_id = :3

      AND COALESCE(batch_no,'') = ':4'

      AND expiry_date <=>
          CAST(NULLIF(':5','') AS DATE)

    LIMIT 1
    ",
    $requestItemId,
    $itemId,
    $warehouseId,
    $batchNo,
    $expiryDate
);

$rs = DB::Query($sql);
$stock = $rs->fetchAssoc();

if (!$stock) {

    $message =
        "This stock/batch is no longer available.";

    return false;
}


$requestedQty =
    floatval($stock["requested_qty"]);

$availableForThisRequest =
    floatval($stock["available_qty"]);


/* ============================================================
   TOTAL CURRENT ALLOCATION FOR REQUEST LINE
   ============================================================ */

$sql = DB::PrepareSQL(
    "
    SELECT COALESCE(SUM(allocated_qty),0)

    FROM augmentation_request_allocation

    WHERE augmentation_request_item_id = :1

      AND allocation_status IN (
          'PENDING',
          'APPROVED'
      )
    ",
    $requestItemId
);

$totalLineAllocation =
    floatval(DB::DBLookup($sql));


/* ============================================================
   CURRENT TOTAL FOR SAME STOCK/BATCH
   ============================================================ */

$sql = DB::PrepareSQL(
    "
    SELECT COALESCE(SUM(allocated_qty),0)

    FROM augmentation_request_allocation

    WHERE augmentation_request_item_id = :1

      AND item_id = :2

      AND warehouse_id = :3

      AND COALESCE(batch_no,'') = ':4'

      AND expiry_date <=>
          CAST(NULLIF(':5','') AS DATE)

      AND allocation_status IN (
          'PENDING',
          'APPROVED'
      )
    ",
    $requestItemId,
    $itemId,
    $warehouseId,
    $batchNo,
    $expiryDate
);

$totalSameStock =
    floatval(DB::DBLookup($sql));


/* ============================================================
   CALCULATE MAXIMUM NEW TOTAL FOR THIS ROW
   ============================================================ */

$otherLineAllocations =
    $totalLineAllocation - $oldQty;

$otherSameStockAllocations =
    $totalSameStock - $oldQty;


$maxByRequest =
    $requestedQty - $otherLineAllocations;

$maxByStock =
    $availableForThisRequest -
    $otherSameStockAllocations;


$maximumQty =
    min(
        $maxByRequest,
        $maxByStock
    );


if ($maximumQty < 0) {
    $maximumQty = 0;
}


if ($newQty > ($maximumQty + 0.000001)) {

    $message =
        "Maximum quantity allowed for this allocation is "
        . number_format($maximumQty, 2)
        . ".";

    return false;
}


/* ============================================================
   NEVER ALLOW THESE VALUES TO BE CHANGED FROM EDIT PAGE
   ============================================================ */

$values["augmentation_request_id"] =
    $oldvalues["augmentation_request_id"];

$values["augmentation_request_item_id"] =
    $oldvalues["augmentation_request_item_id"];

$values["item_id"] =
    $oldvalues["item_id"];

$values["sku"] =
    $oldvalues["sku"];

$values["item_description"] =
    $oldvalues["item_description"];

$values["warehouse_id"] =
    $oldvalues["warehouse_id"];

$values["warehouse_code"] =
    $oldvalues["warehouse_code"];

$values["warehouse_name"] =
    $oldvalues["warehouse_name"];

$values["batch_no"] =
    $oldvalues["batch_no"];

$values["expiry_date"] =
    $oldvalues["expiry_date"];

$values["allocation_status"] =
    $oldvalues["allocation_status"];


/* ============================================================
   AUDIT USER
   ============================================================ */

$userData =
    Security::currentUserData();

if (
    is_array($userData) &&
    isset($userData["ID"])
) {
    $values["updated_by"] =
        intval($userData["ID"]);
}

$sqlValues["updated_at"] =
    "NOW()";


return true;
		;
		return true;
	}

	function BeforeDelete( $where, &$deleted_values, &$message, $pageObject ) {
		$requestId =
    intval(
        $deleted_values["augmentation_request_id"]
    );


if (
    $deleted_values["allocation_status"]
    != "PENDING"
) {

    $message =
        "Only PENDING allocation records can be removed.";

    return false;
}


$sql = DB::PrepareSQL(
    "
    SELECT allocation_status

    FROM augmentation_request

    WHERE augmentation_request_id = :1
    ",
    $requestId
);

$requestStatus =
    DB::DBLookup($sql);


if ($requestStatus != "FOR_ALLOCATION") {

    $message =
        "Allocation can no longer be removed. Request status is "
        . $requestStatus . ".";

    return false;
}


return true;
		;
		return true;
	}
		

}


?>