<?php
class eventclass_augmentation_request1  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeShowAdd' => true,
	'OnPageLoad' => true,
	'BeforeAdd' => true 
);
		$this->fieldValues = array(
	'filterLimit' => array(
		 
	),
	'mapIcon' => array(
		 
	),
	'viewCustom' => array(
		 
	),
	'lookupWhere' => array(
		 
	),
	'viewFileText' => array(
		 
	),
	'defaultValue' => array(
		'office_bureau' => array(
			'edit' => true 
		) 
	),
	'autoUpdateValue' => array(
		 
	),
	'uploadFolder' => array(
		 
	),
	'viewPluginInit' => array(
		 
	),
	'editPluginInit' => array(
		 
	) 
);
			}
		function BeforeShowAdd( &$xt, &$templatefile, $pageObject ) {
		// ======================================================
// AUGMENTATION REQUEST - ADD PAGE - BEFORE DISPLAY
// Preview Request Number
// Current Date
// Logged-in User Mother Facility
// ======================================================

// ------------------------------------------------------
// Current Philippine date
// ------------------------------------------------------
$dateNow = new DateTime(
    "now",
    new DateTimeZone("Asia/Manila")
);

$currentDate = $dateNow->format("Y-m-d");

// ------------------------------------------------------
// Transaction numbering
//
// Important:
// transaction_code = AR
// prefix           = RIS
//
// Example output:
// RIS00004
// ------------------------------------------------------
$transactionCode = "AR";

$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);

$previewReferenceNo = "";

if ($rs) {

    $data = $rs->fetchAssoc();

    if ($data) {

        $prefix = trim($data["prefix"]);
        $digitLength = (int)$data["digit_length"];
        $nextNo = (int)$data["next_no"];

        if ($digitLength <= 0) {
            $digitLength = 5;
        }

        if ($nextNo <= 0) {
            $nextNo = 1;
        }

        $previewReferenceNo =
            $prefix .
            str_pad(
                $nextNo,
                $digitLength,
                "0",
                STR_PAD_LEFT
            );
    }
}

// ------------------------------------------------------
// Get logged-in user's Mother Facility
// ------------------------------------------------------
$username = Security::getUserName();

$loggedUserId = 0;
$motherFacilityId = 0;

if ($username != "") {

    $sqlUser = "
        SELECT
            ID,
            mother_facility_id
        FROM users
        WHERE username = '" .
            db_addslashes($username) . "'
        LIMIT 1
    ";

    $rsUser = DB::Query($sqlUser);

    if ($rsUser) {

        $userData = $rsUser->fetchAssoc();

        if ($userData) {

            $loggedUserId =
                (int)$userData["ID"];

            $motherFacilityId =
                (int)$userData["mother_facility_id"];
        }
    }
}

// ------------------------------------------------------
// Send values to JavaScript
// ------------------------------------------------------
$pageObject->setProxyValue(
    "preview_reference_number",
    $previewReferenceNo
);

$pageObject->setProxyValue(
    "current_request_date",
    $currentDate
);

$pageObject->setProxyValue(
    "logged_user_mother_facility_id",
    $motherFacilityId
);

