<?php
/* Copyright (C) 2024 SuperAdmin
 *
 * 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    antpurchase/class/actions_antpurchase.class.php
 * \ingroup antpurchase
 * \brief   Example hook overload.
 *
 * Put detailed description here.
 */

require_once DOL_DOCUMENT_ROOT.'/core/class/commonhookactions.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
/**
 * Class ActionsAntPurchase
 */
class ActionsAntPurchase extends CommonHookActions
{
	/**
	 * @var DoliDB Database handler.
	 */
	public $db;

	/**
	 * @var string Error code (or message)
	 */
	public $error = '';

	/**
	 * @var array Errors
	 */
	public $errors = array();


	/**
	 * @var array Hook results. Propagated to $hookmanager->resArray for later reuse
	 */
	public $results = array();

	/**
	 * @var string String displayed by executeHook() immediately after return
	 */
	public $resprints;

	/**
	 * @var int		Priority of hook (50 is used if value is not defined)
	 */
	public $priority;


	/**
	 * Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}


	/**
	 * Execute action
	 *
	 * @param	array			$parameters		Array of parameters
	 * @param	CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param	string			$action      	'add', 'update', 'view'
	 * @return	int         					Return integer <0 if KO,
	 *                           				=0 if OK but we want to process standard actions too,
	 *                            				>0 if OK and we want to replace standard actions.
	 */
	public function getNomUrl($parameters, &$object, &$action)
	{
		global $db, $langs, $conf, $user;
		$this->resprints = '';
		return 0;
	}

	/**
	 * Overloading the doActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             Return integer < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			// Do what you want here...
			// You can for example call global vars like $fieldstosearchall to overwrite them, or update database depending on $action and $_POST values.
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}


	/**
	 * Overloading the doMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             Return integer < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			foreach ($parameters['toselect'] as $objectid) {
				// Do action on each object id
			}
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}


	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             Return integer < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter
		$disabled = 1;

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("AntPurchaseMassAction").'</option>';
		}

		if (!$error) {
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}



	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	Return integer <0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function beforePDFCreation($parameters, &$object, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;

		$outputlangs = $langs;

		$ret = 0;
		$deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
		}

		return $ret;
	}

	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$pdfhandler     PDF builder handler
	 * @param   string	$action         'add', 'update', 'view'
	 * @return  int 		            Return integer <0 if KO,
	 *                                  =0 if OK but we want to process standard actions too,
	 *                                  >0 if OK and we want to replace standard actions.
	 */
	public function afterPDFCreation($parameters, &$pdfhandler, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;

		$outputlangs = $langs;

		$ret = 0;
		$deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {
			// do something only for the context 'somecontext1' or 'somecontext2'
		}

		return $ret;
	}



	/**
	 * Overloading the loadDataForCustomReports function : returns data to complete the customreport tool
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             Return integer < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function loadDataForCustomReports($parameters, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$langs->load("antpurchase@antpurchase");

		$this->results = array();

		$head = array();
		$h = 0;

		if ($parameters['tabfamily'] == 'antpurchase') {
			$head[$h][0] = dol_buildpath('/module/index.php', 1);
			$head[$h][1] = $langs->trans("Home");
			$head[$h][2] = 'home';
			$h++;

			$this->results['title'] = $langs->trans("AntPurchase");
			$this->results['picto'] = 'antpurchase@antpurchase';
		}

		$head[$h][0] = 'customreports.php?objecttype='.$parameters['objecttype'].(empty($parameters['tabfamily']) ? '' : '&tabfamily='.$parameters['tabfamily']);
		$head[$h][1] = $langs->trans("CustomReports");
		$head[$h][2] = 'customreports';

		$this->results['head'] = $head;

		return 1;
	}



	/**
	 * Overloading the restrictedArea function : check permission on an object
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int 		      			  	Return integer <0 if KO,
	 *                          				=0 if OK but we want to process standard actions too,
	 *  	                            		>0 if OK and we want to replace standard actions.
	 */
	public function restrictedArea($parameters, &$action, $hookmanager)
	{
		global $user;

		if ($parameters['features'] == 'myobject') {
			if ($user->hasRight('antpurchase', 'myobject', 'read')) {
				$this->results['result'] = 1;
				return 1;
			} else {
				$this->results['result'] = 0;
				return 1;
			}
		}

		return 0;
	}

