<?php
/* Copyright (C) 2023 László Szollősi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * \file    core/triggers/interface_99_modSettlements_SettlementsTriggers.class.php
 * \ingroup settlements
 * \brief   Example trigger.
 *
 * Put detailed description here.
 *
 * \remarks You can create other triggers by copying this one.
 * - File name should be either:
 *      - interface_99_modSettlements_MyTrigger.class.php
 *      - interface_99_all_MyTrigger.class.php
 * - The file must stay in core/triggers
 * - The class name must be InterfaceMytrigger
 */

require_once DOL_DOCUMENT_ROOT . '/core/triggers/dolibarrtriggers.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/usernaplo.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/groupusers.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/grouphotels.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/usergrouptoolgroupnaplo.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/usergrouptoolgroup.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/settlements/class/grouptools.class.php';



/**
 *  Class of triggers for Settlements module
 */
class InterfaceSettlementsTriggers extends DolibarrTriggers
{
	/**
	 * Constructor
	 *
	 * @param DoliDB $db Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;

		$this->name = preg_replace('/^Interface/i', '', get_class($this));
		$this->family = "demo";
		$this->description = "Settlements triggers.";
		// 'development', 'experimental', 'dolibarr' or version
		$this->version = 'development';
		$this->picto = 'settlements@settlements';
	}

	/**
	 * Trigger name
	 *
	 * @return string Name of trigger file
	 */
	public function getName()
	{
		return $this->name;
	}

	/**
	 * Trigger description
	 *
	 * @return string Description of trigger file
	 */
	public function getDesc()
	{
		return $this->description;
	}


