<?php
class eventclass_qa_incoming_goods  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeShowAdd' => true,
	'BeforeAdd' => true,
	'OnPageLoad' => true,
	'BeforeEdit' => true,
	'BeforeShowEdit' => true,
	'AfterAdd' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		'print' => array(
			'view' => true 
		),
		'batch_barcode' => array(
			'view' => true 
		) 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		'inspection_date' => array(
			'edit' => true 
		) 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeShowAdd( &$xt, &$templatefile, $pageObject ) {
		function previewTxnNumber($transactionCode)
{
    $sql = "
        SELECT prefix, digit_length, next_no
        FROM transaction_numbering
        WHERE transaction_code = '" . db_addslashes($transactionCode) . "'
          AND is_active = 1
        LIMIT 1
    ";

    $rs = DB::Query($sql);
    $data = $rs ? $rs->fetchAssoc() : null;

    if (!$data) {
        return "";
    }

    return $data["prefix"] .
        str_pad((int)$data["next_no"], (int)$data["digit_length"], "0", STR_PAD_LEFT);
}

$previewQaNo = previewTxnNumber("QA");
$previewBatchNo = previewTxnNumber("BATCH");
$previewVbnSeq = previewTxnNumber("VBN");

$pageObject->setProxyValue("preview_reference_number", $previewQaNo);
$pageObject->setProxyValue("preview_batch_no", $previewBatchNo);

$userName = $_SESSION["UserID"];

$sqlUser = "
    SELECT 
        u.mother_facility_id,
        u.warehouse_id,
        mf.facility_code,
        mf.facility_name,
        w.warehouse_code,
        w.name AS warehouse_name
    FROM users u
    LEFT JOIN mother_facility mf ON mf.id = u.mother_facility_id
    LEFT JOIN warehouse w ON w.id = u.warehouse_id
    WHERE u.username = '" . db_addslashes($userName) . "'
    LIMIT 1
";

$rsUser = DB::Query($sqlUser);
$dataUser = $rsUser ? $rsUser->fetchAssoc() : null;

if ($dataUser) {

    $vbnSeqOnly = preg_replace('/[^0-9]/', '', $previewVbnSeq);

    $previewVbn =
        $dataUser["facility_code"] . "-" .
        $dataUser["warehouse_code"] . "-" .
        date("Y") . "-" .
        $vbnSeqOnly;

    $pageObject->setProxyValue("mother_facility_id", $dataUser["mother_facility_id"]);
    $pageObject->setProxyValue("warehouse_id", $dataUser["warehouse_id"]);
    $pageObject->setProxyValue("preview_vbn", $previewVbn);
}




$isPo = 0;
$isDonation = 0;

if (isset($_REQUEST["po_detail_id"]) && (int)$_REQUEST["po_detail_id"] > 0) {
    $isPo = 1;
}

if (isset($_REQUEST["donation_receiving_detail_id"]) && (int)$_REQUEST["donation_receiving_detail_id"] > 0) {
    $isDonation = 1;
}

$pageObject->setProxyValue("is_po", $isPo);
$pageObject->setProxyValue("is_donation", $isDonation);

/* SHELF LIFE MAP */
$itemShelfLife = array();

$rsItem = DB::Query("
    SELECT id, shelf_life_days
    FROM item
    WHERE shelf_life_days IS NOT NULL
");

while ($rsItem && ($row = $rsItem->fetchAssoc())) {
    $itemShelfLife[$row["id"]] = (int)$row["shelf_life_days"];
}

$pageObject->setProxyValue("item_shelf_life", $itemShelfLife);



		;
		
	}

	function BeforeAdd( &$values, &$sqlValues, &$message, $inline, $pageObject ) {
		function getTxnNumber($transactionCode)
{
    $sql = "
        SELECT id, prefix, digit_length, next_no
        FROM transaction_numbering
        WHERE transaction_code = '" . db_addslashes($transactionCode) . "'
          AND is_active = 1
        LIMIT 1
    ";

    $rs = DB::Query($sql);
    $data = $rs ? $rs->fetchAssoc() : null;

    if (!$data) {
        return "";
    }

    $number = $data["prefix"] .
        str_pad((int)$data["next_no"], (int)$data["digit_length"], "0", STR_PAD_LEFT);

    DB::Exec("
        UPDATE transaction_numbering
        SET next_no = next_no + 1
        WHERE id = " . (int)$data["id"]
    );

    return $number;
}

$userName = $_SESSION["UserID"];

$sqlUser = "
    SELECT 
        u.mother_facility_id,
        u.warehouse_id,
        mf.facility_code,
        mf.facility_name,
        w.warehouse_code,
        w.name AS warehouse_name
    FROM users u
    LEFT JOIN mother_facility mf ON mf.id = u.mother_facility_id
    LEFT JOIN warehouse w ON w.id = u.warehouse_id
    WHERE u.username = '" . db_addslashes($userName) . "'
    LIMIT 1
";

$rsUser = DB::Query($sqlUser);
$dataUser = $rsUser ? $rsUser->fetchAssoc() : null;

if (!$dataUser) {
    $message = "User mother facility and warehouse setup not found.";
    return false;
}

$qaNo = getTxnNumber("QA");
$batchNo = getTxnNumber("BATCH");
$vbnSeq = getTxnNumber("VBN");

$vbnSeqOnly = preg_replace('/[^0-9]/', '', $vbnSeq);

$vbn =
    $dataUser["facility_code"] . "-" .
    $dataUser["warehouse_code"] . "-" .
    date("Y") . "-" .
    $vbnSeqOnly;

$values["qa_no"] = $qaNo;
$values["receiving_report_no"] = $qaNo;
$values["batch_no"] = $batchNo;
$values["vbn"] = $vbn;

$values["mother_facility_id"] = (int)$dataUser["mother_facility_id"];
$values["receiving_warehouse_id"] = (int)$dataUser["warehouse_id"];
$values["receiving_warehouse_name"] = $dataUser["warehouse_name"];

$delivered = isset($values["delivered_quantity"]) ? (float)$values["delivered_quantity"] : 0;
$accepted = isset($values["accepted_quantity"]) ? (float)$values["accepted_quantity"] : 0;
$rejected = isset($values["rejected_quantity"]) ? (float)$values["rejected_quantity"] : 0;

if ($delivered > 0) {
    $values["average_acceptance_rate"] = round(($accepted / $delivered) * 100, 2);
    $values["average_rejection_rate"] = round(($rejected / $delivered) * 100, 2);
} else {
    $values["average_acceptance_rate"] = 0;
    $values["average_rejection_rate"] = 0;
}

// QA Incoming Goods does not require approval.
// Automatically mark the record as APPROVED before saving.
$values["approval_status"] = "APPROVED";

return true;
		;
		return true;
	}

	function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		$delivered = isset($values["delivered_quantity"]) ? (float)$values["delivered_quantity"] : 0;
$accepted = isset($values["accepted_quantity"]) ? (float)$values["accepted_quantity"] : 0;
$rejected = isset($values["rejected_quantity"]) ? (float)$values["rejected_quantity"] : 0;

if ($delivered > 0) {
    $values["average_acceptance_rate"] = round(($accepted / $delivered) * 100, 2);
    $values["average_rejection_rate"] = round(($rejected / $delivered) * 100, 2);
} else {
    $values["average_acceptance_rate"] = 0;
    $values["average_rejection_rate"] = 0;
}

// QA Incoming Goods does not require approval.
// Automatically mark the record as APPROVED before saving.
$values["approval_status"] = "APPROVED";

// ======================================================
// QA INCOMING GOODS
// AFTER RECORD UPDATED
//
// Do not regenerate criteria during ordinary editing.
// Regenerate only when the selected item changes.
// ======================================================

$qaId = isset($keys["id"])
    ? intval($keys["id"])
    : 0;

if ($qaId <= 0) {
    return;
}

$oldItemId = isset($oldvalues["item_id"])
    ? intval($oldvalues["item_id"])
    : 0;

$newItemId = intval(
    DBLookup(
        "SELECT item_id
         FROM qa_incoming_goods
         WHERE id = " . $qaId
    )
);

// ------------------------------------------------------
// Update sample quantity and sample unit
// without deleting inspection results
// ------------------------------------------------------

$sqlQa = "
    SELECT
        total_sample_inspected,
        unit
    FROM qa_incoming_goods
    WHERE id = " . $qaId . "
    LIMIT 1
";

$rsQa = DB::Query($sqlQa);
$qa = $rsQa ? $rsQa->fetchAssoc() : null;

if ($qa) {

    $sampleQuantity = floatval(
        $qa["total_sample_inspected"]
    );

    $sampleUnit = db_addslashes(
        (string)$qa["unit"]
    );

    DB::Exec("
        UPDATE qa_incoming_goods_detail
        SET
            sample_quantity = " .
                $sampleQuantity . ",

            sample_unit = '" .
                $sampleUnit . "',

            updatedAt = NOW()

        WHERE qa_incoming_goods_id = " .
            $qaId
    );
}

// Do not erase entered results when the item is unchanged.
if (
    $newItemId <= 0 ||
    $newItemId === $oldItemId
) {
    return;
}

// ------------------------------------------------------
// Resolve the new Parent Item
// ------------------------------------------------------

$sqlItem = "
    SELECT
        id,
        name,
        COALESCE(
            parent_item_id,
            id
        ) AS criteria_parent_item_id
    FROM item
    WHERE id = " . $newItemId . "
    LIMIT 1
";

$rsItem = DB::Query($sqlItem);
$item = $rsItem
    ? $rsItem->fetchAssoc()
    : null;

if (!$item) {
    return;
}

$criteriaParentItemId = intval(
    $item["criteria_parent_item_id"]
);

$itemName = db_addslashes(
    (string)$item["name"]
);

$sampleQuantity = $qa
    ? floatval(
        $qa["total_sample_inspected"]
    )
    : 0;

$sampleUnit = $qa
    ? db_addslashes(
        (string)$qa["unit"]
    )
    : "";

// ------------------------------------------------------
// Remove the old item's criteria
// ------------------------------------------------------

DB::Exec(
    "DELETE FROM qa_incoming_goods_detail
     WHERE qa_incoming_goods_id = " .
     $qaId
);

// ------------------------------------------------------
// Load the new Parent Item criteria
// ------------------------------------------------------

$sqlInsertCriteria = "
    INSERT INTO qa_incoming_goods_detail
    (
        qa_incoming_goods_id,
        item_id,
        item_name,
        criteria_id,
        criteria_code,
        sample_quantity,
        sample_unit,
        criteria_description,
        expected_result,
        inspection_method,
        inspection_result,
        remarks_about_quality,
        sort_order,
        createdAt,
        updatedAt
    )

    SELECT
        " . $qaId . ",
        " . $newItemId . ",
        '" . $itemName . "',
        c.id,
        c.criteria_code,
        " . $sampleQuantity . ",
        '" . $sampleUnit . "',
        c.criteria_description,
        c.expected_result,
        c.inspection_method,
        'PASSED',
        NULL,
        c.sort_order,
        NOW(),
        NOW()

    FROM qa_item_criteria c

    WHERE c.item_id = " .
        $criteriaParentItemId . "

      AND c.qa_module =
          'INCOMING_GOODS'

      AND c.status =
          'ACTIVE'

    ORDER BY
        c.sort_order,
        c.id
";

DB::Exec($sqlInsertCriteria);
return true;
		;
		return true;
	}

	function BeforeShowEdit( &$xt, &$templatefile, $values, $pageObject ) {
		// ==========================================================
// IDENTIFY SOURCE TYPE
// ==========================================================

$sourceType = isset($data["source_transaction_type"])
    ? strtoupper(trim($data["source_transaction_type"]))
    : "";

$isPo = in_array(
    $sourceType,
    array("PO_RECEIVING", "PURCHASE_ORDER")
);

$isDonation = in_array(
    $sourceType,
    array("DONATION_RECEIVING", "DONATION")
);

$pageObject->setProxyValue(
    "is_po",
    $isPo ? 1 : 0
);

$pageObject->setProxyValue(
    "is_donation",
    $isDonation ? 1 : 0
);


// ==========================================================
// SHELF-LIFE MAP
// ==========================================================

$itemShelfLife = array();

$rsItem = DB::Query("
    SELECT
        id,
        shelf_life_days
    FROM item
    WHERE shelf_life_days IS NOT NULL
      AND shelf_life_days > 0
");

while ($rsItem && ($row = $rsItem->fetchAssoc())) {

    $itemShelfLife[(int)$row["id"]] =
        (int)$row["shelf_life_days"];
}

$pageObject->setProxyValue(
    "item_shelf_life",
    $itemShelfLife
);


		;
		
	}

	function AfterAdd( &$values, &$keys, $inline, $pageObject ) {
		// ======================================================
// QA INCOMING GOODS
// AFTER RECORD ADDED
//
// Load criteria based on the selected item's Parent Item.
// ======================================================

$qaId = isset($keys["id"])
    ? intval($keys["id"])
    : 0;

if ($qaId <= 0) {
    return;
}

// ------------------------------------------------------
// Get the saved QA Incoming record
// ------------------------------------------------------

$sqlQa = "
    SELECT
        item_id,
        item_name,
        total_sample_inspected,
        unit
    FROM qa_incoming_goods
    WHERE id = " . $qaId . "
    LIMIT 1
";

$rsQa = DB::Query($sqlQa);
$qa = $rsQa ? $rsQa->fetchAssoc() : null;

if (!$qa) {
    return;
}

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

if ($itemId <= 0) {
    return;
}

// ------------------------------------------------------
// Resolve the Parent Item
//
// Child item:
//     use parent_item_id
//
// Parent item:
//     use its own id
// ------------------------------------------------------

$sqlItem = "
    SELECT
        i.id,
        i.name,
        COALESCE(
            i.parent_item_id,
            i.id
        ) AS criteria_parent_item_id
    FROM item i
    WHERE i.id = " . $itemId . "
    LIMIT 1
";

$rsItem = DB::Query($sqlItem);
$item = $rsItem
    ? $rsItem->fetchAssoc()
    : null;

if (!$item) {
    return;
}

$criteriaParentItemId = intval(
    $item["criteria_parent_item_id"]
);

$itemName = db_addslashes(
    (string)$item["name"]
);

$sampleQuantity = floatval(
    $qa["total_sample_inspected"]
);

$sampleUnit = db_addslashes(
    (string)$qa["unit"]
);

// ------------------------------------------------------
// Avoid duplicated detail rows
// ------------------------------------------------------

DB::Exec(
    "DELETE FROM qa_incoming_goods_detail
     WHERE qa_incoming_goods_id = " . $qaId
);

// ------------------------------------------------------
// Copy the Parent Item criteria to QA detail
// ------------------------------------------------------

$sqlInsertCriteria = "
    INSERT INTO qa_incoming_goods_detail
    (
        qa_incoming_goods_id,
        item_id,
        item_name,
        criteria_id,
        criteria_code,
        sample_quantity,
        sample_unit,
        criteria_description,
        expected_result,
        inspection_method,
        inspection_result,
        remarks_about_quality,
        sort_order,
        createdAt,
        updatedAt
    )

    SELECT
        " . $qaId . ",
        " . $itemId . ",
        '" . $itemName . "',
        c.id,
        c.criteria_code,
        " . $sampleQuantity . ",
        '" . $sampleUnit . "',
        c.criteria_description,
        c.expected_result,
        c.inspection_method,
        'PASSED',
        NULL,
        c.sort_order,
        NOW(),
        NOW()

    FROM qa_item_criteria c

    WHERE c.item_id = " .
        $criteriaParentItemId . "

      AND c.qa_module =
          'INCOMING_GOODS'

      AND c.status =
          'ACTIVE'

    ORDER BY
        c.sort_order,
        c.id
";

DB::Exec($sqlInsertCriteria);
		;
		
	}
	public function default_inspection_date_efedit(  ) {
	$defaultValue = Now();
return $defaultValue;
}

public function custom_print_vfview( $value, $data ) {
	
$value = "<a href='" . $_SESSION["path"] . "frameset?__report=BoxBarcode_DSWD.rptdesign&txnid=".$data['id']."&ea=".$_SESSION["ea"]."&&__dpi=96&__format=pdf&__pageoverflow=2&__overwrite=false'>Print</a>";

;
return $value;
}

public function custom_batch_barcode_vfview( $value, $data ) {
	
$value = "<a href='" . $_SESSION["path"] . "frameset?__report=BoxBarcode_DSWD.rptdesign&txnid=".$data['id']."&ea=".$_SESSION["ea"]."&&__dpi=96&__format=pdf&__pageoverflow=2&__overwrite=false'>Print</a>";

;
return $value;
}	

}


?>