<?php
class class_GlobalEvents extends GlobalEventsBase
{
	function init() {
		$this->events = array(
	'pageEvents' => array(
		'AfterSuccessfulLogin' => true,
		'AfterLogout' => true,
		'ModifyMenu' => true 
	),
	'onScreenEvents' => array(
		'15997' => true 
	),
	'dashboardEvents' => array(
		 
	),
	'buttons' => array(
		 
	),
	'maps' => array(
		 
	),
	'tablePermissions' => array(
		 
	),
	'recordEditable' => array(
		 
	) 
);
	}

		function AfterSuccessfulLogin( $username, $password, &$data, $pageObject ) {
		// ============================================================
// BUILDLEDGER CORE - AFTER SUCCESSFUL LOGIN
// PHPRunner connections:
//   Platform      = central buildledger_platform database
//   TenantRuntime = dynamically selected tenant database
// ============================================================


// ------------------------------------------------------------
// 1. Clear any previous BuildLedger tenant context
// ------------------------------------------------------------
unset(
    $_SESSION["tenant_id"],
    $_SESSION["tenant_name"],
    $_SESSION["tenant_dbname"],
    $_SESSION["tenant_role_code"],
    $_SESSION["tenant_is_owner"],
    $_SESSION["active_suites"],
    $_SESSION["company_id"],
    $_SESSION["company_name"],
    $_SESSION["branch_id"],
    $_SESSION["branch_name"],
    $_SESSION["company_context_loaded"]
);


// ------------------------------------------------------------
// 2. Save the authenticated Platform user
// ------------------------------------------------------------
$userId = isset($data["id"])
    ? (int)$data["id"]
    : 0;

$_SESSION["platform_user_id"] = $userId;

$_SESSION["user_email"] = isset($data["email"])
    ? $data["email"]
    : "";

$_SESSION["display_name"] = isset($data["display_name"])
    ? $data["display_name"]
    : "";


// ------------------------------------------------------------
// 3. Validate the Platform user
// ------------------------------------------------------------
if ($userId <= 0) {
    Security::logout();

    header(
        "Location: login.php?message=" .
        urlencode("Unable to identify the BuildLedger user.")
    );

    exit();
}

$userStatus = isset($data["status"])
    ? strtoupper(trim($data["status"]))
    : "ACTIVE";

if ($userStatus !== "ACTIVE") {
    Security::logout();

    header(
        "Location: login.php?message=" .
        urlencode(
            "Your BuildLedger account is inactive. " .
            "Please contact your administrator."
        )
    );

    exit();
}


// ------------------------------------------------------------
// 4. Use the central Platform connection
// ------------------------------------------------------------
DB::SetConnection("Platform");


// ------------------------------------------------------------
// 5. Find the user's default active tenant
// ------------------------------------------------------------
$tenantSql = "
    SELECT
        tm.tenant_id,
        tm.role_code,
        tm.is_owner,
        tm.is_default_tenant,

        t.tenant_name,
        t.status AS tenant_status,

        td.database_name,
        td.database_status

    FROM tenant_membership tm

    INNER JOIN tenant t
        ON t.id = tm.tenant_id

    INNER JOIN tenant_database td
        ON td.tenant_id = tm.tenant_id

    WHERE tm.user_id = " . $userId . "
      AND tm.membership_status = 'ACTIVE'
      AND t.status = 'ACTIVE'
      AND td.database_status = 'READY'

    ORDER BY
        tm.is_default_tenant DESC,
        tm.id ASC

    LIMIT 1
";

$tenantRs = DB::Query($tenantSql);
$tenant = $tenantRs->fetchAssoc();

if (!$tenant) {
    Security::logout();

    header(
        "Location: login.php?message=" .
        urlencode(
            "No active BuildLedger organization is assigned " .
            "to this user."
        )
    );

    exit();
}


// ------------------------------------------------------------
// 6. Save the selected tenant context
// ------------------------------------------------------------
$_SESSION["tenant_id"] =
    (int)$tenant["tenant_id"];

$_SESSION["tenant_name"] =
    $tenant["tenant_name"];

$_SESSION["tenant_dbname"] =
    $tenant["database_name"];

$_SESSION["tenant_role_code"] =
    isset($tenant["role_code"])
        ? $tenant["role_code"]
        : "";

$_SESSION["tenant_is_owner"] =
    isset($tenant["is_owner"])
        ? (int)$tenant["is_owner"]
        : 0;


// ------------------------------------------------------------
// 7. Load active purchased suites
// ------------------------------------------------------------
$_SESSION["active_suites"] = array();

$suiteSql = "
    SELECT
        suite_code

    FROM vw_tenant_active_suites

    WHERE tenant_id = " .
        (int)$_SESSION["tenant_id"] . "

    ORDER BY suite_id
";

$suiteRs = DB::Query($suiteSql);

while ($suite = $suiteRs->fetchAssoc()) {
    $_SESSION["active_suites"][] =
        $suite["suite_code"];
}


// Core is required and must always be available.
if (
    !in_array(
        "CORE_PLATFORM",
        $_SESSION["active_suites"],
        true
    )
) {
    $_SESSION["active_suites"][] =
        "CORE_PLATFORM";
}


// ------------------------------------------------------------
// 8. Switch to the selected tenant database
// ------------------------------------------------------------
// TenantRuntime uses $_SESSION["tenant_dbname"] as its database.
DB::SetConnection("TenantRuntime");


// ------------------------------------------------------------
// 9. Load the user's default company and branch
// ------------------------------------------------------------
$accessSql = "
    SELECT
        cua.company_id,
        cua.branch_id,
        cua.is_default_company,

        c.registered_name,

        b.branch_name

    FROM company_user_access cua

    INNER JOIN company c
        ON c.id = cua.company_id

    LEFT JOIN branch b
        ON b.id = cua.branch_id

    WHERE cua.platform_user_id = " . $userId . "
      AND cua.access_status = 'ACTIVE'
      AND c.status = 'ACTIVE'
      AND (
            b.id IS NULL
            OR b.status = 'ACTIVE'
          )

    ORDER BY
        cua.is_default_company DESC,
        cua.id ASC

    LIMIT 1
";

$accessRs = DB::Query($accessSql);
$access = $accessRs->fetchAssoc();

if (!$access) {
    // Return to the central database before logging out.
    DB::SetConnection("Platform");

    Security::logout();

    header(
        "Location: login.php?message=" .
        urlencode(
            "No active company access is assigned " .
            "to this user."
        )
    );

    exit();
}


// ------------------------------------------------------------
// 10. Save company and branch context
// ------------------------------------------------------------
$_SESSION["company_id"] =
    (int)$access["company_id"];

$_SESSION["company_name"] =
    $access["registered_name"];

if (
    isset($access["branch_id"]) &&
    $access["branch_id"] !== null &&
    $access["branch_id"] !== ""
) {
    $_SESSION["branch_id"] =
        (int)$access["branch_id"];

    $_SESSION["branch_name"] =
        isset($access["branch_name"])
            ? $access["branch_name"]
            : "";
} else {
    $_SESSION["branch_id"] = null;

    $_SESSION["branch_name"] =
        "All permitted branches";
}

$_SESSION["company_context_loaded"] = 1;


// ------------------------------------------------------------
// 11. Return to the central Platform connection
// ------------------------------------------------------------
DB::SetConnection("Platform");


// ------------------------------------------------------------
// 12. Set the displayed user name
// ------------------------------------------------------------
$displayName = isset($data["display_name"])
    ? trim($data["display_name"])
    : "";

if ($displayName === "") {
    $firstName = isset($data["first_name"])
        ? trim($data["first_name"])
        : "";

    $lastName = isset($data["last_name"])
        ? trim($data["last_name"])
        : "";

    $displayName = trim(
        $firstName . " " . $lastName
    );
}

if ($displayName === "") {
    $displayName = isset($data["email"])
        ? $data["email"]
        : "BuildLedger User";
}

$_SESSION["display_name"] = $displayName;

Security::setDisplayName($displayName);


// ------------------------------------------------------------
// 13. Open the BuildLedger Core menu
// ------------------------------------------------------------
header("Location: menu.php");
exit();
		;
		
	}