	/**
	 * Function called when a Dolibarrr business event is done.
	 * All functions "runTrigger" are triggered if file
	 * is inside directory core/triggers
	 *
	 * @param string 		$action 	Event action code
	 * @param CommonObject 	$object 	Object
	 * @param User 			$user 		Object user
	 * @param Translate 	$langs 		Object langs
	 * @param Conf 			$conf 		Object conf
	 * @return int              		<0 if KO, 0 if no triggered ran, >0 if OK
	 */
	public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
	{
		if (empty($conf->settlements) || empty($conf->settlements->enabled)) {
			return 0; // If module is not enabled, we do nothing
		}

		// Put here code you want to execute when a Dolibarr business events occurs.
		// Data and type of action are stored into $object and $action

		// You can isolate code for each action in a separate method: this method should be named like the trigger in camelCase.
		// For example : COMPANY_CREATE => public function companyCreate($action, $object, User $user, Translate $langs, Conf $conf)
		$methodName = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($action)))));
		$callback = array($this, $methodName);
		if (is_callable($callback)) {
			dol_syslog(
				"Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id
			);

			return call_user_func($callback, $action, $object, $user, $langs, $conf);
		}
		;

		// Or you can execute some code here
		//print $action;
		//print '<br>';
		//print_r($object);
		//exit;
		switch ($action) {
			case 'GROUP_CREATE':
				global $db, $user;
				$fk_groupid = $object->id;
				$fk_group_entity = $object->fk_entity;
				$group_ref = $object->ref;

				//létre kell hoznom egy llx_settlements_grouptools rekordott a groupusernevévelm entityjével
				$grouptoolsObj = new GroupTools($db);
				$grouptoolsObj->ref = $group_ref;
				$grouptoolsObj->label = $group_ref;
				$grouptoolsObj->fk_entity = $fk_group_entity;
				$result = $grouptoolsObj->create($user);


				//össze kell rendelnem őket a llx_settlements_usergrouptoolgroup táblában fk_groupid és fk_group_tools_id
				$usergrouptoolgroupObj = new UserGroupToolGroup($db);
				$usergrouptoolgroupObj->ref = $group_ref;
				$usergrouptoolgroupObj->label = $group_ref;
				$usergrouptoolgroupObj->fk_groupid = $fk_groupid;
				$usergrouptoolgroupObj->fk_group_tools_id = $result;
				$result2 = $usergrouptoolgroupObj->create($user);

				if ($object->single_user_group == 1) {
					$fk_user = $object->fk_user;
					$group_id = $object->id;
					$groupusers = new GroupUsers($this->db);
					$groupusers->createGroupUserRow($group_id, $fk_user);
				} elseif ($object->hotelgroup == 1) {
					$fk_hotel_id = $object->hotel;
					$group_id = $object->id;
					$rowid = $object->grouphotels_id;
					$groupHotels = new GroupHotels($this->db);
					$groupHotels->updateGroupHotelRow($group_id, $fk_hotel_id, $rowid);
				} else {
					$object->single_user_group = null;
				}
				break;

			case 'USERGROUPTOOLGROUP_DELETE':
				$usergrouptoolgroupnaplo = new UserGroupToolGroupNaplo($this->db);
				$usergrouptoolgroupnaplo->usergroup_toolgroup_id = $object->id;
				$usergrouptoolgroupnaplo->fk_groupid = $object->fk_groupid;
				$usergrouptoolgroupnaplo->fk_group_tools_id = $object->fk_group_tools_id;
				$usergrouptoolgroupnaplo->status = 0;
				$usergrouptoolgroupnaplo->create($user);
				break;
			case 'USERGROUPTOOLGROUP_CREATE':
				$usergrouptoolgroupnaplo = new UserGroupToolGroupNaplo($this->db);
				$usergrouptoolgroupnaplo->usergroup_toolgroup_id = $object->id;
				$usergrouptoolgroupnaplo->fk_groupid = $object->fk_groupid;
				$usergrouptoolgroupnaplo->fk_group_tools_id = $object->fk_group_tools_id;
				$usergrouptoolgroupnaplo->status = 1;
				$usergrouptoolgroupnaplo->create($user);
				break;
			case 'GROUP_MODIFY':
				if ($object->hotelgroup == 1) {
					$fk_hotel_id = $object->hotel;
					$group_id = $object->id;
					$rowid = $object->grouphotels_id;
					$groupHotels = new GroupHotels($this->db);
					$groupHotels->updateGroupHotelRow($group_id, $fk_hotel_id, $rowid);
				}
				if ($object->single_user_group == 1) {
					$fk_user = $object->fk_user;
					$group_id = $object->id;
					$rowid = $object->group_user_id;
					$groupusers = new GroupUsers($this->db);
					$groupusers->updateGroupUserRow($group_id, $fk_user, $rowid);
				}
				if ($object->table_element == 'settlements_group') {
					$sql = "update llx_settlements_grouptools as sgtup SET ref = '{$object->ref}', label = '{$object->ref}' WHERE sgtup.rowid IN (
						SELECT sgt.rowid FROM public.llx_settlements_group as sg
						INNER JOIN llx_settlements_usergrouptoolgroup as sugtg ON sugtg.fk_groupid = sg.rowid
						INNER JOIN llx_settlements_grouptools as sgt ON sgt.rowid = sugtg.fk_group_tools_id
						WHERE sg.rowid = {$object->id}
						ORDER BY sg.rowid ASC
						)";
					$result = $this->db->query($sql);

				}
				break;
			case 'GROUP_DELETE':
				global $db;
				$errors = 0;
				if ($object->table_element == 'settlements_group') {
					$db->begin();
					$groupusers = new GroupUsers($this->db);
					$result = $groupusers->fetchAll('ASC', 'fk_user', 0, 0, array('customsql' => 'fk_settlements_group = ' . ((int) $object->id)));
					foreach ($result as $row) {
						$result = $groupusers->deleteLine($user, $row->id);
						if(!$result){
							$errors++;
						}
					}
					$usergrouptoolgroupObj = new UserGroupToolGroup($db);
					$grouptoolsObj = new Grouptools($db);
					$resultUserGroupToolGroup = $usergrouptoolgroupObj->fetchAll('ASC', 'rowid', 0, 0, array('customsql' => 'fk_groupid = ' . (int) $object->id));
					foreach ($resultUserGroupToolGroup as $record) {
						$result1 = $grouptoolsObj->deleteLine($user, $record->fk_group_tools_id);
						if(!$result1){
							$errors++;
						}
						$result2 = $usergrouptoolgroupObj->deleteLine($user, $object->id);
						if(!$result2){
							$errors++;
						}
					}
					if(!$errors){
						$db->commit();
					}else{
						$db->rollback();
						setEventMessage('Error', 'error');
					}
				}
				break;
			//case 'USERGROUP_MODIFY':			
			/* case 'LINEGROUPUSERS_DELETE':
										   $data['id'] = GETPOST('id', 'int');
										   $data['action'] = GETPOST('massaction', 'alpha');
										   $data['toselect'] = GETPOST('toselect', 'array');
										   $userNaplo = new UserNaplo($this->db);
										   $userNaplo->createUserNaplo($user, $data);
										   dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
										   break;

									   case 'GROUPUSERS_CREATE':
										   $data['id'] = GETPOST('id', 'int');
										   $data['action'] = GETPOST('massactionadd', 'alpha');
										   $data['toselect'] = GETPOST('toselectnewuser', 'array');
										   $userNaplo = new UserNaplo($this->db);
										   $userNaplo->createUserNaplo($user, $data);
										   dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
										   break; */
			/* case 'USER_MODIFY':
										   global $user;
										   $userNaplo = new UserNaplo($this->db);
										   $userNaplo->createUserNaplo($user, $object);
										   dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
										   break; */
			// Users
			//case 'USER_CREATE':
			//case 'USER_MODIFY':
			//case 'USER_NEW_PASSWORD':
			//case 'USER_ENABLEDISABLE':
			//case 'USER_DELETE':

			// Actions
			//case 'ACTION_MODIFY':
			//case 'ACTION_CREATE':
			//case 'ACTION_DELETE':

			// Groups
			//case 'USERGROUP_CREATE':
			//case 'USERGROUP_MODIFY':
			//case 'USERGROUP_DELETE':

			// Companies
			//case 'COMPANY_CREATE':
			//case 'COMPANY_MODIFY':
			//case 'COMPANY_DELETE':

			// Contacts
			//case 'CONTACT_CREATE':
			//case 'CONTACT_MODIFY':
			//case 'CONTACT_DELETE':
			//case 'CONTACT_ENABLEDISABLE':

			// Products
			//case 'PRODUCT_CREATE':
			//case 'PRODUCT_MODIFY':
			//case 'PRODUCT_DELETE':
			//case 'PRODUCT_PRICE_MODIFY':
			//case 'PRODUCT_SET_MULTILANGS':
			//case 'PRODUCT_DEL_MULTILANGS':

			//Stock mouvement
			//case 'STOCK_MOVEMENT':

			//MYECMDIR
			//case 'MYECMDIR_CREATE':
			//case 'MYECMDIR_MODIFY':
			//case 'MYECMDIR_DELETE':

			// Customer orders
			//case 'ORDER_CREATE':
			//case 'ORDER_MODIFY':
			//case 'ORDER_VALIDATE':
			//case 'ORDER_DELETE':
			//case 'ORDER_CANCEL':
			//case 'ORDER_SENTBYMAIL':
			//case 'ORDER_CLASSIFY_BILLED':
			//case 'ORDER_SETDRAFT':
			//case 'LINEORDER_INSERT':
			//case 'LINEORDER_UPDATE':
			//case 'LINEORDER_DELETE':

			// Supplier orders
			//case 'ORDER_SUPPLIER_CREATE':
			//case 'ORDER_SUPPLIER_MODIFY':
			//case 'ORDER_SUPPLIER_VALIDATE':
			//case 'ORDER_SUPPLIER_DELETE':
			//case 'ORDER_SUPPLIER_APPROVE':
			//case 'ORDER_SUPPLIER_REFUSE':
			//case 'ORDER_SUPPLIER_CANCEL':
			//case 'ORDER_SUPPLIER_SENTBYMAIL':
			//case 'ORDER_SUPPLIER_DISPATCH':
			//case 'LINEORDER_SUPPLIER_DISPATCH':
			//case 'LINEORDER_SUPPLIER_CREATE':
			//case 'LINEORDER_SUPPLIER_UPDATE':
			//case 'LINEORDER_SUPPLIER_DELETE':

			// Proposals
			//case 'PROPAL_CREATE':
			//case 'PROPAL_MODIFY':
			//case 'PROPAL_VALIDATE':
			//case 'PROPAL_SENTBYMAIL':
			//case 'PROPAL_CLOSE_SIGNED':
			//case 'PROPAL_CLOSE_REFUSED':
			//case 'PROPAL_DELETE':
			//case 'LINEPROPAL_INSERT':
			//case 'LINEPROPAL_UPDATE':
			//case 'LINEPROPAL_DELETE':

			// SupplierProposal
			//case 'SUPPLIER_PROPOSAL_CREATE':
			//case 'SUPPLIER_PROPOSAL_MODIFY':
			//case 'SUPPLIER_PROPOSAL_VALIDATE':
			//case 'SUPPLIER_PROPOSAL_SENTBYMAIL':
			//case 'SUPPLIER_PROPOSAL_CLOSE_SIGNED':
			//case 'SUPPLIER_PROPOSAL_CLOSE_REFUSED':
			//case 'SUPPLIER_PROPOSAL_DELETE':
			//case 'LINESUPPLIER_PROPOSAL_INSERT':
			//case 'LINESUPPLIER_PROPOSAL_UPDATE':
			//case 'LINESUPPLIER_PROPOSAL_DELETE':

			// Contracts
			//case 'CONTRACT_CREATE':
			//case 'CONTRACT_MODIFY':
			//case 'CONTRACT_ACTIVATE':
			//case 'CONTRACT_CANCEL':
			//case 'CONTRACT_CLOSE':
			//case 'CONTRACT_DELETE':
			//case 'LINECONTRACT_INSERT':
			//case 'LINECONTRACT_UPDATE':
			//case 'LINECONTRACT_DELETE':

			// Bills
			//case 'BILL_CREATE':
			//case 'BILL_MODIFY':
			//case 'BILL_VALIDATE':
			//case 'BILL_UNVALIDATE':
			//case 'BILL_SENTBYMAIL':
			//case 'BILL_CANCEL':
			//case 'BILL_DELETE':
			//case 'BILL_PAYED':
			//case 'LINEBILL_INSERT':
			//case 'LINEBILL_UPDATE':
			//case 'LINEBILL_DELETE':

			//Supplier Bill
			//case 'BILL_SUPPLIER_CREATE':
			//case 'BILL_SUPPLIER_UPDATE':
			//case 'BILL_SUPPLIER_DELETE':
			//case 'BILL_SUPPLIER_PAYED':
			//case 'BILL_SUPPLIER_UNPAYED':
			//case 'BILL_SUPPLIER_VALIDATE':
			//case 'BILL_SUPPLIER_UNVALIDATE':
			//case 'LINEBILL_SUPPLIER_CREATE':
			//case 'LINEBILL_SUPPLIER_UPDATE':
			//case 'LINEBILL_SUPPLIER_DELETE':

			// Payments
			//case 'PAYMENT_CUSTOMER_CREATE':
			//case 'PAYMENT_SUPPLIER_CREATE':
			//case 'PAYMENT_ADD_TO_BANK':
			//case 'PAYMENT_DELETE':

			// Online
			//case 'PAYMENT_PAYBOX_OK':
			//case 'PAYMENT_PAYPAL_OK':
			//case 'PAYMENT_STRIPE_OK':

			// Donation
			//case 'DON_CREATE':
			//case 'DON_UPDATE':
			//case 'DON_DELETE':

			// Interventions
			//case 'FICHINTER_CREATE':
			//case 'FICHINTER_MODIFY':
			//case 'FICHINTER_VALIDATE':
			//case 'FICHINTER_DELETE':
			//case 'LINEFICHINTER_CREATE':
			//case 'LINEFICHINTER_UPDATE':
			//case 'LINEFICHINTER_DELETE':

			// Members
			//case 'MEMBER_CREATE':
			//case 'MEMBER_VALIDATE':
			//case 'MEMBER_SUBSCRIPTION':
			//case 'MEMBER_MODIFY':
			//case 'MEMBER_NEW_PASSWORD':
			//case 'MEMBER_RESILIATE':
			//case 'MEMBER_DELETE':

			// Categories
			//case 'CATEGORY_CREATE':
			//case 'CATEGORY_MODIFY':
			//case 'CATEGORY_DELETE':
			//case 'CATEGORY_SET_MULTILANGS':

			// Projects
			//case 'PROJECT_CREATE':
			//case 'PROJECT_MODIFY':
			//case 'PROJECT_DELETE':

			// Project tasks
			//case 'TASK_CREATE':
			//case 'TASK_MODIFY':
			//case 'TASK_DELETE':

			// Task time spent
			//case 'TASK_TIMESPENT_CREATE':
			//case 'TASK_TIMESPENT_MODIFY':
			//case 'TASK_TIMESPENT_DELETE':
			//case 'PROJECT_ADD_CONTACT':
			//case 'PROJECT_DELETE_CONTACT':
			//case 'PROJECT_DELETE_RESOURCE':

			// Shipping
			//case 'SHIPPING_CREATE':
			//case 'SHIPPING_MODIFY':
			//case 'SHIPPING_VALIDATE':
			//case 'SHIPPING_SENTBYMAIL':
			//case 'SHIPPING_BILLED':
			//case 'SHIPPING_CLOSED':
			//case 'SHIPPING_REOPEN':
			//case 'SHIPPING_DELETE':

			// and more...

			default:
				dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id);
				break;
		}

		return 0;
	}
}