<?php
class eventclass_item2  extends TableEventsBase {
	
	function init() {
		$this->events = array(
	'OnPageLoad' => true,
	'BeforeAdd' => true,
	'AfterEdit' => 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 ) {
		// Place event code here.
// Use "Add Action" button to add code snippets.
// Auto-populate priority only for subcategory_id = 5
if (isset($values["subcategory_id"]) && $values["subcategory_id"] == 5) {

    $sql = "
        SELECT IFNULL(MAX(priority), 0) + 1 AS next_priority
        FROM item
        WHERE subcategory_id = 5
    ";

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

    $values["priority"] = $data["next_priority"];
}
return true;
		;
		return true;
	}

	function AfterEdit( &$values, $where, &$oldvalues, &$keys, $inline, $pageObject ) {
		// Place event code here.
// Use "Add Action" button to add code snippets.

if (isset($values["subcategory_id"]) && $values["subcategory_id"] == 5) {

    // Only auto-assign if priority is empty
    if (empty($values["priority"])) {

        $sql = "
            SELECT IFNULL(MAX(priority), 0) + 1 AS next_priority
            FROM item
            WHERE subcategory_id = 5
              AND id <> ".$keys["id"];

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

        $values["priority"] = $data["next_priority"];
    }
}
		;
		
	}
		

}


?>