	function AfterLogout( $username ) {
		// Clear all BuildLedger user and tenant context.
unset(
    $_SESSION["platform_user_id"],
    $_SESSION["user_email"],
    $_SESSION["display_name"],

    $_SESSION["tenant_id"],
    $_SESSION["tenant_name"],
    $_SESSION["tenant_dbname"],
    $_SESSION["tenant_role_code"],
    $_SESSION["tenant_is_owner"],

    $_SESSION["active_suites"],

    $_SESSION["company_id"],
    $_SESSION["company_name"],
    $_SESSION["branch_id"],
    $_SESSION["branch_name"],
    $_SESSION["company_context_loaded"]
);
		;
		
	}

	function ModifyMenu( &$menu ) {
		$activeSuites = isset($_SESSION["active_suites"])
    ? $_SESSION["active_suites"]
    : array();

$suiteMenuIds = array(
    "FINANCE_COMPLIANCE" => 45,
    "SALES_REVENUE" => 46,
    "COMMERCE_POS" => 47,
    "PROCUREMENT" => 48,
    "INVENTORY_SUPPLY_CHAIN" => 49,
    "PROJECTS_SERVICES" => 50,
    "HCM_PAYROLL" => 51,
    "ASSETS_LOGISTICS" => 52,
    "PLANNING_CONSOLIDATION" => 53
);

foreach ($suiteMenuIds as $suiteCode => $menuItemId) {
    if (!in_array($suiteCode, $activeSuites, true)) {
        $menu->removeItem($menuItemId);
    }
}
		;
		if( $menu->name() == "main" ) {
    // modify main menu here
}
	}
	
