<?php

namespace app\controllers;

use Yii;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use yii\helpers\FileHelper;
use yii\helpers\Json;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;


class FunzioniController extends Controller
{
	
	public $enableCsrfValidation = false;
	
	public function actionF1()
	{
		
		$authorizationHeader = Yii::$app->request->headers->get('Authorization');
		$username = Yii::$app->request->headers->get('username');
		$password = Yii::$app->request->headers->get('password');
		$synch_date = Yii::$app->request->headers->get('synch_date');
		$target = Yii::$app->request->headers->get('target');
		$CrmProjectTargets = \app\models\CrmProjectTargets::find()
		->where(["name" => $target])
		->one();
		
		$CrmProjectTargetContacts = \app\models\CrmProjectTargetContacts::find()
		->where(["id_target" => $CrmProjectTargets->id])
		->andWhere(["synch" => 0])
		->limit(500)
		//->andWhere([">", "updated_at", $synch_date])
		->asArray()
		->all();
		
		$data = [];
		
		foreach($CrmProjectTargetContacts as $CrmProjectTargetContact){
			
			$CrmProjectTargetContactsS = \app\models\CrmProjectTargetContacts::findOne($CrmProjectTargetContact['id']);
			$CrmProjectTargetContactsS->synch = 1;
			$CrmProjectTargetContactsS->save(false);
			
			$data[] = [
				'id' => $CrmProjectTargetContact['id'],
				'id_project' => $CrmProjectTargetContact['id_project'],
				'id_target' => $CrmProjectTargetContact['id_target'],
				'id_status' => $CrmProjectTargetContact['id_status'],
				'contact_date' => $CrmProjectTargetContact['contact_date'],
				'company' => $CrmProjectTargetContact['company'],
				'telephone_pref' => $CrmProjectTargetContact['telephone_pref'],
				'telephone' => $CrmProjectTargetContact['telephone'],
				'smartphone' => $CrmProjectTargetContact['smartphone'],
				'note' => $CrmProjectTargetContact['note'],
				'referent' => $CrmProjectTargetContact['referent'],
				'referent_email' => $CrmProjectTargetContact['referent_email'],
				'general_email' => $CrmProjectTargetContact['general_email'],
				'employees' => $CrmProjectTargetContact['employees'],
				'revenue' => $CrmProjectTargetContact['revenue'],
				'website' => $CrmProjectTargetContact['website'],
				'vat_number' => $CrmProjectTargetContact['vat_number'],
				'address' => $CrmProjectTargetContact['address'],
				'postal_code' => $CrmProjectTargetContact['postal_code'],
				'city' => $CrmProjectTargetContact['city'],
				'region' => $CrmProjectTargetContact['region'],
				'nation' => $CrmProjectTargetContact['nation'],
				'province' => $CrmProjectTargetContact['province'],
				'tags' => $CrmProjectTargetContact['tags'],
				'tags_search' => $CrmProjectTargetContact['tags_search'],
				'monthly_visits' => $CrmProjectTargetContact['monthly_visits'],
				'sector' => $CrmProjectTargetContact['sector'],
				'category' => $CrmProjectTargetContact['category'],
				'referent_linkedin' => $CrmProjectTargetContact['referent_linkedin'],
				'company_linkedin' => $CrmProjectTargetContact['company_linkedin'],
				'used_platform' => $CrmProjectTargetContact['used_platform'],
				'monthly_shipments' => $CrmProjectTargetContact['monthly_shipments'],
				'used_courier' => $CrmProjectTargetContact['used_courier'],
				'privacy' => $CrmProjectTargetContact['privacy'],
				'privacy_date' => $CrmProjectTargetContact['privacy_date'],
				'code' => $CrmProjectTargetContact['code'],
				'ateco_code' => $CrmProjectTargetContact['ateco_code'],
				'id_projects' => $CrmProjectTargetContact['id_projects'],
				'longitude' => $CrmProjectTargetContact['longitude'],
				'latitude' => $CrmProjectTargetContact['latitude'],
				'source' => $CrmProjectTargetContact['source'],
				'business_supply_chain' => $CrmProjectTargetContact['business_supply_chain'],
				'created_at' => $CrmProjectTargetContact['created_at'],
				'updated_at' => $CrmProjectTargetContact['updated_at'],
            ];
		}
		
		Yii::$app->response->format = Response::FORMAT_JSON;
		return $data;
	}
	
	public function actionF2()
	{
		
		$authorizationHeader = Yii::$app->request->headers->get('Authorization');
		$username = Yii::$app->request->headers->get('username');
		$password = Yii::$app->request->headers->get('password');
		
		$CrmProjectTargets = \app\models\CrmProjectTargets::find()
		->asArray()
		->all();
		
		$data = [];
		
		foreach($CrmProjectTargets as $CrmProjectTarget){
			
			$CrmProjectTargetContactsCount = \app\models\CrmProjectTargetContacts::find()
			->where(["id_target" => $CrmProjectTarget['id']])
			->andWhere(["synch" => 0])
			->count();
			
			$data[] = [
				'target' => $CrmProjectTarget['name'], 'synch' => $CrmProjectTargetContactsCount
            ];
		}
		
		Yii::$app->response->format = Response::FORMAT_JSON;
		return $data;
	}
	
	// Modifica contatto proveniente da PadelSearch
	public function actionF3()
	{
		
		$authorizationHeader = Yii::$app->request->headers->get('Authorization');
		$username = Yii::$app->request->headers->get('username');
		$password = Yii::$app->request->headers->get('password');
		$data = Yii::$app->request->getBodyParams();
		
		$jsonData = file_get_contents("php://input");
		$decodedData = json_decode($jsonData, true);
		
		/*
		$decodedData = [];
		foreach ($data as $jsonString => $emptyValue) {
			$jsonData = json_decode($jsonString, true);

			if ($jsonData !== null && json_last_error() === JSON_ERROR_NONE) {
				$decodedData[] = $jsonData;
			} else {
				Yii::error("Errore nella decodifica JSON: " . json_last_error_msg());
			}
		}
		*/
		
		$CrmProjectTargetContacts = isset($decodedData["code"])?\app\models\CrmProjectTargetContacts::find()->where(["code" => $decodedData["code"]])->one():new \app\models\CrmProjectTargetContacts();
		$CrmProjectTargetContacts->company = isset($decodedData["company"])?$decodedData["company"]:null;
		$CrmProjectTargetContacts->vat_number = isset($decodedData["vat_number"])?$decodedData["vat_number"]:null;
		$CrmProjectTargetContacts->address = isset($decodedData["address"])?$decodedData["address"]:null;
		$CrmProjectTargetContacts->postal_code = isset($decodedData["postal_code"])?$decodedData["postal_code"]:null;
		$CrmProjectTargetContacts->city = isset($decodedData["city"])?$decodedData["city"]:null;
		$CrmProjectTargetContacts->nation = isset($decodedData["nation"])?$decodedData["nation"]:null;
		$CrmProjectTargetContacts->region = isset($decodedData["region"])?$decodedData["region"]:null;
		$CrmProjectTargetContacts->province = isset($decodedData["province"])?$decodedData["province"]:null;
		$CrmProjectTargetContacts->business_supply_chain = isset($decodedData["business_supply_chain"])?$decodedData["business_supply_chain"]:null;
		$CrmProjectTargetContacts->telephone = isset($decodedData["telephone"])?$decodedData["telephone"]:null;
		$CrmProjectTargetContacts->general_email = isset($decodedData["general_email"])?$decodedData["general_email"]:null;
		$CrmProjectTargetContacts->website = isset($decodedData["website"])?$decodedData["website"]:null;
		
		if(!isset($decodedData["code"])){
			$CrmProjectTargetContacts->code = \app\models\Functions::getCompanyCode();
		}
		
		$CrmProjectTargetContacts->synch = 1;
		$CrmProjectTargetContacts->updated_at = strtotime(date("Y-m-d H:i:s"));
		$CrmProjectTargetContacts->id_project = 197;
		$CrmProjectTargetContacts->id_target = 601;
		$CrmProjectTargetContacts->save(false);
		
		$data = [];
		
		if(!isset($decodedData["code"])){
			$data[] = [
				'code' => $CrmProjectTargetContacts->code
            ];
		} else {
			$data[] = [];
		}
		
		Yii::$app->response->format = Response::FORMAT_JSON;
		return $data;
	}
	