	/**
	 * Execute action completeTabsHead
	 *
	 * @param   array           $parameters     Array of parameters
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         'add', 'update', 'view'
	 * @param   Hookmanager     $hookmanager    hookmanager
	 * @return  int                             Return integer <0 if KO,
	 *                                          =0 if OK but we want to process standard actions too,
	 *                                          >0 if OK and we want to replace standard actions.
	 */
	public function completeTabsHead(&$parameters, &$object, &$action, $hookmanager)
	{
		global $langs, $conf, $user;

		if (!isset($parameters['object']->element)) {
			return 0;
		}
		if ($parameters['mode'] == 'remove') {
			// used to make some tabs removed
			return 0;
		} elseif ($parameters['mode'] == 'add') {
			$langs->load('antpurchase@antpurchase');
			// used when we want to add some tabs
			$counter = count($parameters['head']);
			$element = $parameters['object']->element;
			$id = $parameters['object']->id;
			// verifier le type d'onglet comme member_stats où ça ne doit pas apparaitre
			// if (in_array($element, ['societe', 'member', 'contrat', 'fichinter', 'project', 'propal', 'commande', 'facture', 'order_supplier', 'invoice_supplier'])) {
			if (in_array($element, ['context1', 'context2'])) {
				$datacount = 0;

				$parameters['head'][$counter][0] = dol_buildpath('/antpurchase/antpurchase_tab.php', 1) . '?id=' . $id . '&amp;module='.$element;
				$parameters['head'][$counter][1] = $langs->trans('AntPurchaseTab');
				if ($datacount > 0) {
					$parameters['head'][$counter][1] .= '<span class="badge marginleftonlyshort">' . $datacount . '</span>';
				}
				$parameters['head'][$counter][2] = 'antpurchaseemails';
				$counter++;
			}
			if ($counter > 0 && (int) DOL_VERSION < 14) {
				$this->results = $parameters['head'];
				// return 1 to replace standard code
				return 1;
			} else {
				// en V14 et + $parameters['head'] est modifiable par référence
				return 0;
			}
		} else {
			// Bad value for $parameters['mode']
			return -1;
		}
	}

	/* Add here any other hooked methods... */
	