$pageObject->setProxyValue(
    "logged_user_id",
    $loggedUserId
);
		;
		
	}

	function BeforeAdd( &$values, &$sqlValues, &$message, $inline, $pageObject ) {
		// ======================================================
// AUGMENTATION REQUEST - BEFORE RECORD ADDED
//
// Authoritative server-side values:
// 1. Request Number
// 2. Request Date
// 3. Mother Facility
// 4. Created By
// ======================================================

// ------------------------------------------------------
// Current Philippine date
// ------------------------------------------------------
$dateNow = new DateTime(
    "now",
    new DateTimeZone("Asia/Manila")
);

$currentDate = $dateNow->format("Y-m-d");

// ------------------------------------------------------
// Get logged-in user
// ------------------------------------------------------
$username = Security::getUserName();

if ($username == "") {

    $message =
        "Unable to identify the logged-in user.";

    return false;
}

$sqlUser = "
    SELECT
        ID,
        mother_facility_id
    FROM users
    WHERE username = '" .
        db_addslashes($username) . "'
    LIMIT 1
";

$rsUser = DB::Query($sqlUser);

if (!$rsUser) {

    $message =
        "Unable to retrieve the logged-in user.";

    return false;
}

$userData = $rsUser->fetchAssoc();

if (!$userData) {

    $message =
        "The logged-in user was not found.";

    return false;
}

$loggedUserId =
    (int)$userData["ID"];

$motherFacilityId =
    (int)$userData["mother_facility_id"];

if ($motherFacilityId <= 0) {

    $message =
        "Your account has no assigned Mother Facility. " .
        "Please update the Mother Facility in the user account.";

    return false;
}

// ------------------------------------------------------
// Validate Mother Facility
// ------------------------------------------------------
$sqlFacility = "
    SELECT
        id,
        facility_code,
        facility_name,
        status
    FROM mother_facility
    WHERE id = " . $motherFacilityId . "
    LIMIT 1
";

$rsFacility = DB::Query($sqlFacility);

if (!$rsFacility) {

    $message =
        "Unable to validate the assigned Mother Facility.";

    return false;
}

$facilityData = $rsFacility->fetchAssoc();

if (!$facilityData) {

    $message =
        "The assigned Mother Facility does not exist.";

    return false;
}

if (
    isset($facilityData["status"]) &&
    strtoupper(trim($facilityData["status"])) == "INACTIVE"
) {

    $message =
        "The Mother Facility assigned to your account is inactive.";

    return false;
}

// ------------------------------------------------------
// Allocate request number
//
// transaction_code = AR
// prefix = RIS
// ------------------------------------------------------
$transactionCode = "AR";

// Atomically increase next_no.
//
// LAST_INSERT_ID receives the new next_no.
// Subtract one to get the number allocated to this record.
// ------------------------------------------------------
$sqlUpdateNumber = "
    UPDATE transaction_numbering
    SET
        next_no = LAST_INSERT_ID(next_no + 1),
        updated_at = NOW()
    WHERE transaction_code = '" .
        db_addslashes($transactionCode) . "'
      AND is_active = 1
";

DB::Exec($sqlUpdateNumber);

$rsAllocated = DB::Query("
    SELECT LAST_INSERT_ID() AS new_next_no
");

if (!$rsAllocated) {

    $message =
        "Unable to allocate the Augmentation Request number.";

    return false;
}

$allocatedData = $rsAllocated->fetchAssoc();

$newNextNo =
    isset($allocatedData["new_next_no"])
        ? (int)$allocatedData["new_next_no"]
        : 0;

$allocatedNo = $newNextNo - 1;

if ($allocatedNo <= 0) {

    $message =
        "Transaction numbering for Augmentation Request is not configured.";

    return false;
}

// ------------------------------------------------------
// Retrieve prefix and digit length
// ------------------------------------------------------
$sqlNumbering = "
    SELECT
        prefix,
        digit_length
    FROM transaction_numbering
    WHERE transaction_code = '" .
        db_addslashes($transactionCode) . "'
      AND is_active = 1
    LIMIT 1
";

$rsNumbering = DB::Query($sqlNumbering);

if (!$rsNumbering) {

    $message =
        "Unable to retrieve the Augmentation Request numbering setup.";

    return false;
}

$numberingData = $rsNumbering->fetchAssoc();

if (!$numberingData) {

    $message =
        "Augmentation Request numbering is not configured.";

    return false;
}

$prefix =
    trim($numberingData["prefix"]);

$digitLength =
    (int)$numberingData["digit_length"];

if ($digitLength <= 0) {
    $digitLength = 5;
}

$finalRequestNo =
    $prefix .
    str_pad(
        $allocatedNo,
        $digitLength,
        "0",
        STR_PAD_LEFT
    );

// ------------------------------------------------------
// Make sure generated number is unique
// ------------------------------------------------------
$sqlExisting = "
    SELECT augmentation_request_id
    FROM augmentation_request
    WHERE request_no = '" .
        db_addslashes($finalRequestNo) . "'
    LIMIT 1
";

$rsExisting = DB::Query($sqlExisting);

if ($rsExisting) {

    $existingData = $rsExisting->fetchAssoc();

    if ($existingData) {

        $message =
            "The generated Request Number " .
            $finalRequestNo .
            " already exists. Please check transaction numbering.";

        return false;
    }
}

// ------------------------------------------------------
// Force automatic values
// ------------------------------------------------------
$values["request_no"] =
    $finalRequestNo;

$values["request_date"] =
    $currentDate;

$values["mother_facility_id"] =
    $motherFacilityId;

$values["created_by"] =
    $loggedUserId;

$values["updated_by"] =
    $loggedUserId;

// Default source for manually encoded internal requests
if (
    !isset($values["request_channel"]) ||
    trim($values["request_channel"]) == ""
) {
    $values["request_channel"] = "internal";
}

return true;
		;
		return true;
	}
	public function default_office_bureau_efedit(  ) {
	$defaultValue = DRMB;
return $defaultValue;
}	

}


?>