	// custom buttons 
	
	// ajax code snippets
	
	
	// field events
	

	// code snippets
		// code snippet - Snippet
	function event_15997(  ) {
		
		$tenantName = isset($_SESSION["tenant_name"])
    ? $_SESSION["tenant_name"]
    : "";

$companyName = isset($_SESSION["company_name"])
    ? $_SESSION["company_name"]
    : "";

$branchName = isset($_SESSION["branch_name"])
    ? $_SESSION["branch_name"]
    : "";

$roleCode = isset($_SESSION["tenant_role_code"])
    ? $_SESSION["tenant_role_code"]
    : "";

echo '<div style="
    width:100%;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    padding:16px 20px;
    background:#ffffff;
    border:1px solid #e2e8f0;
    border-radius:12px;
    box-sizing:border-box;
    box-shadow:0 3px 12px rgba(15,23,42,0.06);
">';

echo '<div>';

echo '<div style="
    font-size:18px;
    font-weight:700;
    color:#102a4c;
    margin-bottom:3px;
">';

echo htmlspecialchars(
    $companyName,
    ENT_QUOTES,
    "UTF-8"
);

echo '</div>';

echo '<div style="
    font-size:13px;
    color:#64748b;
">';

echo htmlspecialchars(
    $tenantName,
    ENT_QUOTES,
    "UTF-8"
);

if ($branchName !== "") {
    echo ' · ';

    echo htmlspecialchars(
        $branchName,
        ENT_QUOTES,
        "UTF-8"
    );
}

echo '</div>';
echo '</div>';

echo '<div style="
    text-align:right;
">';

echo '<div style="
    font-size:12px;
    color:#64748b;
">Current role</div>';

echo '<div style="
    font-size:13px;
    font-weight:600;
    color:#334155;
">';

echo htmlspecialchars(
    $roleCode,
    ENT_QUOTES,
    "UTF-8"
);

echo '</div>';
echo '</div>';

echo '</div>';
		;
		
	}

}
?>