	// Modal Inserimento Persona Fisica
	public function actionF4()
	{
		
		$PhoneCodeNumbers = ArrayHelper::map(\app\models\PhoneCodeNumbers::find()->orderBy(["phonecode" => SORT_ASC])->all(), 'id', function($model) {
			return '+' . $model->phonecode.' ('.$model->iso3.')';
		});
		
		$Regions = ArrayHelper::map(\app\models\Regions::find()->orderBy(["name" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$CrmClientStatus = ArrayHelper::map(\app\models\CrmClientStatus::find()->orderBy(["id" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$CrmLanguages = ArrayHelper::map(\app\models\CrmLanguages::find()->orderBy(["id" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$BusinessCategories = \app\models\BusinessCategories::find()->all();
		$BusinessSubcategories = \app\models\BusinessSubcategories::find()->all();
		$items = [];
		foreach ($BusinessCategories as $BusinessCategory) {
			// Trovo le sottocategorie di questa categoria
			$subs = array_filter($BusinessSubcategories, function($sub) use ($BusinessCategory) {
				return $sub->id_category == $BusinessCategory->id;
			});

			// Converto in array id => nome
			$subsList = ArrayHelper::map($subs, 'id', 'name');

			// Aggiungo al gruppo
			$items[$BusinessCategory->name] = $subsList;
		}
		
		$text = '';

		$text .= '<div class="modal-dialog modal-dialog-centered mw-650px">';
			$text .= '<div class="modal-content">';

				// Header
				$text .= '<div class="modal-header">';
					$text .= '<h2 class="modal-title fw-bolder">Persona Fisica</h2>';
					$text .= '<button type="button" class="btn btn-icon btn-sm btn-active-icon-primary" data-bs-dismiss="modal" aria-label="Chiudi">';
					$text .= '<span class="svg-icon svg-icon-1">';
					$text .= '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">';
					$text .= '<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black" />';
					$text .= '<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black" />';
					$text .= '</svg>';
					$text .= '</span>';
					$text .= '</button>';
				$text .= '</div>';

				$text .= '<div class="modal-body scroll-y mx-5 mx-xl-15 my-7">';
					$text .= '<form id="actionF4Form" class="form" action="#">';
		
						$text .= '<div class="row">';
						
							$text .= '<div class="col-md-6">';
							$text .= Html::dropDownList('entity_type',1,[1 => 'Persona fisica', 2 => 'Azienda'],['class' => 'form-select mb-3', 'prompt' => 'Tipo contatto', 'id' => 'entity_type', 'disabled' => 'disabled']);
							//$text .= Html::dropDownList('entity_type',1,[1 => 'Persona fisica', 2 => 'Azienda'],['class' => 'form-select mb-3', 'prompt' => 'Tipo contatto', 'id' => 'entity_type', 'onchange' => 'entityTypeChange(this)']);
							$text .= '</div>';
							
							$text .= '<div class="col-md-6">';
							$text .= Html::dropDownList('address_country', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_country','data-url' => Url::to(['funzioni/f16']), 'data-placeholder' => 'Nazione...']);
							$text .= '</div>';
						
						$text .= '</div>';
						
						#####################################################################################################
						# Persona fisica
						#####################################################################################################

						$text .= '<div class="individual-fields mb-10">';
							
							$text .= '<h5 class="mb-4 mt-6">Dati personali</h5>';
							
								$text .= '<div class="row">';
									$text .= '<div class="col-md-4">';
										$text .= Html::input('text', 'first_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Nome']);
									$text .= '</div>';
									$text .= '<div class="col-md-4">';
										$text .= Html::input('text', 'middle_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Secondo nome']);
									$text .= '</div>';
									$text .= '<div class="col-md-4">';
										$text .= Html::input('text', 'last_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Cognome']);
									$text .= '</div>';
							$text .= '</div>';
						
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6">';
									$text .= Html::dropDownList('gender',null,["F" => "F","M" => "M"],['class' => 'form-select mb-3', 'prompt' => 'Genere']);
								$text .= '</div>';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('date', 'date_of_birth', null, ['class' => 'form-control mb-3', 'placeholder' => 'Data di nascita']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row" id="fiscalCodeDiv">';
								$text .= '<div class="col-md-9">';
									$text .= Html::input('text', 'tax_id', null, ['class' => 'form-control mb-3', 'placeholder' => 'Codice fiscale', 'id' => 'tax_id']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= '<button type="button" class="btn btn-primary actionF21">Calcola</button>';
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Dati di residenza</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6" id="address_stateDiv">';
									$text .= Html::dropDownList('address_state',null,$Regions,['class' => 'form-select mb-3 address_state12345', 'prompt' => 'Regione', 'id' => 'address_state', 'onchange' => 'actionF17(this)']);
								$text .= '</div>';
								$text .= '<div class="col-md-6" id="address_provinceDiv">';
									$text .= Html::dropDownList('address_province',null,[],['class' => 'form-select mb-3', 'prompt' => 'Provincia', 'id' => 'address_province']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('address_city', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_city','data-url' => Url::to(['funzioni/f18']), 'data-placeholder' => 'Cerca città...']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'address_street', null, ['class' => 'form-control mb-3', 'placeholder' => 'Indirizzo']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'address_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Civico']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'address_postal_code', null, ['class' => 'form-control mb-3', 'placeholder' => 'CAP / ZIP']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Dati di contatto</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('email', 'email', null, ['class' => 'form-control mb-3', 'placeholder' => 'Email']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-3">';
									$text .= Html::dropDownList('phone_code_number',105,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'phone_code_number']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-9">';
									$text .= Html::input('text', 'phone', null, ['class' => 'form-control mb-3', 'placeholder' => 'Telefono']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::dropDownList('mobile_code_number',105,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'mobile_code_number']);
								$text .= '</div>';
								$text .= '<div class="col-md-9">';
									$text .= Html::input('text', 'mobile', null, ['class' => 'form-control mb-3', 'placeholder' => 'Cellulare']);
								$text .= '</div>';

								$text .= '<div class="col-md-6">';
									$text .= Html::input('email', 'pec_email', null, ['class' => 'form-control mb-3', 'placeholder' => 'PEC']);
								$text .= '</div>';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'website', null, ['class' => 'form-control mb-3', 'placeholder' => 'Sito web']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Social</h5>';
							
							$text .= '<div class="row">';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('facebook', 'facebook', null, ['class' => 'form-control mb-3', 'placeholder' => 'Facebook']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('instagram', 'instagram', null, ['class' => 'form-control mb-3', 'placeholder' => 'Instagram']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('youtube', 'youtube', null, ['class' => 'form-control mb-3', 'placeholder' => 'Youtube']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('linkedin', 'linkedin', null, ['class' => 'form-control mb-3', 'placeholder' => 'Linkedin']);
								$text .= '</div>';
								
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Privacy</h5>';
							
							$text .= '<div class="row mb-4">';
								$text .= '<div class="col-md-12">';
									$text .= Html::checkbox('privacy1', false, [
										'label' => 'Consenso Privacy (GDPR)',
										'class' => 'form-check-input',
										'labelOptions' => ['class' => 'form-check-label'],
									]);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::checkbox('privacy2', false, [
										'label' => 'Consenso Marketing',
										'class' => 'form-check-input',
										'labelOptions' => ['class' => 'form-check-label'],
									]);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Altre informazioni</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('language',null,$CrmLanguages,['class' => 'form-select mb-3', 'prompt' => 'Lingua preferita', 'id' => 'language']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('client_companies[]', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'client_companies','data-url' => Url::to(['funzioni/f20']), 'data-placeholder' => 'Collega azienda...']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('text', 'notes', null, ['class' => 'form-control mb-3', 'placeholder' => 'Note']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('status',null,$CrmClientStatus,['class' => 'form-select mb-3', 'prompt' => 'Stato', 'id' => 'status']);
								$text .= '</div>';
							$text .= '</div>';
						
							//$text .= '<div class="col-md-6">';
							//$text .= Html::dropDownList('place_of_birth', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'place_of_birth','data-url' => Url::to(['funzioni/f18']), 'data-placeholder' => 'Città di nascita...']);
							//$text .= '</div>';
						$text .= '</div>';

					$text .= '</form>';

				$text .= '</div>';

				// Footer
				$text .= '<div class="modal-footer">';
					$text .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>';
					$text .= '<button type="button" class="btn btn-primary actionF5">Salva</button>';
				$text .= '</div>';

			$text .= '</div>';
		$text .= '</div>';

		
		return json_encode(array(
			"error" => 0,
			"text" => $text,
		));
		
	}
	
	# Salvataggio Persona Fisica
	public function actionF5()
    {
		
		$entity_type = Yii::$app->request->post('entity_type');
		$tax_id = Yii::$app->request->post('tax_id');
		$vat_number = Yii::$app->request->post('vat_number');
		$business_name = Yii::$app->request->post('business_name');
		$registration_number = Yii::$app->request->post('registration_number');
		$first_name = Yii::$app->request->post('first_name');
		$middle_name = Yii::$app->request->post('middle_name');
		$last_name = Yii::$app->request->post('last_name');
		$gender = Yii::$app->request->post('gender');
		$date_of_birth = Yii::$app->request->post('date_of_birth');
		$place_of_birth = Yii::$app->request->post('place_of_birth');
		$email = Yii::$app->request->post('email');
		$phone_code_number = Yii::$app->request->post('phone_code_number');
		$phone = Yii::$app->request->post('phone');
		$mobile_code_number = Yii::$app->request->post('mobile_code_number');
		$mobile = Yii::$app->request->post('mobile');
		$fax = Yii::$app->request->post('fax');
		$pec_email = Yii::$app->request->post('pec_email');
		$website = Yii::$app->request->post('website');
		$address_street = Yii::$app->request->post('address_street');
		$address_number = Yii::$app->request->post('address_number');
		$address_city = Yii::$app->request->post('address_city');
		$address_postal_code = Yii::$app->request->post('address_postal_code');
		$address_province = Yii::$app->request->post('address_province');
		$address_state = Yii::$app->request->post('address_state');
		$address_country = Yii::$app->request->post('address_country');
		$legal_representative = Yii::$app->request->post('legal_representative');
		$company_type = Yii::$app->request->post('company_type');
		$industry = Yii::$app->request->post('industry');
		$employees_number = Yii::$app->request->post('employees_number');
		$revenue = Yii::$app->request->post('revenue');
		$language = Yii::$app->request->post('language');
		$facebook = Yii::$app->request->post('facebook');
		$instagram = Yii::$app->request->post('instagram');
		$youtube = Yii::$app->request->post('youtube');
		$linkedin = Yii::$app->request->post('linkedin');
		$notes = Yii::$app->request->post('notes');
		$status = Yii::$app->request->post('status');
		$client_companies = Yii::$app->request->post('client_companies');
		$privacy1 = Yii::$app->request->post('privacy1');
		$privacy2 = Yii::$app->request->post('privacy2');
		//$created_at = Yii::$app->request->post('created_at');
		
		
		if(!$entity_type){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TIPO ENTITÀ è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$email){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo EMAIL è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo EMAIL non è un indirizzo valido","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$phone){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TELEFONO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$fax){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo FAX è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_city){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CITTÀ è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_province){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PROVINCIA è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$mobile){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CELLULARE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$pec_email){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PEC è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!filter_var($pec_email, FILTER_VALIDATE_EMAIL)){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PEC non è un indirizzo valido","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$website){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SITO WEB è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_street){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo VIA è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CIVICO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_postal_code){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CAP è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_state){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo STATO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_country){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NAZIONE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if($privacy1){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo Consenso Privacy (GDPR) è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}

		// Persona fisica (entity_type = 1)
		if($entity_type == 1){
			//if(!$first_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$middle_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SECONDO NOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$gender){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo GENERE è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$place_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo LUOGO DI NASCITA è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$last_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo COGNOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$date_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo DATA DI NASCITA è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
		}

		// Azienda (entity_type = 2)
		if($entity_type == 2){
			//if(!$tax_id){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CODICE FISCALE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$business_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo RAGIONE SOCIALE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$company_type){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TIPO SOCIETÀ è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$employees_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NUMERO DIPENDENTI è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$vat_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PARTITA IVA è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$registration_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NUMERO DI REGISTRAZIONE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$legal_representative){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo LEGALE RAPPRESENTANTE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$revenue){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo FATTURATO è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$industry){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SETTORE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
		}

		// Note e Stato (facoltativi, se vuoi farli obbligatori togli commento)
		 //if(!$notes){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NOTE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$status){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo STATO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$created_at){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo DATA CREAZIONE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		
		$CrmClient = new \app\models\CrmClients();
		$CrmClient->entity_type = $entity_type;
		$CrmClient->tax_id = $tax_id;
		$CrmClient->vat_number = $vat_number;
		$CrmClient->business_name = $business_name;
		$CrmClient->registration_number = $registration_number;
		$CrmClient->first_name = $first_name;
		$CrmClient->middle_name = $middle_name;
		$CrmClient->last_name = $last_name;
		$CrmClient->gender = $gender;
		$CrmClient->date_of_birth = $date_of_birth;
		$CrmClient->place_of_birth = $place_of_birth;
		$CrmClient->email = $email;
		$CrmClient->phone_code_number = $phone_code_number;
		$CrmClient->phone = $phone;
		$CrmClient->mobile_code_number = $mobile_code_number;
		$CrmClient->mobile = $mobile;
		$CrmClient->fax = $fax;
		$CrmClient->pec_email = $pec_email;
		$CrmClient->website = $website;
		$CrmClient->address_street = $address_street;
		$CrmClient->address_number = $address_number;
		$CrmClient->address_city = $address_city;
		$CrmClient->address_postal_code = $address_postal_code;
		$CrmClient->address_province = $address_province;
		$CrmClient->address_state = $address_state;
		$CrmClient->address_country = $address_country;
		$CrmClient->legal_representative = $legal_representative;
		$CrmClient->company_type = $company_type;
		$CrmClient->industry = $industry;
		$CrmClient->employees_number = $employees_number;
		$CrmClient->revenue = $revenue;
		$CrmClient->notes = $notes;
		$CrmClient->language = $language;
		$CrmClient->facebook = $facebook;
		$CrmClient->instagram = $instagram;
		$CrmClient->youtube = $youtube;
		$CrmClient->linkedin = $linkedin;
		$CrmClient->status = $status;
		$CrmClient->created_at = date("Y-m-d H:i");
		$CrmClient->save(false);
		
		foreach($client_companies as $client_company){
			$CrmClientCompany = new \app\models\CrmClientsCompanies();
			$CrmClientCompany->id_client = $CrmClient->id;
			$CrmClientCompany->id_company = $client_company;
			$CrmClientCompany->save(false);
		}

		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Salvataggio effettuato con successo","success","bi bi-check-circle")));
		exit;
		
	}
	
	// Visualizza la modal per la modifica di un cliente
	public function actionF6()
	{
		
		$id = Yii::$app->request->post('id');
		$CrmClient = \app\models\CrmClients::findOne($id);
		
		$PhoneCodeNumbers = ArrayHelper::map(\app\models\PhoneCodeNumbers::find()->orderBy(["phonecode" => SORT_ASC])->all(), 'id', function($model) {
			return '+' . $model->phonecode.' ('.$model->iso3.')';
		});
		
		$Regions = ArrayHelper::map(\app\models\Regions::find()->orderBy(["name" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$Provinces = ArrayHelper::map(\app\models\Provinces::find()->where(["id_region" => $CrmClient->address_state])->orderBy(["name" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		

		$text = '';
		
		$text = '<div class="modal-dialog modal-dialog-centered mw-650px">';
		$text .= '<div class="modal-content">';

		// HEADER
		$text .= '<div class="modal-header" id="kt_modal_add_user_header">';
		$text .= '<h2 class="modal-title fw-bolder" id="kt_modal_add_user_label">Aggiungi</h2>';
		$text .= '<button type="button" class="btn btn-icon btn-sm btn-active-icon-primary" data-bs-dismiss="modal" aria-label="Close">';
		$text .= '<span class="svg-icon svg-icon-1">';
		$text .= '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">';
		$text .= '<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black" />';
		$text .= '<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black" />';
		$text .= '</svg>';
		$text .= '</span>';
		$text .= '</button>';
		$text .= '</div>';

		// BODY
		$text .= '<div class="modal-body scroll-y mx-5 mx-xl-15 my-7">';
		$text .= '<form id="actionF4Form" class="form" action="#">';
		
		$text .= '<div class="col-md-6">';
		$text .= Html::dropDownList('entity_type',$CrmClient->entity_type,[1 => 'Persona fisica', 2 => 'Azienda'],['class' => 'form-select mb-3', 'prompt' => 'Tipo anagrafica', 'id' => 'entity_type', 'onchange' => 'entityTypeChange(this)']);
		$text .= '</div>';
		
		$text .= '<div class="col-md-6">';
		$text .= Html::dropDownList('address_country', $CrmClient->address_country, [$CrmClient->address_country => $CrmClient->nation_rel?$CrmClient->nation_rel->name:''], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_country','data-url' => Url::to(['funzioni/f16']), 'data-placeholder' => 'Nazione di residenza...']);
		$text .= '</div>';
		
		// Titolo sezione Campi condivisi
		$text .= '<h5 class="mb-4">Informazioni generali</h5>';
		$text .= '<div class="shared-fields mb-10">';
		$text .= '<div class="row">';
		
		$text .= '<div class="col-md-6">';
		$text .= Html::input('email', 'email', $CrmClient->email, ['class' => 'form-control mb-3', 'placeholder' => 'Email']);
		$text .= '</div>';
		$text .= '<div class="col-md-3">';
		$text .= Html::dropDownList('phone_code_number',$CrmClient->phone_code_number,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'phone_code_number']);
		$text .= '</div>';
		$text .= '<div class="col-md-3">';
		$text .= Html::input('text', 'phone', $CrmClient->phone, ['class' => 'form-control mb-3', 'placeholder' => 'Telefono']);
		$text .= '</div>';
		$text .= '<div class="col-md-3">';
		$text .= Html::dropDownList('mobile_code_number',$CrmClient->mobile_code_number,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'mobile_code_number']);
		$text .= '</div>';
		$text .= '<div class="col-md-3">';
		$text .= Html::input('text', 'mobile', $CrmClient->mobile, ['class' => 'form-control mb-3', 'placeholder' => 'Cellulare']);
		$text .= '</div>';
		
		$text .= '<div class="col-md-6">';
		$text .= Html::dropDownList('address_state',$CrmClient->address_state,$Regions,['class' => 'form-select mb-3 address_state12345', 'prompt' => 'Regione', 'id' => 'address_state', 'onchange' => 'actionF17(this)']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::dropDownList('address_province',$CrmClient->address_province,$Provinces,['class' => 'form-select mb-3', 'prompt' => 'Provincia', 'id' => 'address_province']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::dropDownList('address_city', $CrmClient->address_city, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_city','data-url' => Url::to(['funzioni/f18']), 'data-placeholder' => 'Cerca città...']);
		$text .= '</div>';
		
		
		
		$text .= '<div class="col-md-6">';
		$text .= Html::input('email', 'pec_email', null, ['class' => 'form-control mb-3', 'placeholder' => 'PEC']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'website', null, ['class' => 'form-control mb-3', 'placeholder' => 'Sito web']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'address_street', null, ['class' => 'form-control mb-3', 'placeholder' => 'Indirizzo']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'address_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Civico']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'address_postal_code', null, ['class' => 'form-control mb-3', 'placeholder' => 'CAP']);
		$text .= '</div>';
		
		$text .= '</div>';
		$text .= '</div>';

		// Titolo sezione Persona fisica

		$text .= '<div class="individual-fields mb-10 d-none">';
		$text .= '<h5 class="mb-4 mt-6">Dati persona fisica</h5>';
		$text .= '<div class="row">';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'first_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Nome']);
		$text .= Html::input('text', 'middle_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Secondo nome']);
		$text .= Html::input('text', 'gender', null, ['class' => 'form-control mb-3', 'placeholder' => 'Genere']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'last_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Cognome']);
		$text .= Html::input('date', 'date_of_birth', null, ['class' => 'form-control mb-3', 'placeholder' => 'Data di nascita']);
		$text .= Html::input('text', 'place_of_birth', null, ['class' => 'form-control mb-3', 'placeholder' => 'Luogo di nascita']);
		$text .= '</div>';
		$text .= '</div>';
		$text .= '</div>';

		// Titolo sezione Azienda

		$text .= '<div class="company-fields mb-10 d-none">';
		$text .= '<h5 class="mb-4 mt-6">Dati azienda</h5>';
		$text .= '<div class="row">';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'tax_id', null, ['class' => 'form-control mb-3', 'placeholder' => 'Codice fiscale']);
		$text .= Html::input('text', 'business_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Ragione sociale']);
		$text .= Html::input('text', 'company_type', null, ['class' => 'form-control mb-3', 'placeholder' => 'Tipo società']);
		$text .= Html::input('number', 'employees_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Numero dipendenti']);
		$text .= '</div>';
		$text .= '<div class="col-md-6">';
		$text .= Html::input('text', 'vat_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Partita IVA']);
		$text .= Html::input('text', 'registration_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Numero di registrazione']);
		$text .= Html::input('text', 'legal_representative', null, ['class' => 'form-control mb-3', 'placeholder' => 'Legale rappresentante']);
		$text .= Html::input('number', 'revenue', null, ['class' => 'form-control mb-3', 'placeholder' => 'Fatturato']);
		$text .= Html::input('text', 'industry', null, ['class' => 'form-control mb-3', 'placeholder' => 'Settore']);
		$text .= '</div>';
		$text .= '</div>';
		$text .= '</div>';

		// Titolo sezione Note e Stato
		$text .= '<h5 class="mb-4 mt-6">Altre informazioni</h5>';
		
		$text .= Html::input('text', 'notes', null, ['class' => 'form-control mb-3', 'placeholder' => 'Note']);
		$text .= Html::input('text', 'status', null, ['class' => 'form-control mb-3', 'placeholder' => 'Stato']);
		//$text .= Html::input('datetime-local', 'created_at', null, ['class' => 'form-control mb-3', 'placeholder' => 'Data creazione']);
		
		$text .= Html::hiddenInput('id', $id);

		$text .= '</form>';
		$text .= '</div>';

		// FOOTER
		$text .= '<div class="modal-footer">';
		$text .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>';
		$text .= '<button type="button" class="btn btn-primary actionF7">Salva</button>';
		$text .= '</div>'; // modal-footer

		$text .= '</div>'; // modal-content
		$text .= '</div>'; // modal-dialog

		
		return json_encode(array(
			"error" => 0,
			"text" => $text,
		));
		
	}
	
	# Modifica cliente
	public function actionF7()
    {
		
		$id = Yii::$app->request->post('id');
		$entity_type = Yii::$app->request->post('entity_type');
		$tax_id = Yii::$app->request->post('tax_id');
		$vat_number = Yii::$app->request->post('vat_number');
		$business_name = Yii::$app->request->post('business_name');
		$registration_number = Yii::$app->request->post('registration_number');
		$first_name = Yii::$app->request->post('first_name');
		$middle_name = Yii::$app->request->post('middle_name');
		$last_name = Yii::$app->request->post('last_name');
		$gender = Yii::$app->request->post('gender');
		$date_of_birth = Yii::$app->request->post('date_of_birth');
		$place_of_birth = Yii::$app->request->post('place_of_birth');
		$email = Yii::$app->request->post('email');
		$phone_code_number = Yii::$app->request->post('phone_code_number');
		$phone = Yii::$app->request->post('phone');
		$mobile_code_number = Yii::$app->request->post('mobile_code_number');
		$mobile = Yii::$app->request->post('mobile');
		$fax = Yii::$app->request->post('fax');
		$pec_email = Yii::$app->request->post('pec_email');
		$website = Yii::$app->request->post('website');
		$address_street = Yii::$app->request->post('address_street');
		$address_number = Yii::$app->request->post('address_number');
		$address_city = Yii::$app->request->post('address_city');
		$address_postal_code = Yii::$app->request->post('address_postal_code');
		$address_province = Yii::$app->request->post('address_province');
		$address_state = Yii::$app->request->post('address_state');
		$address_country = Yii::$app->request->post('address_country');
		$legal_representative = Yii::$app->request->post('legal_representative');
		$company_type = Yii::$app->request->post('company_type');
		$industry = Yii::$app->request->post('industry');
		$employees_number = Yii::$app->request->post('employees_number');
		$revenue = Yii::$app->request->post('revenue');
		$notes = Yii::$app->request->post('notes');
		$status = Yii::$app->request->post('status');
		//$created_at = Yii::$app->request->post('created_at');

		//return json_encode(array("error" => 1,"text" => \app\models\Functions::ModalMessage("PT Elite","Scegliere il COLORE della sottocategoria","warning","bi bi-exclamation-triangle-fill")));
		//exit;
		
		Yii::error($_POST);
		
		$CrmClient = \app\models\CrmClients::findOne($id);
		$CrmClient->entity_type = $entity_type;
		$CrmClient->tax_id = $tax_id;
		$CrmClient->vat_number = $vat_number;
		$CrmClient->business_name = $business_name;
		$CrmClient->registration_number = $registration_number;
		$CrmClient->first_name = $first_name;
		$CrmClient->middle_name = $middle_name;
		$CrmClient->last_name = $last_name;
		$CrmClient->gender = $gender;
		$CrmClient->date_of_birth = $date_of_birth;
		$CrmClient->place_of_birth = $place_of_birth;
		$CrmClient->email = $email;
		$CrmClient->phone_code_number = $phone_code_number;
		$CrmClient->phone = $phone;
		$CrmClient->mobile_code_number = $mobile_code_number;
		$CrmClient->mobile = $mobile;
		$CrmClient->fax = $fax;
		$CrmClient->pec_email = $pec_email;
		$CrmClient->website = $website;
		$CrmClient->address_street = $address_street;
		$CrmClient->address_number = $address_number;
		$CrmClient->address_city = $address_city;
		$CrmClient->address_postal_code = $address_postal_code;
		$CrmClient->address_province = $address_province;
		$CrmClient->address_state = $address_state;
		$CrmClient->address_country = $address_country;
		$CrmClient->legal_representative = $legal_representative;
		$CrmClient->company_type = $company_type;
		$CrmClient->industry = $industry;
		$CrmClient->employees_number = $employees_number;
		$CrmClient->revenue = $revenue;
		$CrmClient->notes = $notes;
		$CrmClient->status = $status;
		$CrmClient->created_at = date("Y-m-d H:i");
		$CrmClient->save(false);

		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Salvataggio effettuato con successo","success","bi bi-check-circle")));
		exit;
		
	}
	
	# Modal di conferma eliminazione cliente
	public function actionF8()
    {
		
		$id = Yii::$app->request->post('id');
		$CrmClient = \app\models\CrmClients::findOne($id);
		
		$text = '';
		
		$text .= '<div class="modal-dialog">';
			$text .= '<div class="modal-content">';
				$text .= '<div class="modal-header">';
					$text .= '<h3 class="modal-title">Conferma eliminazione</h3>';
				$text .= '</div>';
				$text .= '<div class="modal-body">';
					$text .= '<p>Confermi di voler eliminare il cliente "'.$CrmClient->first_name.'" ?</p>';
					$text .= '<p>Se confermi verranno eliminate anche tutte le sottocategorie ad essa associate</p>';
				$text .= '</div>';
				$text .= '<div class="modal-footer">';
					$text .= '<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>';
					$text .= '<button type="button" class="btn btn-danger actionF9" data-id="'.$id.'">Elimina</button>';
				$text .= '</div>';
			$text .= '</div>';
		$text .= '</div>';
		
		return json_encode(array(
			"error" => 0,
			"text" => $text
		));
			
	}
	
	# Eliminazione cliente
	public function actionF9()
    {
		
		$id = Yii::$app->request->post('id');
		$CrmClient = \app\models\CrmClients::findOne($id);
		
		//Elimino anche tutte le sottocategorie ad essa associate
		//Yii::$app->db->createCommand('DELETE FROM ptelite_tickler_subcategories WHERE id_category = '.$id)->execute();
		
		//$CrmClient->delete();
		
		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Eliminazione effettuata con successo","success","bi bi-check-circle")));
		exit;
			
	}
	
	// Modal  Inserimento prodotto
	public function actionF10()
	{
		
		$text = '';
		
		$text .= '<div class="modal-dialog modal-dialog-centered mw-650px">';
		$text .= '<div class="modal-content">';
		$text .= '<div class="modal-header" id="kt_modal_add_user_header">';
		$text .= '<h2 class="modal-title fw-bolder" id="kt_modal_add_user_label">Aggiungi</h2>';
		$text .= '<button type="button" class="btn btn-icon btn-sm btn-active-icon-primary" data-bs-dismiss="modal" aria-label="Close">';
		$text .= '<span class="svg-icon svg-icon-1">';
		$text .= '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">';
		$text .= '<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black" />';
		$text .= '<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black" />';
		$text .= '</svg>';
		$text .= '</span>';
		$text .= '</button>';
		$text .= '</div>';
		$text .= '<div class="modal-body scroll-y mx-5 mx-xl-15 my-7">';
		$text .= '<form id="actionF10Form" class="form" action="#">';
		$text .= Html::input('text', 'name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Nome']);
		$text .= Html::input('text', 'type', null, ['class' => 'form-control mb-3', 'placeholder' => 'Tipo di prodotto']);
		$text .= Html::input('text', 'code', null, ['class' => 'form-control mb-3', 'placeholder' => 'Codice']);
		$text .= Html::input('text', 'description', null, ['class' => 'form-control mb-3', 'placeholder' => 'Descrizione']);
		$text .= '</form>';
		$text .= '</div>';
		$text .= '<div class="modal-footer">';
		$text .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>';
		$text .= '<button type="button" class="btn btn-primary actionF11">Salva</button>';
		$text .= '</div>';
		$text .= '</div>';
		$text .= '</div>';
		
		return json_encode(array(
			"error" => 0,
			"text" => $text,
		));
		
	}
	
	# Salvataggio prodotto
	public function actionF11()
    {
		
		$name = Yii::$app->request->post('name');
		$type = Yii::$app->request->post('type');
		$code = Yii::$app->request->post('code');
		$description = Yii::$app->request->post('description');

		//return json_encode(array("error" => 1,"text" => \app\models\Functions::ModalMessage("PT Elite","Scegliere il COLORE della sottocategoria","warning","bi bi-exclamation-triangle-fill")));
		//exit;
		
		$CrmProduct = new \app\models\CrmProducts();
		$CrmProduct->name = $name;
		$CrmProduct->type = $type;
		$CrmProduct->code = $code;
		$CrmProduct->description = $description;
		$CrmProduct->save(false);

		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Salvataggio effettuato con successo","success","bi bi-check-circle")));
		exit;
		
	}
	
	// Modifica Prodotto
	public function actionF12()
	{
		
		$id = Yii::$app->request->post('id');
		$CrmProduct = \app\models\CrmProducts::findOne($id);
		
		$text = '';
		
		$text .= '<div class="modal-dialog modal-dialog-centered mw-650px">';
		$text .= '<div class="modal-content">';
		$text .= '<div class="modal-header" id="kt_modal_add_user_header">';
		$text .= '<h2 class="modal-title fw-bolder" id="kt_modal_add_user_label">Aggiungi</h2>';
		$text .= '<button type="button" class="btn btn-icon btn-sm btn-active-icon-primary" data-bs-dismiss="modal" aria-label="Close">';
		$text .= '<span class="svg-icon svg-icon-1">';
		$text .= '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">';
		$text .= '<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black" />';
		$text .= '<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black" />';
		$text .= '</svg>';
		$text .= '</span>';
		$text .= '</button>';
		$text .= '</div>';
		$text .= '<div class="modal-body scroll-y mx-5 mx-xl-15 my-7">';
		$text .= '<form id="actionF10Form" class="form" action="#">';
		$text .= Html::input('text', 'name', $CrmProduct->name, ['class' => 'form-control mb-3', 'placeholder' => 'Nome']);
		$text .= Html::input('text', 'type', $CrmProduct->type, ['class' => 'form-control mb-3', 'placeholder' => 'Tipo di prodotto']);
		$text .= Html::input('text', 'code', $CrmProduct->code, ['class' => 'form-control mb-3', 'placeholder' => 'Codice']);
		$text .= Html::input('text', 'description', $CrmProduct->description, ['class' => 'form-control mb-3', 'placeholder' => 'Descrizione']);
		$text .= Html::hiddenInput('id', $id);
		$text .= '</form>';
		$text .= '</div>';
		$text .= '<div class="modal-footer">';
		$text .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>';
		$text .= '<button type="button" class="btn btn-primary actionF11">Salva</button>';
		$text .= '</div>';
		$text .= '</div>';
		$text .= '</div>';
		
		return json_encode(array(
			"error" => 0,
			"text" => $text,
		));
		
	}
	
	# Modifica Prodotto
	public function actionF13()
    {
		
		$id = Yii::$app->request->post('id');
		$name = Yii::$app->request->post('name');
		$type = Yii::$app->request->post('type');
		$code = Yii::$app->request->post('code');
		$description = Yii::$app->request->post('description');

		//return json_encode(array("error" => 1,"text" => \app\models\Functions::ModalMessage("PT Elite","Scegliere il COLORE della sottocategoria","warning","bi bi-exclamation-triangle-fill")));
		//exit;
		
		$CrmProduct = \app\models\CrmProducts::findOne($id);
		$CrmProduct->name = $name;
		$CrmProduct->type = $type;
		$CrmProduct->code = $code;
		$CrmProduct->description = $description;
		$CrmProduct->save(false);

		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Salvataggio effettuato con successo","success","bi bi-check-circle")));
		exit;
		
	}
	
	# Conferma eliminazione Prodotto
	public function actionF14()
    {
		
		$id = Yii::$app->request->post('id');
		$CrmProduct = \app\models\CrmProducts::findOne($id);
		
		$text = '';
		
		$text .= '<div class="modal-dialog">';
			$text .= '<div class="modal-content">';
				$text .= '<div class="modal-header">';
					$text .= '<h3 class="modal-title">Conferma eliminazione</h3>';
				$text .= '</div>';
				$text .= '<div class="modal-body">';
					$text .= '<p>Confermi di voler eliminare il Prodotto "'.$CrmProduct->first_name.'" ?</p>';
					//$text .= '<p>Se confermi verranno eliminate anche tutte le sottocategorie ad essa associate</p>';
				$text .= '</div>';
				$text .= '<div class="modal-footer">';
					$text .= '<button type="button" class="btn btn-light" data-bs-dismiss="modal">Annulla</button>';
					$text .= '<button type="button" class="btn btn-danger actionF15" data-id="'.$id.'">Elimina</button>';
				$text .= '</div>';
			$text .= '</div>';
		$text .= '</div>';
		
		return json_encode(array(
			"error" => 0,
			"text" => $text
		));
			
	}
	
	# Eliminazione Prodotto
	public function actionF15()
    {
		
		$id = Yii::$app->request->post('id');
		$CrmProduct = \app\models\CrmProducts::findOne($id);
		
		//Elimino anche tutte le sottocategorie ad essa associate
		//Yii::$app->db->createCommand('DELETE FROM ptelite_tickler_subcategories WHERE id_category = '.$id)->execute();
		
		//$CrmProduct->delete();
		
		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Eliminazione effettuata con successo","success","bi bi-check-circle")));
		exit;
			
	}
	
	public function actionF16($q = null)
	{
		Yii::$app->response->format = Response::FORMAT_JSON;

		$query = \app\models\Nations::find()
		->select([
            'id',
            "CONCAT(code, ' - ', name) AS text"
        ])
		->where(['like', 'name', $q])
		->limit(20)
		->asArray()
		->all();

		return ['results' => $query];
	}
	
	public function actionF17()
	{
		\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

		$regionId = Yii::$app->request->post('region_id');

		// Assicurati che ci sia un ID valido
		if (!$regionId) {
			return ['results' => []];
		}

		// Recupera le province dalla tabella
		$Provinces = \app\models\Provinces::find()
			->select(['id', 'name AS text']) // Select2 richiede 'id' e 'text'
			->where(['id_region' => $regionId])
			->orderBy('name')
			->asArray()
			->all();

		return ['results' => $Provinces];
	}
	
	public function actionF18()
	{
		Yii::$app->response->format = Response::FORMAT_JSON;
		
		$request = Yii::$app->request;
		$q = $request->post('q');
		$address_state = $request->post('address_state');
		$address_province = $request->post('address_province');
		$address_country = $request->post('address_country');
		

		$query = \app\models\Cities::find()
		->select(['id', 'name AS text'])
		->where(['like', 'name', $q])
		->andFilterWhere(['id_province' => $address_province])
		->andFilterWhere(['id_region' => $address_state])
		->andFilterWhere(['id_nation' => $address_country])
		->limit(20)
		->asArray()
		->all();

		return ['results' => $query];
	}
	
	# Ottengo le informazioni che servono per rendere dinamici alcuni campi a seconda della Nazione scelta
	public function actionF19()
    {
		
		$id = Yii::$app->request->post('id');
		$Nation = \app\models\Nations::findOne($id);
		$PhoneCodeNumber = \app\models\PhoneCodeNumbers::find()->where(["iso" => $Nation->code])->one();
		
		return json_encode(array(
			"error" => 0,
			"id" => $id,
			"id_phone_code_number" => $PhoneCodeNumber->id
		));
		exit;
			
	}
	
	public function actionF20()
	{
		Yii::$app->response->format = Response::FORMAT_JSON;
		
		$request = Yii::$app->request;
		$q = $request->post('q');
		//$address_state = $request->post('address_state');
		//$address_province = $request->post('address_province');
		//$address_country = $request->post('address_country');
		

		$query = \app\models\CrmProjectTargetContacts::find()
		->select(['id', 'company AS text'])
		->where(['like', 'company', $q])
		//->andFilterWhere(['id_province' => $address_province])
		//->andFilterWhere(['id_region' => $address_state])
		//->andFilterWhere(['id_nation' => $address_country])
		->limit(20)
		->asArray()
		->all();

		return ['results' => $query];
	}
	
	# Calcolo codice fiscale
	public function actionF21()
    {
		
		$first_name = Yii::$app->request->post('first_name');
		$last_name = Yii::$app->request->post('last_name');
		$date_of_birth = Yii::$app->request->post('date_of_birth');
		$gender = Yii::$app->request->post('gender');
		$place_of_birth = Yii::$app->request->post('place_of_birth');
		
		if(!$first_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NOME è obbligatorio ai fini del calcolo del codice fiscale","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$last_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo COGNOME è obbligatorio ai fini del calcolo del codice fiscale","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$date_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo DATA DI NASCITA è obbligatorio ai fini del calcolo del codice fiscale","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$gender){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo GENERE è obbligatorio ai fini del calcolo del codice fiscale","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$place_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CITTA' DI NASCITA è obbligatorio ai fini del calcolo del codice fiscale","warning","bi bi-exclamation-triangle-fill"))); exit;}
		
		$City = \app\models\Cities::findOne($place_of_birth);
		
		$fiscal_code = \app\models\Functions::calcolaCodiceFiscale($first_name,$last_name,$date_of_birth,$gender,$City->cadastral_code);
		
		return json_encode(array(
			"error" => 0,
			"text" => $fiscal_code,
		));
		exit;
			
	}

	public function actionF22()
	{
		Yii::$app->response->format = Response::FORMAT_JSON;
		
		$request = Yii::$app->request;
		$q = $request->post('q');
		$address_country = $request->post('address_country');
		$country_code = \app\models\Nations::findOne($address_country)->code;
		
		$query = \app\models\LegalForms::find()
		->select(['id', 'name AS text'])
		->where(['like', 'name', $q])
		->andFilterWhere(['country_code' => $country_code])
		->limit(20)
		->asArray()
		->all();

		return ['results' => $query];
	}
	
	// Modal Inserimento Persona Giuridica
	public function actionF23()
	{
		
		$PhoneCodeNumbers = ArrayHelper::map(\app\models\PhoneCodeNumbers::find()->orderBy(["phonecode" => SORT_ASC])->all(), 'id', function($model) {
			return '+' . $model->phonecode.' ('.$model->iso3.')';
		});
		
		$Regions = ArrayHelper::map(\app\models\Regions::find()->orderBy(["name" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$CrmClientStatus = ArrayHelper::map(\app\models\CrmClientStatus::find()->orderBy(["id" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$CrmLanguages = ArrayHelper::map(\app\models\CrmLanguages::find()->orderBy(["id" => SORT_ASC])->all(), 'id', function($model) {
			return $model->name;
		});
		
		$BusinessCategories = \app\models\BusinessCategories::find()->all();
		$BusinessSubcategories = \app\models\BusinessSubcategories::find()->all();
		$items = [];
		foreach ($BusinessCategories as $BusinessCategory) {
			// Trovo le sottocategorie di questa categoria
			$subs = array_filter($BusinessSubcategories, function($sub) use ($BusinessCategory) {
				return $sub->id_category == $BusinessCategory->id;
			});

			// Converto in array id => nome
			$subsList = ArrayHelper::map($subs, 'id', 'name');

			// Aggiungo al gruppo
			$items[$BusinessCategory->name] = $subsList;
		}
		
		$text = '';

		$text .= '<div class="modal-dialog modal-dialog-centered mw-650px">';
			$text .= '<div class="modal-content">';

				// Header
				$text .= '<div class="modal-header">';
					$text .= '<h2 class="modal-title fw-bolder">Persona Giuridica</h2>';
					$text .= '<button type="button" class="btn btn-icon btn-sm btn-active-icon-primary" data-bs-dismiss="modal" aria-label="Chiudi">';
					$text .= '<span class="svg-icon svg-icon-1">';
					$text .= '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">';
					$text .= '<rect opacity="0.5" x="6" y="17.3137" width="16" height="2" rx="1" transform="rotate(-45 6 17.3137)" fill="black" />';
					$text .= '<rect x="7.41422" y="6" width="16" height="2" rx="1" transform="rotate(45 7.41422 6)" fill="black" />';
					$text .= '</svg>';
					$text .= '</span>';
					$text .= '</button>';
				$text .= '</div>';

				$text .= '<div class="modal-body scroll-y mx-5 mx-xl-15 my-7">';
					$text .= '<form id="actionF4Form" class="form" action="#">';
		
						$text .= '<div class="row">';
						
							$text .= '<div class="col-md-6">';
								$text .= Html::dropDownList('entity_type',2,[1 => 'Persona fisica', 2 => 'Azienda'],['class' => 'form-select mb-3', 'prompt' => 'Tipo contatto', 'id' => 'entity_type', 'disabled' => 'disabled']);
								//$text .= Html::dropDownList('entity_type',1,[1 => 'Persona fisica', 2 => 'Azienda'],['class' => 'form-select mb-3', 'prompt' => 'Tipo contatto', 'id' => 'entity_type', 'onchange' => 'entityTypeChange(this)']);
							$text .= '</div>';
							
							$text .= '<div class="col-md-6">';
								$text .= Html::dropDownList('address_country', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_country','data-url' => Url::to(['funzioni/f16']), 'data-placeholder' => 'Nazione...']);
							$text .= '</div>';
						
						$text .= '</div>';
						
						#####################################################################################################
						# Persona Giuridica
						#####################################################################################################

						$text .= '<div class="individual-fields mb-10">';
							
							$text .= '<h5 class="mb-4 mt-6">Dati Azienda</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'business_name', null, ['class' => 'form-control mb-3', 'placeholder' => 'Ragione sociale']);
								$text .= '</div>';
								$text .= '<div class="col-md-6">';
									$text .= Html::dropDownList('company_type', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'company_type','data-url' => Url::to(['funzioni/f22']), 'data-placeholder' => 'Forma giuridica...']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Dati di residenza</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6" id="address_stateDiv">';
									$text .= Html::dropDownList('address_state',null,$Regions,['class' => 'form-select mb-3 address_state12345', 'prompt' => 'Regione', 'id' => 'address_state', 'onchange' => 'actionF17(this)']);
								$text .= '</div>';
								$text .= '<div class="col-md-6" id="address_provinceDiv">';
									$text .= Html::dropDownList('address_province',null,[],['class' => 'form-select mb-3', 'prompt' => 'Provincia', 'id' => 'address_province']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('address_city', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'address_city','data-url' => Url::to(['funzioni/f18']), 'data-placeholder' => 'Cerca città...']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'address_street', null, ['class' => 'form-control mb-3', 'placeholder' => 'Indirizzo']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'address_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Civico']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'address_postal_code', null, ['class' => 'form-control mb-3', 'placeholder' => 'CAP / ZIP']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Dati di fatturazione</h5>';
							
							$text .= '<div class="form-check form-switch mb-5">';
							$text .= Html::checkbox('billing_switch', false, ['class' => 'form-check-input','id' => 'billingSwitch']);
							$text .= Html::label('La sede di fatturazione coincide con quella di residenza', 'billingSwitch', ['class' => 'form-check-label']);
							$text .= '</div>';
							
							$text .= '<div class="col-md-12 billing-field">';
								$text .= Html::dropDownList('billing_country', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'billing_country','data-url' => Url::to(['funzioni/f16']), 'data-placeholder' => 'Nazione di fatturazione...']);
							$text .= '</div>';
							
							$text .= '<div class="row billing-field">';
								$text .= '<div class="col-md-6" id="billing_stateDiv">';
									$text .= Html::dropDownList('billing_state',null,$Regions,['class' => 'form-select mb-3 billing_state', 'prompt' => 'Regione', 'id' => 'billing_state', 'onchange' => 'actionF17(this)']);
								$text .= '</div>';
								$text .= '<div class="col-md-6" id="billing_provinceDiv">';
									$text .= Html::dropDownList('billing_province',null,[],['class' => 'form-select mb-3', 'prompt' => 'Provincia', 'id' => 'billing_province']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('billing_city', null, [], ['class' => 'form-control mb-3 select2-ajax','id' => 'billing_city','data-url' => Url::to(['funzioni/f18']), 'data-placeholder' => 'Cerca città...']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row billing-field">';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'billing_street', null, ['class' => 'form-control mb-3', 'placeholder' => 'Indirizzo']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'billing_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Civico']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::input('text', 'billing_postal_code', null, ['class' => 'form-control mb-3', 'placeholder' => 'CAP / ZIP']);
								$text .= '</div>';
							$text .= '</div>';
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('text', 'vat_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Partita IVA']);
								$text .= '</div>';
								
								
								
								$text .= '<div class="col-md-12 mb-3">';
									$text .= '<div class="d-flex align-items-center">';
										$text .= Html::input('text', 'tax_id', null, [
											'class' => 'form-control me-3',
											'placeholder' => 'Codice fiscale',
											'id' => 'tax_id'
										]);
										$text .= '<div class="form-check form-switch mb-0">';
											$text .= Html::checkbox('tax_idSwitch', false, [
												'class' => 'form-check-input',
												'id' => 'tax_idSwitch',
											]);
											$text .= Html::label('Uguale alla Partita Iva', 'tax_idSwitch', [
												'class' => 'form-check-label',
											]);
										$text .= '</div>';
									$text .= '</div>';
								$text .= '</div>';

								
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('text', 'registration_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Codice univoco']); //Solo se UE
								$text .= '</div>';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('email', 'pec_email', null, ['class' => 'form-control mb-3', 'placeholder' => 'PEC']);
								$text .= '</div>';
								$text .= '<div class="col-md-6">';
									$text .= Html::input('text', 'legal_representative', null, ['class' => 'form-control mb-3', 'placeholder' => 'Legale rappresentante']);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Dati di contatto</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('email', 'email', null, ['class' => 'form-control mb-3', 'placeholder' => 'Email']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-3">';
									$text .= Html::dropDownList('phone_code_number',105,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'phone_code_number']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-9">';
									$text .= Html::input('text', 'phone', null, ['class' => 'form-control mb-3', 'placeholder' => 'Telefono']);
								$text .= '</div>';
								$text .= '<div class="col-md-3">';
									$text .= Html::dropDownList('mobile_code_number',105,$PhoneCodeNumbers,['class' => 'form-select mb-3', 'prompt' => 'Pref.', 'id' => 'mobile_code_number']);
								$text .= '</div>';
								$text .= '<div class="col-md-9">';
									$text .= Html::input('text', 'mobile', null, ['class' => 'form-control mb-3', 'placeholder' => 'Cellulare']);
								$text .= '</div>';

								$text .= '<div class="col-md-12">';
									$text .= Html::input('text', 'website', null, ['class' => 'form-control mb-3', 'placeholder' => 'Sito web']);
								$text .= '</div>';
							$text .= '</div>';

							$text .= '<h5 class="mb-4 mt-6">Social</h5>';
							
							$text .= '<div class="row">';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('facebook', 'facebook', null, ['class' => 'form-control mb-3', 'placeholder' => 'Facebook']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('instagram', 'instagram', null, ['class' => 'form-control mb-3', 'placeholder' => 'Instagram']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('youtube', 'youtube', null, ['class' => 'form-control mb-3', 'placeholder' => 'Youtube']);
								$text .= '</div>';
								
								$text .= '<div class="col-md-12">';
									$text .= Html::input('linkedin', 'linkedin', null, ['class' => 'form-control mb-3', 'placeholder' => 'Linkedin']);
								$text .= '</div>';
								
							$text .= '</div>';
							
							$text .= '<h5 class="mb-4 mt-6">Privacy</h5>';
							
							$text .= '<div class="row mb-4">';
								$text .= '<div class="col-md-12">';
									$text .= Html::checkbox('privacy1', false, [
										'label' => 'Consenso Privacy (GDPR)',
										'class' => 'form-check-input',
										'labelOptions' => ['class' => 'form-check-label'],
									]);
								$text .= '</div>';
							$text .= '</div>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::checkbox('privacy2', false, [
										'label' => 'Consenso Marketing',
										'class' => 'form-check-input',
										'labelOptions' => ['class' => 'form-check-label'],
									]);
								$text .= '</div>';
							$text .= '</div>';

							$text .= '<h5 class="mb-4 mt-6">Altre informazioni</h5>';
							
							$text .= '<div class="row">';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('language',null,$CrmLanguages,['class' => 'form-select mb-3', 'prompt' => 'Lingua preferita', 'id' => 'language']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::textarea('notes', null, [
										'class' => 'form-control mb-3',
										'placeholder' => 'Note',
										'rows' => 4 // puoi modificarlo a piacere
									]);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('number', 'employees_number', null, ['class' => 'form-control mb-3', 'placeholder' => 'Numero dipendenti']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::input('number', 'revenue', null, ['class' => 'form-control mb-3', 'placeholder' => 'Fatturato']);
								$text .= '</div>';
								$text .= '<div class="col-md-12">';
									$text .= Html::dropDownList('status',null,$CrmClientStatus,['class' => 'form-select mb-3', 'prompt' => 'Stato', 'id' => 'status']);
								$text .= '</div>';
							$text .= '</div>';
						
						$text .= '</div>';

					$text .= '</form>';

				$text .= '</div>';

				// Footer
				$text .= '<div class="modal-footer">';
					$text .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>';
					$text .= '<button type="button" class="btn btn-primary actionF24">Salva</button>';
				$text .= '</div>';

			$text .= '</div>';
		$text .= '</div>';

		
		return json_encode(array(
			"error" => 0,
			"text" => $text,
		));
		
	}
	
	# Salvataggio Persona Giuridica
	public function actionF24()
    {
		
		$entity_type = Yii::$app->request->post('entity_type');
		$tax_id = Yii::$app->request->post('tax_id');
		$vat_number = Yii::$app->request->post('vat_number');
		$business_name = Yii::$app->request->post('business_name');
		$registration_number = Yii::$app->request->post('registration_number');
		$first_name = Yii::$app->request->post('first_name');
		$middle_name = Yii::$app->request->post('middle_name');
		$last_name = Yii::$app->request->post('last_name');
		$gender = Yii::$app->request->post('gender');
		$date_of_birth = Yii::$app->request->post('date_of_birth');
		$place_of_birth = Yii::$app->request->post('place_of_birth');
		$email = Yii::$app->request->post('email');
		$phone_code_number = Yii::$app->request->post('phone_code_number');
		$phone = Yii::$app->request->post('phone');
		$mobile_code_number = Yii::$app->request->post('mobile_code_number');
		$mobile = Yii::$app->request->post('mobile');
		$fax = Yii::$app->request->post('fax');
		$pec_email = Yii::$app->request->post('pec_email');
		$website = Yii::$app->request->post('website');
		$address_street = Yii::$app->request->post('address_street');
		$address_number = Yii::$app->request->post('address_number');
		$address_city = Yii::$app->request->post('address_city');
		$address_postal_code = Yii::$app->request->post('address_postal_code');
		$address_province = Yii::$app->request->post('address_province');
		$address_state = Yii::$app->request->post('address_state');
		$address_country = Yii::$app->request->post('address_country');
		
		$billing_switch = Yii::$app->request->post('billing_switch');
		$billing_street = Yii::$app->request->post('billing_street');
		$billing_number = Yii::$app->request->post('billing_number');
		$billing_city = Yii::$app->request->post('billing_city');
		$billing_postal_code = Yii::$app->request->post('billing_postal_code');
		$billing_province = Yii::$app->request->post('billing_province');
		$billing_state = Yii::$app->request->post('billing_state');
		$billing_country = Yii::$app->request->post('billing_country');
		
		$legal_representative = Yii::$app->request->post('legal_representative');
		$company_type = Yii::$app->request->post('company_type');
		$industry = Yii::$app->request->post('industry');
		$employees_number = Yii::$app->request->post('employees_number');
		$revenue = Yii::$app->request->post('revenue');
		$language = Yii::$app->request->post('language');
		$facebook = Yii::$app->request->post('facebook');
		$instagram = Yii::$app->request->post('instagram');
		$youtube = Yii::$app->request->post('youtube');
		$linkedin = Yii::$app->request->post('linkedin');
		$notes = Yii::$app->request->post('notes');
		$status = Yii::$app->request->post('status');
		$client_companies = Yii::$app->request->post('client_companies');
		$privacy1 = Yii::$app->request->post('privacy1');
		$privacy2 = Yii::$app->request->post('privacy2');
		//$created_at = Yii::$app->request->post('created_at');
		
		
		if(!$entity_type){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TIPO ENTITÀ è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!$email){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo EMAIL è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo EMAIL non è un indirizzo valido","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$phone){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TELEFONO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$fax){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo FAX è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_city){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CITTÀ è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_province){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PROVINCIA è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$mobile){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CELLULARE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$pec_email){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PEC è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!filter_var($pec_email, FILTER_VALIDATE_EMAIL)){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PEC non è un indirizzo valido","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$website){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SITO WEB è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_street){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo VIA è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CIVICO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_postal_code){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CAP è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_state){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo STATO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$address_country){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NAZIONE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		if($privacy1){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo Consenso Privacy (GDPR) è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}

		// Persona fisica (entity_type = 1)
		if($entity_type == 1){
			//if(!$first_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$middle_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SECONDO NOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$gender){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo GENERE è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$place_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo LUOGO DI NASCITA è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$last_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo COGNOME è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$date_of_birth){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo DATA DI NASCITA è obbligatorio per persona fisica","warning","bi bi-exclamation-triangle-fill"))); exit;}
		}

		// Azienda (entity_type = 2)
		if($entity_type == 2){
			//if(!$tax_id){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo CODICE FISCALE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$business_name){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo RAGIONE SOCIALE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$company_type){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo TIPO SOCIETÀ è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$employees_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NUMERO DIPENDENTI è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$vat_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo PARTITA IVA è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$registration_number){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NUMERO DI REGISTRAZIONE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$legal_representative){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo LEGALE RAPPRESENTANTE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$revenue){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo FATTURATO è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
			//if(!$industry){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo SETTORE è obbligatorio per azienda","warning","bi bi-exclamation-triangle-fill"))); exit;}
		}

		// Note e Stato (facoltativi, se vuoi farli obbligatori togli commento)
		 //if(!$notes){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo NOTE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$status){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo STATO è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		//if(!$created_at){return json_encode(array("error"=>1,"text"=>\app\models\Functions::ModalMessage("CRM","Il campo DATA CREAZIONE è obbligatorio","warning","bi bi-exclamation-triangle-fill"))); exit;}
		
		$CrmClient = new \app\models\CrmClients();
		$CrmClient->entity_type = $entity_type;
		$CrmClient->tax_id = $tax_id;
		$CrmClient->vat_number = $vat_number;
		$CrmClient->business_name = $business_name;
		$CrmClient->registration_number = $registration_number;
		$CrmClient->first_name = $first_name;
		$CrmClient->middle_name = $middle_name;
		$CrmClient->last_name = $last_name;
		$CrmClient->gender = $gender;
		$CrmClient->date_of_birth = $date_of_birth;
		$CrmClient->place_of_birth = $place_of_birth;
		$CrmClient->email = $email;
		$CrmClient->phone_code_number = $phone_code_number;
		$CrmClient->phone = $phone;
		$CrmClient->mobile_code_number = $mobile_code_number;
		$CrmClient->mobile = $mobile;
		$CrmClient->fax = $fax;
		$CrmClient->pec_email = $pec_email;
		$CrmClient->website = $website;
		$CrmClient->address_street = $address_street;
		$CrmClient->address_number = $address_number;
		$CrmClient->address_city = $address_city;
		$CrmClient->address_postal_code = $address_postal_code;
		$CrmClient->address_province = $address_province;
		$CrmClient->address_state = $address_state;
		$CrmClient->address_country = $address_country;
		
		$CrmClient->billing_switch = $billing_switch?billing_switch:0;
		$CrmClient->billing_street = $billing_street;
		$CrmClient->billing_number = $billing_number;
		$CrmClient->billing_city = $billing_city;
		$CrmClient->billing_postal_code = $billing_postal_code;
		$CrmClient->billing_province = $billing_province;
		$CrmClient->billing_state = $billing_state;
		$CrmClient->billing_country = $billing_country;
		
		$CrmClient->legal_representative = $legal_representative;
		$CrmClient->company_type = $company_type;
		$CrmClient->industry = $industry;
		$CrmClient->employees_number = $employees_number;
		$CrmClient->revenue = $revenue;
		$CrmClient->notes = $notes;
		$CrmClient->language = $language;
		$CrmClient->facebook = $facebook;
		$CrmClient->instagram = $instagram;
		$CrmClient->youtube = $youtube;
		$CrmClient->linkedin = $linkedin;
		$CrmClient->status = $status;
		$CrmClient->created_at = date("Y-m-d H:i");
		$CrmClient->save(false);
		
		foreach($client_companies as $client_company){
			$CrmClientCompany = new \app\models\CrmClientsCompanies();
			$CrmClientCompany->id_client = $CrmClient->id;
			$CrmClientCompany->id_company = $client_company;
			$CrmClientCompany->save(false);
		}

		return json_encode(array("error" => 0,"text" => \app\models\Functions::ModalMessage("PT Elite","Salvataggio effettuato con successo","success","bi bi-check-circle")));
		exit;
		
	}
	
	public function actionP1()
    {
		
		if($xlsx = \app\models\SimpleXLSX::parse('uploads/db PADELSEARCH.xlsx')){
			foreach( $xlsx->rows(0) as $rowArray ) {
				
				$A = $rowArray[0];
				$B = $rowArray[1];
				$C = $rowArray[2];
				$D = $rowArray[3];
				$E = $rowArray[4];
				$F = $rowArray[5];
				$G = $rowArray[6];
				$H = $rowArray[7];
				$I = $rowArray[8];
				$J = $rowArray[9];
				$K = $rowArray[10];
				$L = $rowArray[11];
				$M = $rowArray[12];
				$N = $rowArray[13];
				$O = $rowArray[14];
				$P = $rowArray[15];
				$Q = $rowArray[16];
				$R = $rowArray[17];
				$S = $rowArray[18];
				$T = $rowArray[19];
				$U = $rowArray[20];
				$V = $rowArray[21];
				$W = $rowArray[22];
				$X = $rowArray[23];
				$Y = $rowArray[24];
				$Z = $rowArray[25];
				$AA = $rowArray[26];
				$AB = $rowArray[27];
				$AC = $rowArray[28];
				$AD = $rowArray[29];
				$AE = $rowArray[30];
				$AF = $rowArray[31];
				$AG = $rowArray[32];
				$AH = $rowArray[33];
				$AI = $rowArray[34];
				$AJ = $rowArray[35];
				$AK = $rowArray[36];
				$AL = $rowArray[37];
				$AM = $rowArray[38];
				$AN = $rowArray[39];
				$AO = $rowArray[40];
				$AP = $rowArray[41];
				$AQ = $rowArray[42];
				$AR = $rowArray[43];
				$AS = $rowArray[44];
				$AT = $rowArray[45];
				$AU = $rowArray[46];
				$AV = $rowArray[47];
				$AW = $rowArray[48];
				$AX = $rowArray[49];
				$AY = $rowArray[50];
				$AZ = $rowArray[51];
				$BA = $rowArray[52];
				$BB = $rowArray[53];
				$BC = $rowArray[54];
				$BD = $rowArray[55];
				$BE = $rowArray[56];
				$BF = $rowArray[57];
				$BG = $rowArray[58];
				$BH = $rowArray[59];
				$BI = $rowArray[60];
				$BJ = $rowArray[61];
				$BK = $rowArray[62];
				$BL = $rowArray[63];
				$BM = $rowArray[64];
				$BN = $rowArray[65];
				$BO = $rowArray[66];
				$BP = $rowArray[67];
				$BQ = $rowArray[68];
				$BR = $rowArray[69];
				$BS = $rowArray[70];
				$BT = $rowArray[71];
				$BU = $rowArray[72];
				$BV = $rowArray[73];
				$BW = $rowArray[74];
				$BX = $rowArray[75];
				$BY = $rowArray[76];
				$BZ = $rowArray[77];
				$CA = $rowArray[78];
				$CB = $rowArray[79];
				
				$CrmProjectTargetContacts = \app\models\CrmProjectTargetContacts::find()->where(["company" => $A])->one();
				if($CrmProjectTargetContacts){
					if($H){
						$CrmProjectTargetContacts->website = trim($H);
						$CrmProjectTargetContacts->updated_at = strtotime(date("Y-m-d H:i:s"));
						$CrmProjectTargetContacts->save(false);
					}
				}
				
			}
		}
		
	}
	
	// Adeguamento dei campi longitude e latitude nella tabella "crm_project_target_contacts"
	public function actionP2()
    {
		
		$CrmProjectTargetContacts = \app\models\CrmProjectTargetContacts::find()
		//->where(["id" => 5224])
		->all();
		
		foreach($CrmProjectTargetContacts as $CrmProjectTargetContact){
		
			$building_address = $CrmProjectTargetContact->address?$CrmProjectTargetContact->address:"";
			$building_postal_code = $CrmProjectTargetContact->postal_code?$CrmProjectTargetContact->postal_code:"";
			$city = $CrmProjectTargetContact->city?$CrmProjectTargetContact->city:"";
			$province = $CrmProjectTargetContact->province_rel?$CrmProjectTargetContact->province_rel->code:"";
			$region = $CrmProjectTargetContact->region_rel?$CrmProjectTargetContact->region_rel->name:"";
			
			
			$url = "https://maps.google.com/maps/api/geocode/json?key=AIzaSyCj5fH1EA5mVg27sDVAEZrPQso1wYfqtS0&address=".urlencode($building_address.",".$building_postal_code.",".$city.",".$province.",".$region);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
			$responseJson = curl_exec($ch);
			curl_close($ch);
			$response = json_decode($responseJson);
			
			$CrmProjectTargetContact->longitude = $response->results?$response->results[0]->geometry->location->lng:0;
			$CrmProjectTargetContact->latitude = $response->results?$response->results[0]->geometry->location->lat:0;
			$CrmProjectTargetContact->save(false);
		
		}
		
	}
	
	//Caricamento del Padel Center da Mr Padel Paddle
	public function actionP3()
    {
		
		\app\models\Test::deleteAll();
		//123,54,35,76,192
		//$WpMrpaddleStrutture = \app\models\WpMrpaddleStrutture::find()->all();
		$WpMrpaddleStrutture = \app\models\WpMrpaddleStrutture::find()->where(["id_nazioneStruttura" => 223])->all();
		foreach($WpMrpaddleStrutture as $WpMrpaddleStruttura){
			$WpMrpaddleNazioni = \app\models\WpMrpaddleNazioni::findOne($WpMrpaddleStruttura->id_nazioneStruttura);
			$Nations = \app\models\Nations::find()->where(["name" => $WpMrpaddleNazioni->nameNationEN])->one();
			$CrmProjectTargetContacts = \app\models\CrmProjectTargetContacts::find()->where(["company" => $WpMrpaddleStruttura->nomeStruttura])->andWhere(["nation" => $Nations?$Nations->name:0])->one() ?? new \app\models\CrmProjectTargetContacts();
		
			if(!$Nations){
				$Test = new \app\models\Test();
				$Test->value1 = $WpMrpaddleNazioni->nameNationEN;
				$Test->value2 = "Nazione non trovata";
				$Test->save(false);
				continue;
			}
			
			if(\app\models\CrmProjectTargetContacts::find()->where(["company" => $WpMrpaddleStruttura->nomeStruttura])->andWhere(["nation" => $Nations?$Nations->name:0])->one()){
				$Test = new \app\models\Test();
				$Test->value1 = $CrmProjectTargetContacts->company;
				$Test->value2 = "Azienda doppione";
				$Test->save(false);
			}
			
			
			$CrmProjectTargetContacts->id_project = 197;
			$CrmProjectTargetContacts->id_target = 601;
			$CrmProjectTargetContacts->id_status = NULL;
			$CrmProjectTargetContacts->contact_date = NULL;
			$CrmProjectTargetContacts->company = trim($WpMrpaddleStruttura->nomeStruttura);
			$CrmProjectTargetContacts->telephone_pref = NULL;
			$CrmProjectTargetContacts->telephone = $WpMrpaddleStruttura->telefonoStruttura;
			$CrmProjectTargetContacts->smartphone = NULL;
			$CrmProjectTargetContacts->note = $WpMrpaddleStruttura->noteStruttura;
			$CrmProjectTargetContacts->referent = NULL;
			$CrmProjectTargetContacts->referent_email = NULL;
			$CrmProjectTargetContacts->general_email = $WpMrpaddleStruttura->emailStruttura;
			$CrmProjectTargetContacts->employees = NULL;
			$CrmProjectTargetContacts->revenue = NULL;
			$CrmProjectTargetContacts->website = $WpMrpaddleStruttura->url_sitoStruttura;
			$CrmProjectTargetContacts->vat_number = NULL;
			$CrmProjectTargetContacts->address = $WpMrpaddleStruttura->indirizzoStruttura;
			$CrmProjectTargetContacts->postal_code = $WpMrpaddleStruttura->capStruttura;
			$CrmProjectTargetContacts->postal_code = $WpMrpaddleStruttura->capStruttura;
			##############################################
			$Cities = \app\models\Cities::find()->where(["name" => $CrmProjectTargetContacts->city])->andWhere(["id_nation" => $Nations->id])->one();
			if($Cities){
				$CrmProjectTargetContacts->city = $Cities->name;
				$CrmProjectTargetContacts->province = $Cities->province_rel?$Cities->province_rel->name:NULL;
				$CrmProjectTargetContacts->region = $Cities->region_rel?$Cities->region_rel->name:NULL;
				$CrmProjectTargetContacts->nation = $Cities->nation_rel?$Cities->nation_rel->name:NULL;
			}
			if(!$Cities){
				$CrmProjectTargetContacts->city = NULL;
				$CrmProjectTargetContacts->province = NULL;
				$CrmProjectTargetContacts->region = NULL;
				//$CrmProjectTargetContacts->nation = NULL;
				$CrmProjectTargetContacts->nation = $Nations->name;
			}
			##############################################
			$CrmProjectTargetContacts->tags = NULL;
			$CrmProjectTargetContacts->tags_search = NULL;
			$CrmProjectTargetContacts->monthly_visits = NULL;
			$CrmProjectTargetContacts->sector = NULL;
			$CrmProjectTargetContacts->category = NULL;
			$CrmProjectTargetContacts->referent_linkedin = NULL;
			$CrmProjectTargetContacts->company_linkedin = NULL;
			$CrmProjectTargetContacts->used_platform = NULL;
			$CrmProjectTargetContacts->monthly_shipments = NULL;
			$CrmProjectTargetContacts->used_courier = NULL;
			$CrmProjectTargetContacts->privacy = NULL;
			$CrmProjectTargetContacts->privacy_date = NULL;
			
			if ($CrmProjectTargetContacts->isNewRecord) {
				$CrmProjectTargetContacts->code = \app\models\Functions::getCompanyCode();
			}
			
			$CrmProjectTargetContacts->ateco_code = NULL;
			$CrmProjectTargetContacts->id_projects = NULL;
			$CrmProjectTargetContacts->longitude = $WpMrpaddleStruttura->longitudineStruttura;
			$CrmProjectTargetContacts->latitude = $WpMrpaddleStruttura->latitudineStruttura;
			$CrmProjectTargetContacts->source = NULL;
			$CrmProjectTargetContacts->business_supply_chain = "Padel Courts";
			$CrmProjectTargetContacts->synch = 0;
			$CrmProjectTargetContacts->created_at = NULL;
			$CrmProjectTargetContacts->updated_at = strtotime(date("Y-m-d H:i:s"));
			$CrmProjectTargetContacts->save(false);

					
		}
		
	}
	
}