		public function addOpenElementsDashboardGroup($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter
		$disabled = 1;
      
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('index'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("AntPurchaseMassAction").'</option>';
		}

		if (!$error) {
		    return 1; // or return 1 to replace standard code
			
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	
	
	
		public function tabContentCreateThirdparty___($parameters, &$object, &$action, $hookmanager)
	{
		global $db, $conf, $user, $langs;				$langs->loadLangs(array("companies", "commercial", "bills", "banks", "users"));		if (isModEnabled('adherent')) {			$langs->load("members");		}		if (isModEnabled('categorie')) {			$langs->load("categories");		}		if (isModEnabled('incoterm')) {			$langs->load("incoterm");		}		if (isModEnabled('notification')) {			$langs->load("mails");		}		if (isModEnabled('accounting')) {			$langs->load("products");		}				$form = new Form($db);		$formfile = new FormFile($db);		$formadmin = new FormAdmin($db);		$formcompany = new FormCompany($db);
		$socid = GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int');		if ($user->socid) {			$socid = $user->socid;		}		if (empty($socid) && $action == 'view') {			$action = 'create';		}		$id = $socid;		$object = new Societe($db);		$extrafields = new ExtraFields($db);		// fetch optionals attributes and labels		$extrafields->fetch_name_optionals_label($object->table_element);
		$error = 0; // Error counter
		$disabled = 1;
      
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('index'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("AntPurchaseMassAction").'</option>';
		}

		if (!$error) {			print '<table class="border centpercent">';			print '<tr class="tr-field-thirdparty-name"><td class="titlefieldcreate">';			print '<span id="TypeName" class="fieldrequired">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).'</span>';			print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus">';			print '</td><td>' ;			print '';			print '</td></tr>' ;						// Other attributes			$parameters = array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3');			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';				print '</table>' ;						print '<table class="border centpercent">';			// Name, firstname			print '<tr class="tr-field-thirdparty-name"><td class="titlefieldcreate">';			if ($object->particulier || $private) {				print '<span id="TypeName" class="fieldrequired">'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName', 'name').'</span>';			} else {				print '<span id="TypeName" class="fieldrequired">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).'</span>';			}			print '</td><td'.(!getDolGlobalString('SOCIETE_USEPREFIX') ? ' colspan="3"' : '').'>';			print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus">';			print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alphanohtml', 'minwidth300');	// For some countries that need the company name in 2 languages			// This implementation of the feature to search already existing company has been disabled. It must be implemented by keeping the "input text" and we must call the search ajax societe/ajax/ajaxcompanies.php			// on a keydown of the input. We should show data about a duplicate found if we found less than 5 answers into a div under the input.						print '</td>';			if (getDolGlobalString('SOCIETE_USEPREFIX')) {  // Old not used prefix field				print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.dol_escape_htmltag($object->prefix_comm).'"></td>';			}			print '</tr>';			// If javascript on, we show option individual			if ($conf->use_javascript_ajax) {				if (getDolGlobalString('THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION')) {					// Firstname					print '<tr class="individualline"><td>'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'</td>';					print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.dol_escape_htmltag($object->firstname).'"></td>';					print '</tr>';					// Title					print '<tr class="individualline"><td>'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';					print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').'</td>';					print '</tr>';				}			}			// Alias names (commercial, trademark or alias names)			print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';			print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>';			// Prospect/Customer			print '<tr><td class="titlefieldcreate">'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).'</td>';			print '<td class="maxwidthonsmartphone">';			$selected = (GETPOSTISSET('client') ? GETPOST('client', 'int') : $object->client);			print $formcompany->selectProspectCustomerType($selected);			print '</td>';			if ($conf->browser->layout == 'phone') {				print '</tr><tr>';			}			print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>';			print '<table class="nobordernopadding"><tr><td>';			$tmpcode = $object->code_client;			if (empty($tmpcode) && !empty($modCodeClient->code_auto)) {				$tmpcode = $modCodeClient->getNextValue($object, 0);			}			print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">';			print '</td><td>';			$s = $modCodeClient->getToolTip($langs, $object, 0);			print $form->textwithpicto('', $s, 1);			print '</td></tr></table>';			print '</td></tr>';			if ((isModEnabled("fournisseur") && $user->hasRight('fournisseur', 'lire') && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) || (isModEnabled("supplier_order") && $user->hasRight('supplier_order', 'lire')) || (isModEnabled("supplier_invoice") && $user->hasRight('supplier_invoice', 'lire'))				|| (isModEnabled('supplier_proposal') && $user->hasRight('supplier_proposal', 'lire'))) {				// Supplier				print '<tr>';				print '<td>'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).'</td><td>';				$default = -1;				if (getDolGlobalString('THIRDPARTY_SUPPLIER_BY_DEFAULT')) {					$default = 1;				}				print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0), 1);				print '</td>';				if ($conf->browser->layout == 'phone') {					print '</tr><tr>';				}				print '<td>';				if ((isModEnabled("fournisseur") && $user->hasRight('fournisseur', 'lire') && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) || (isModEnabled("supplier_order") && $user->hasRight('supplier_order', 'lire')) || (isModEnabled("supplier_invoice") && $user->hasRight('supplier_invoice', 'lire'))) {					print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);				}				print '</td><td>';				if ((isModEnabled("fournisseur") && $user->hasRight('fournisseur', 'lire') && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) || (isModEnabled("supplier_order") && $user->hasRight('supplier_order', 'lire')) || (isModEnabled("supplier_invoice") && $user->hasRight('supplier_invoice', 'lire'))) {					print '<table class="nobordernopadding"><tr><td>';					$tmpcode = $object->code_fournisseur;					if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) {						$tmpcode = $modCodeFournisseur->getNextValue($object, 1);					}					print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="24">';					print '</td><td>';					$s = $modCodeFournisseur->getToolTip($langs, $object, 1);					print $form->textwithpicto('', $s, 1);					print '</td></tr></table>';				}				print '</td></tr>';			}			// Status			print '<tr><td>'.$form->editfieldkey('Status', 'status', '', $object, 0).'</td><td colspan="3">';			print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100', 1);			print '</td></tr>';			// Barcode			if (isModEnabled('barcode')) {				print '<tr><td>'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>';				print '<td colspan="3">';				print img_picto('', 'barcode', 'class="pictofixedwidth"');				print '<input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">';				print '</td></tr>';			}			// Address			print '<tr><td class="tdtop">';			print $form->editfieldkey('Address', 'address', '', $object, 0);			print '</td>';			print '<td colspan="3">';			print '<textarea name="address" id="address" class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft">';			print dol_escape_htmltag($object->address, 0, 1);			print '</textarea>';			print $form->widgetForTranslation("address", $object, $permissiontoadd, 'textarea', 'alphanohtml', 'quatrevingtpercent');			print '</td></tr>';			// Zip / Town			print '<tr><td>'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).'</td><td>';			print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100');			print '</td>';			if ($conf->browser->layout == 'phone') {				print '</tr><tr>';			}			print '<td class="tdtop">'.$form->editfieldkey('Town', 'town', '', $object, 0).'</td><td>';			print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth150 quatrevingtpercent');			print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent');			print '</td></tr>';			// Country			print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';			print img_picto('', 'country', 'class="pictofixedwidth"');			print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 maxwidth500 widthcentpercentminusx');			if ($user->admin) {				print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);			}			print '</td></tr>';			// State			if (!getDolGlobalString('SOCIETE_DISABLE_STATE')) {				if ((getDolGlobalInt('MAIN_SHOW_REGION_IN_STATE_SELECT') == 1 || getDolGlobalInt('MAIN_SHOW_REGION_IN_STATE_SELECT') == 2)) {					print '<tr><td>'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';				} else {					print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';				}				if ($object->country_id) {					print img_picto('', 'state', 'class="pictofixedwidth"');					print $formcompany->select_state($object->state_id, $object->country_code);				} else {					print $countrynotdefined;				}				print '</td></tr>';			}			// Phone / Fax			print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>';			print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning', 'class="pictofixedwidth"').' <input type="text" name="phone" id="phone" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('phone') ? GETPOST('phone', 'alpha') : $object->phone).'"></td>';			if ($conf->browser->layout == 'phone') {				print '</tr><tr>';			}			print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>';			print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax', 'class="pictofixedwidth"').' <input type="text" name="fax" id="fax" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('fax') ? GETPOST('fax', 'alpha') : $object->fax).'"></td></tr>';			// Email / Web			print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', !getDolGlobalString('SOCIETE_EMAIL_MANDATORY') ? '' : $conf->global->SOCIETE_EMAIL_MANDATORY).'</td>';			print '<td'.(($conf->browser->layout == 'phone') || !isModEnabled('mailing') ? ' colspan="3"' : '').'>'.img_picto('', 'object_email', 'class="pictofixedwidth"').' <input type="text" class="maxwidth200 widthcentpercentminusx" name="email" id="email" value="'.$object->email.'"></td>';			if (isModEnabled('mailing') && getDolGlobalString('THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION')) {				if ($conf->browser->layout == 'phone') {					print '</tr><tr>';				}				print '<td class="individualline noemail">'.$form->editfieldkey($langs->trans('No_Email') .' ('.$langs->trans('Contact').')', 'contact_no_email', '', $object, 0).'</td>';				print '<td class="individualline" '.(($conf->browser->layout == 'phone') || !isModEnabled('mailing') ? ' colspan="3"' : '').'>'.$form->selectyesno('contact_no_email', (GETPOSTISSET("contact_no_email") ? GETPOST("contact_no_email", 'alpha') : (empty($object->no_email) ? 0 : 1)), 1, false, 1).'</td>';			}			print '</tr>';			print '<tr><td>'.$form->editfieldkey('Web', 'url', '', $object, 0).'</td>';			print '<td colspan="3">'.img_picto('', 'globe', 'class="pictofixedwidth"').' <input type="text" class="maxwidth500 widthcentpercentminusx" name="url" id="url" value="'.$object->url.'"></td></tr>';			// Unsubscribe			if (isModEnabled('mailing')) {				if ($conf->use_javascript_ajax && getDolGlobalInt('MAILING_CONTACT_DEFAULT_BULK_STATUS') == 2) {					print "\n".'<script type="text/javascript">'."\n";					print '$(document).ready(function () {								$("#email").keyup(function() {									if ($(this).val()!="") {										$(".noemail").addClass("fieldrequired");									} else {										$(".noemail").removeClass("fieldrequired");									}								});							})'."\n";					print '</script>'."\n";				}				if (!GETPOSTISSET("no_email") && !empty($object->email)) {					$result = $object->getNoEmail();					if ($result < 0) {						setEventMessages($object->error, $object->errors, 'errors');					}				}				print '<tr>';				print '<td class="noemail"><label for="no_email">'.$langs->trans("No_Email").'</label></td>';				print '<td>';				print $form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'int') : getDolGlobalInt('MAILING_CONTACT_DEFAULT_BULK_STATUS')), 1, false, (getDolGlobalInt('MAILING_CONTACT_DEFAULT_BULK_STATUS') == 2));				print '</td>';				print '</tr>';			}			// Social networks			if (isModEnabled('socialnetworks')) {				$object->showSocialNetwork($socialnetworks, ($conf->browser->layout == 'phone' ? 2 : 4));			}			// Prof ids			$i = 1;			$j = 0;			$NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2);			while ($i <= 6) {				$idprof = $langs->transcountry('ProfId'.$i, $object->country_code);				if ($idprof != '-') {					$key = 'idprof'.$i;					if (($j % $NBCOLS) == 0) {						print '<tr>';					}					$idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY';					print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).'</td><td>';					print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code);					print '</td>';					if (($j % $NBCOLS) == ($NBCOLS - 1)) {						print '</tr>';					}					$j++;				}				$i++;			}			if ($NBCOLS > 1 && ($j % 2 == 1)) {				print '<td colspan="2"></td></tr>';			}			// Vat is used			print '<tr><td>'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).'</td>';			print '<td>';			print '<input id="assujtva_value" name="assujtva_value" type="checkbox" ' . (GETPOSTISSET('assujtva_value') ? 'checked="checked"' : 'checked="checked"') . ' value="1">'; // Assujeti par defaut en creation			print '</td>';			if ($conf->browser->layout == 'phone') {				print '</tr><tr>';			}			print '<td class="nowrap">'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).'</td>';			print '<td class="nowrap">';			$s = '<input type="text" class="flat maxwidthonsmartphone" name="tva_intra" id="intra_vat" maxlength="20" value="'.$object->tva_intra.'">';			if (!getDolGlobalString('MAIN_DISABLEVATCHECK') && isInEEC($object)) {				$s .= ' ';				if (!empty($conf->use_javascript_ajax)) {					$widthpopup = 600;					if (!empty($conf->dol_use_jmobile)) {						$widthpopup = 350;					}					$heightpopup = 400;					print "\n";					print '<script type="text/javascript">';					print "function CheckVAT(a) {\n";					if ($mysoc->country_code == 'GR' && $object->country_code == 'GR' && !empty($u)) {						print "GRVAT(a,'{$u}','{$p}','{$myafm}');\n";					} else {						print "newpopup('".DOL_URL_ROOT."/societe/checkvat/checkVatPopup.php?vatNumber='+a, '".dol_escape_js($langs->trans("VATIntraCheckableOnEUSite"))."', ".$widthpopup.", ".$heightpopup.");\n";					}					print "}\n";					print '</script>';					print "\n";					$s .= '<a href="#" class="hideonsmartphone" onclick="CheckVAT(document.formsoc.tva_intra.value);">'.$langs->trans("VATIntraCheck").'</a>';					$s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1);				} else {					$s .= '<a href="'.$langs->transcountry("VATIntraCheckURL", $object->country_id).'" target="_blank" rel="noopener noreferrer">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').'</a>';				}			}			print $s;			print '</td>';			print '</tr>';			// VAT reverse charge by default			if (getDolGlobalString('ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE')) {				print '<tr><td>' . $form->editfieldkey('VATReverseChargeByDefault', 'vat_reverse_charge', '', $object, 0) . '</td><td colspan="3">';				print '<input type="checkbox" name="vat_reverse_charge" '.($object->vat_reverse_charge == '1' ? ' checked' : '').'>';				print '</td></tr>';			}			// Local Taxes			//TODO: Place into a function to control showing by country or study better option			if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") {				print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>';				print '<input id="localtax1assuj_value" name="localtax1assuj_value" type="checkbox" ' . (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? 'checked="checked"' : '') . ' value="1">';				print '</td>';				if ($conf->browser->layout == 'phone') {					print '</tr><tr>';				}				print '<td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>';				print '<input id="localtax2assuj_value" name="localtax2assuj_value" type="checkbox" ' . (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? 'checked="checked"' : '') . ' value="1">';				print '</td></tr>';			} elseif ($mysoc->localtax1_assuj == "1") {				print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td colspan="3">';				print '<input id="localtax1assuj_value" name="localtax1assuj_value" type="checkbox" ' . (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? 'checked="checked"' : '') . ' value="1">';				print '</td></tr>';			} elseif ($mysoc->localtax2_assuj == "1") {				print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td colspan="3">';				print '<input id="localtax2assuj_value" name="localtax2assuj_value" type="checkbox" ' . (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? 'checked="checked"' : '') . ' value="1">';				print '</td></tr>';			}			// Type - Workforce/Staff			print '<tr><td>'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.(($conf->browser->layout == 'phone' || getDolGlobalString('SOCIETE_DISABLE_WORKFORCE')) ? ' colspan="3"' : '').'>'."\n";			$sortparam = (!getDolGlobalString('SOCIETE_SORT_ON_TYPEENT') ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label.			print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam, '', 1);			if ($user->admin) {				print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);			}			if (!getDolGlobalString('SOCIETE_DISABLE_WORKFORCE')) {				print '</td>';				if ($conf->browser->layout == 'phone') {					print '</tr><tr>';				}				print '<td>'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>';				print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id, 0, 0, 0, '', 0, 0, 0, '', '', 1);				if ($user->admin) {					print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);				}			} else {				print '<input type="hidden" name="effectif_id" id="effectif_id" value="'.$object->effectif_id.'">';			}			print '</td></tr>';			// Legal Form			print '<tr><td>'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).'</td>';			print '<td colspan="3" class="maxwidthonsmartphone">';			if ($object->country_id) {				print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code');			} else {				print $countrynotdefined;			}			print '</td></tr>';			// Capital			print '<tr><td>'.$form->editfieldkey('Capital', 'capital', '', $object, 0).'</td>';			print '<td colspan="3"><input type="text" name="capital" id="capital" class="maxwidth100" value="'.$object->capital.'"> ';			if (isModEnabled("multicurrency")) {				print '<span class="hideonsmartphone">'.$langs->trans("Currency".$object->multicurrency_code).'</span></td></tr>';			} else {				print '<span class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</span></td></tr>';			}			if (getDolGlobalInt('MAIN_MULTILANGS')) {				print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'."\n";				print img_picto('', 'language', 'class="pictofixedwidth"').$formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone');				print '</td>';				print '</tr>';			}			// Incoterms			if (isModEnabled('incoterm')) {				print '<tr>';				print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';				print '<td colspan="3" class="maxwidthonsmartphone">';				print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''));				print '</td></tr>';			}			// Categories			if (isModEnabled('categorie') && $user->hasRight('categorie', 'lire')) {				$langs->load('categories');				// Customer				print '<tr class="visibleifcustomer"><td class="toptd">'.$form->editfieldkey('CustomersProspectsCategoriesShort', 'custcats', '', $object, 0).'</td><td colspan="3">';				$cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, 'parent', null, null, 1);				print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('custcats', $cate_arbo, GETPOST('custcats', 'array'), null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0);				print "</td></tr>";				if (getDolGlobalString('THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION')) {					print '<tr class="individualline"><td class="toptd">'.$form->editfieldkey('ContactCategoriesShort', 'contcats', '', $object, 0).'</td><td colspan="3">';					$cate_arbo = $form->select_all_categories(Categorie::TYPE_CONTACT, null, 'parent', null, null, 1);					print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('contcats', $cate_arbo, GETPOST('contcats', 'array'), null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0);					print "</td></tr>";				}				// Supplier				if (isModEnabled("supplier_proposal") || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) {					print '<tr class="visibleifsupplier"><td class="toptd">'.$form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0).'</td><td colspan="3">';					$cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, 'parent', null, null, 1);					print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('suppcats', $cate_arbo, GETPOST('suppcats', 'array'), null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0);					print "</td></tr>";				}			}			// Multicurrency			if (isModEnabled("multicurrency")) {				print '<tr>';				print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';				print '<td colspan="3" class="maxwidthonsmartphone">';				print img_picto('', 'currency', 'class="pictofixedwidth"');				print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code') : ($object->multicurrency_code ? $object->multicurrency_code : $conf->currency)), 'multicurrency_code', 1, '', false, 'maxwidth150 widthcentpercentminusx');				print '</td></tr>';			}			// Other attributes			$parameters = array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3');			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';			// Parent company			if (!getDolGlobalString('SOCIETE_DISABLE_PARENTCOMPANY')) {				print '<tr>';				print '<td>'.$langs->trans('ParentCompany').'</td>';				print '<td colspan="3" class="maxwidthonsmartphone">';				print img_picto('', 'company', 'class="paddingrightonly"');				print $form->select_company(GETPOST('parent_company_id'), 'parent_company_id', '', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 maxwidth500 widthcentpercentminusxx');				print '</td></tr>';			}			// Assign a sale representative			print '<tr>';			print '<td>'.$form->editfieldkey('AllocateCommercial', 'commercial_id', '', $object, 0).'</td>';			print '<td colspan="3" class="maxwidthonsmartphone">';			$userlist = $form->select_dolusers('', '', 0, null, 0, '', '', '0', 0, 0, 'AND u.statut = 1', 0, '', '', 0, 2);			// Note: If user has no right to "see all thirdparties", we force selection of sale representative to him, so after creation he can see the record.			$selected = (count(GETPOST('commercial', 'array')) > 0 ? GETPOST('commercial', 'array') : (GETPOST('commercial', 'int') > 0 ? array(GETPOST('commercial', 'int')) : (empty($user->rights->societe->client->voir) ? array($user->id) : array())));			print img_picto('', 'user').$form->multiselectarray('commercial', $userlist, $selected, null, null, 'quatrevingtpercent widthcentpercentminusx', 0, 0);			print '</td></tr>';			// Add logo			print '<tr class="hideonsmartphone">';			print '<td>'.$form->editfieldkey('Logo', 'photoinput', '', $object, 0).'</td>';			print '<td colspan="3">';			print '<input class="flat" type="file" name="photo" id="photoinput" />';			print '</td>';			print '</tr>';			print '</table>'."\n";			// Accountancy codes			if (getDolGlobalString('ACCOUNTANCY_USE_PRODUCT_ACCOUNT_ON_THIRDPARTY')) {				print '<table class="border centpercent">';				if (isModEnabled('accounting')) {					// Accountancy_code_sell					print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>';					print '<td>';					$accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha');					print $formaccounting->select_account($accountancy_code_sell, 'accountancy_code_sell', 1, null, 1, 1, '');					print '</td></tr>';					// Accountancy_code_buy					print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyCode").'</td>';					print '<td>';					$accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha');					print $formaccounting->select_account($accountancy_code_buy, 'accountancy_code_buy', 1, null, 1, 1, '');					print '</td></tr>';				} else { // For external software					// Accountancy_code_sell					print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancySellCode").'</td>';					print '<td class="maxwidthonsmartphone"><input class="minwidth100" name="accountancy_code_sell" value="'.$object->accountancy_code_sell.'">';					print '</td></tr>';					// Accountancy_code_buy					print '<tr><td class="titlefieldcreate">'.$langs->trans("ProductAccountancyBuyCode").'</td>';					print '<td class="maxwidthonsmartphone"><input class="minwidth100" name="accountancy_code_buy" value="'.$object->accountancy_code_buy.'">';					print '</td></tr>';				}				print '</table>';			}								; 
		    return 1; // or return 1 to replace standard code
			
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	
	
	
	/*function formObjectOptions($parameters, &$object, &$action, $hookmanager)
    {
        global $langs, $db;

        // Vérifier que le hook est bien appelé sur un produit
        if ($parameters['currentcontext'] == 'productcard') {

            if ($action == 'create' || $action == 'update') {
                // Appeler la fonction pour générer la référence produit fournisseur
                $supplierID = $object->fk_supplier;  // ID fournisseur
                $productID = $object->id;  // ID produit
                $generatedRef = $this->generateSupplierProductRef($productID, $supplierID);

                // Affecter la référence générée au produit
                $object->ref_fourn = $generatedRef;
            }
        }
    }
	
	
	
	 private function generateSupplierProductRef($productID, $supplierID)
    {
        // Exemple simple pour générer la référence produit fournisseur
        global $db;

        $supplier = new Fournisseur($db);
        $supplier->fetch($supplierID);

        $supplierCode = substr($supplier->name, 0, 3);
        $ref = 'FRN-' . strtoupper($supplierCode) . '-' . $productID;

        // Vérifier l'unicité de la référence
        $sql = "SELECT count(*) as total FROM llx_product_fournisseur_price WHERE ref_fourn = '".$db->escape($ref)."'";
        $resql = $db->query($sql);
        if ($resql) {
            $obj = $db->fetch_object($resql);
            if ($obj->total > 0) {
                $ref .= '-' . str_pad($obj->total + 1, 3, '0', STR_PAD_LEFT);
            }
        }

        return $ref;
    }
	*/
	
	
	
}
