<?php
class eventclass_workforce_assignment_place  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'BeforeAdd' => true,
	'BeforeEdit' => 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 BeforeAdd( &$values, &$sqlValues, &$message, $inline, $pageObject ) {
		// ======================================================
// WORKFORCE ASSIGNMENT PLACE
// BEFORE RECORD ADDED
//
// Authoritative facility:
// Logged-in user's mother facility / DRC
// ======================================================

$username = Security::getUserName();

if ($username === "") {

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

    return false;
}

$safeUsername = db_addslashes(
    $username
);

$sqlUserFacility = "
    SELECT
        u.mother_facility_id,
        mf.facility_code,
        mf.facility_name,
        mf.facility_type
    FROM users u

    INNER JOIN mother_facility mf
        ON mf.id = u.mother_facility_id

    WHERE u.username = '" .
        $safeUsername . "'

      AND u.active = 1
      AND mf.status = 'ACTIVE'
      AND mf.facility_type IN
          ('DRC', 'LDRC')

    LIMIT 1
";

$rsUserFacility = DB::Query(
    $sqlUserFacility
);

$userFacility = $rsUserFacility
    ? $rsUserFacility->fetchAssoc()
    : null;

if (!$userFacility) {

    $message =
        "Your account is not assigned to an active DRC. " .
        "Please contact the system administrator.";

    return false;
}

$facilityId = intval(
    $userFacility["mother_facility_id"]
);

$placeName = strtoupper(
    trim(
        (string)(
            $values["place_name"] ?? ""
        )
    )
);

if ($placeName === "") {

    $message =
        "Place of Assignment is required.";

    return false;
}

$values["mother_facility_id"] =
    $facilityId;

$values["place_name"] =
    $placeName;

$values["place_code"] = strtoupper(
    trim(
        (string)(
            $values["place_code"] ?? ""
        )
    )
);

if (
    !isset($values["is_active"]) ||
    $values["is_active"] === ""
) {
    $values["is_active"] = 1;
}

if (
    !isset($values["sort_order"]) ||
    intval($values["sort_order"]) <= 0
) {
    $values["sort_order"] = 10;
}

// Prevent duplicate places within the same DRC.

$safePlaceName = db_addslashes(
    $placeName
);

$duplicateId = DBLookup(
    "SELECT id
     FROM workforce_assignment_place
     WHERE mother_facility_id = " .
        $facilityId . "
       AND UPPER(TRIM(place_name)) =
           UPPER(TRIM('" .
               $safePlaceName . "'))
     LIMIT 1"
);

if ($duplicateId) {

    $message =
        "This Place of Assignment already exists " .
        "for your DRC.";

    return false;
}

$dateNow = new DateTime(
    "now",
    new DateTimeZone("Asia/Manila")
);

$currentDateTime =
    $dateNow->format("Y-m-d H:i:s");

$values["created_by"] =
    $username;

$values["createdAt"] =
    $currentDateTime;

$values["updated_by"] =
    $username;

$values["updatedAt"] =
    $currentDateTime;

return true;
		;
		return true;
	}

	function BeforeEdit( &$values, &$sqlValues, $where, &$oldvalues, &$keys, &$message, $inline, $pageObject ) {
		// ======================================================
// WORKFORCE ASSIGNMENT PLACE
// BEFORE RECORD UPDATED
// ======================================================

$recordId = intval(
    $keys["id"] ?? 0
);

if ($recordId <= 0) {

    $message =
        "Unable to identify the assignment place.";

    return false;
}

$username = Security::getUserName();

$safeUsername = db_addslashes(
    $username
);

$sqlUserFacility = "
    SELECT
        u.mother_facility_id
    FROM users u

    INNER JOIN mother_facility mf
        ON mf.id = u.mother_facility_id

    WHERE u.username = '" .
        $safeUsername . "'

      AND u.active = 1
      AND mf.status = 'ACTIVE'
      AND mf.facility_type IN
          ('DRC', 'LDRC')

    LIMIT 1
";

$rsUserFacility = DB::Query(
    $sqlUserFacility
);

$userFacility = $rsUserFacility
    ? $rsUserFacility->fetchAssoc()
    : null;

if (!$userFacility) {

    $message =
        "Your account is not assigned to an active DRC.";

    return false;
}

$facilityId = intval(
    $userFacility["mother_facility_id"]
);

// Confirm that the record belongs to the user's DRC.

$recordFacilityId = intval(
    DBLookup(
        "SELECT mother_facility_id
         FROM workforce_assignment_place
         WHERE id = " . $recordId
    )
);

if ($recordFacilityId !== $facilityId) {

    $message =
        "You cannot update a place belonging " .
        "to another DRC.";

    return false;
}

$placeName = strtoupper(
    trim(
        (string)(
            $values["place_name"]
            ?? $oldvalues["place_name"]
            ?? ""
        )
    )
);

if ($placeName === "") {

    $message =
        "Place of Assignment is required.";

    return false;
}

$safePlaceName = db_addslashes(
    $placeName
);

$duplicateId = DBLookup(
    "SELECT id
     FROM workforce_assignment_place
     WHERE mother_facility_id = " .
        $facilityId . "
       AND UPPER(TRIM(place_name)) =
           UPPER(TRIM('" .
               $safePlaceName . "'))
       AND id <> " . $recordId . "
     LIMIT 1"
);

if ($duplicateId) {

    $message =
        "This Place of Assignment already exists " .
        "for your DRC.";

    return false;
}

// Do not permit transfer to another DRC.

$values["mother_facility_id"] =
    $facilityId;

$values["place_name"] =
    $placeName;

if (isset($values["place_code"])) {

    $values["place_code"] = strtoupper(
        trim(
            (string)$values["place_code"]
        )
    );
}

$dateNow = new DateTime(
    "now",
    new DateTimeZone("Asia/Manila")
);

$values["updated_by"] =
    $username;

$values["updatedAt"] =
    $dateNow->format("Y-m-d H:i:s");

return true;
		;
		return true;
	}
		

}


?>