<?php
require_once __DIR__.'/../include/autoload.php';
require_once __DIR__.'/../include/Page.Class.php';

$title="Management / Utenti";

$Page = new Page();
$Page->Title = $title;
$Page->SetIcon('pie_chart');


if(is_backoffice()){
$Role_Values = array(
    'admin' => 'Admin',
    'consulente' => 'Consulente',
   // 'staff' => 'Staff Ufficio',
    'team_leader' => 'Team Leader',
   // 'recruiter' => 'Recruiter',
    'segnalatore' => 'Segnalatore',
   // 'buyer' => 'Acquirente',
   // 'seller' => 'Venditore'
);
} else {
$Role_Values = array(
    'segnalatore' => 'Segnalatore',
   // 'buyer' => 'Acquirente',
   // 'seller' => 'Venditore'
);
}

if(request_ifset('name') && request_ifset('role') && request_ifset('pswd') && request_ifset('email')) {

  

  $UserObj = new stdClass();
  
  //$UserObj->team_id                  = request_ifset('name');  
  $UserObj->full_name                = request_ifset('name');
  $UserObj->role                     = request_ifset('role');
  $UserObj->pswd                     = request_ifset('pswd');
  $UserObj->email                    = request_ifset('email');
  $UserObj->pswd_hashed              = better_crypt($UserObj->pswd);
  
  if($UserObj->role == 'segnalatore') $add_sql=", owned_by = '{$User->id}'";

  save_in_db("INSERT INTO users SET  name = '{$UserObj->full_name}', email = '{$UserObj->email}', pswd = '{$UserObj->pswd_hashed}', role = '{$UserObj->role}', status = 1, company_id = ".COMPANY_ID." $add_sql");
    
  if(request_ifset('sendEmail')){
    if($UserObj->role == 'segnalatore') {

        $EmailContent = <<<EOD
        <h1 style="line-height:1.0">Il tuo account è attivo!</h1>
    
        <p>Gentile {$UserObj->full_name},<br/>
        ti confermiamo l'attivazione del tuo account <b>{$Page->REFERRAL_APP_NAME}</b>.<br/>
        <br/>Seguono le credenziali:<br/>
        <b>USER:</b> {$UserObj->email}<br/>
        <b>PASS:</b> {$UserObj->pswd}<br/>
        <span style="font-size:0.8em"> <i>Consigliamo di cambiare la tua password al primo accesso.</i></span>
        <hr/>
        
        Puoi installare la nostra app:<br/>
        {$Page->BASE_URL_HTTPS}/install<br/><br/>
    
        oppure accedere dal tuo browser, da questo indirizzo: <br/>
        {$Page->BASE_URL_HTTPS}<br/>
        
        
        <hr/>
        EOD;
        
        $EmailContent =  mount_email_template($EmailContent, 1, $Page);
        SendEmail("Il tuo account è attivo! | {$Page->REFERRAL_APP_NAME}",  $EmailContent,  $UserObj->email, REFERRAL_APP_NAME, 'notifications@mybrokerage.it');
    
        
      } else {
        
        $EmailContent = <<<EOD
        <h1 style="line-height:1.0">Il tuo account è attivo!</h1>
    
        <p>Gentile {$UserObj->full_name},<br/>
        ti confermiamo l'attivazione del tuo account <b>{$Page->PLATFORM_NAME}</b>.<br/>
        <br/>Seguono le credenziali:<br/>
        <b>USER:</b> {$UserObj->email}<br/>
        <b>PASS:</b> {$UserObj->pswd}<br/>
        <span style="font-size:0.8em"> <i>Consigliamo di cambiare la tua password al primo accesso.</i></span>
        <hr/>
        
        Puoi installare l'app da qui:<br/>
        {$Page->BASE_URL_HTTPS}/install<br/><br/>
    
        oppure accedere dal tuo browser, da questo indirizzo: <br/>
        {$Page->BASE_URL_HTTPS}<br/>
        
        <hr/>
        EOD;
        
        $EmailContent =  mount_email_template($EmailContent, 1, $Page);
        SendEmail("Il tuo account è attivo! | {$Page->PLATFORM_NAME}",  $EmailContent,  $UserObj->email, PLATFORM_NAME, 'notifications@mybrokerage.it');
    
      }
  }



if(!isset($error)) $msg = "Utente creato correttamente.";
else $msg = $error;

$Body = <<<EOD
        <!-- Main content -->
        <section class="content">
	    <div class="row">
		<div class="card">
		  <div class="card-header plaincolor" data-background-color="red">
		     Crea un nuovo utente
		  </div>
		  <div class="card-body">
			     $msg
			  </div><!-- /.box-body -->
			</div><!-- /.box -->
		</div>
	    </div>
	</section><!-- /.content -->
EOD;

} else {

if(is_backoffice()){
     
    $UsersList = GetListWhere('users', "email NOT LIKE '%superadmin%'", true);

} else {
    
    $UsersList = GetListWhere('users', "owned_by = '{$User->id}' AND email NOT LIKE '%superadmin%'", true);

}
$tr="";
foreach ($UsersList as $UserData){

    $UserData->email = empty_so_trattino($UserData->email);
    switch($UserData->status){
        case 0:
        $UserData->status = 'Disabilitato';
        break;
        case 1:
        $UserData->status = 'Attivo';
        break;
    }
	if(!empty($UserData->telegram_id)){
	$UserData->telegram_check = <<<EOD
	<img width="32" src="https://upload.wikimedia.org/wikipedia/commons/8/82/Telegram_logo.svg" />
EOD;
	}

    if(is_backoffice()) {

    
    $td_aggiuntivo = <<<EOD
    <td>{$UserData->telegram_check} |  <a style="color:#fff" href="{$Page->BASE_URL_HTTPS}/admin/user/{$UserData->id}"><button class="btn btn-primary btn-xs"><i class="fa-solid fa-pen-to-square pr-2" style="color:#fff"></i> Modifica</button></a>
EOD;
} else { $td_aggiuntivo = '<td>'; }

$tr.=<<<EOD
<tr>
  <td>{$UserData->id}
  <td>{$UserData->name}
  <td>{$UserData->cell}
  <td>{$UserData->email}
  <td>{$UserData->status}
  <td>{$UserData->piano}
  <td>{$UserData->role}
  $td_aggiuntivo
</tr>

EOD;
}




$Body=<<<EOD
        <!-- Main content -->
        <section class="content">
	    <div class="row">
		<div class="col-md-6">
			<div class="card">
		  <div class="card-header plaincolor" data-background-color="red">
		      Crea un Nuovo Utente
		  </div>
		  <div class="card-body">
			     <form method="POST" action="">
				<div class="input-group">
				

				<div class="form-group col-md-6">
                    <label>Nome e Cognome</label>
                    <input placeholder="Mario Rossi" required type="text" class="form-control" name="name" />
                </div>
				<div class="form-group col-md-6">
                    <label>Email</label>
                    <input placeholder="mario@rossi.it" required type="text" class="form-control" name="email" />
                </div>
				<div class="form-group col-md-6">
                    <label>Password</label>
                    <input placeholder="" required type="password" autocomplete="off" class="form-control" name="pswd" />
                </div>
				<div class="form-group col-md-6">
                    <label>Tipo account</label>
                    {$fn(input_select('role',$Role_Values,'','select2'))}
                </div>
                <div class="custom-control custom-checkbox form-group">
                    <input type="checkbox" class="custom-control-input" name="sendEmail" id="emailCheck">
                    <label class="custom-control-label" for="emailCheck">Invia email con le credenziali</label>
                </div>
				 
				</div>
                <div class="card-footer">
                <button class="btn btn-primary btn-block" type="submit">Crea utente!</button>

                </div>
			      </form>
			  </div><!-- /.box-body -->
			</div><!-- /.box -->
		</div>
		
		<div class="col-md-12">
			<div class="card">
		  <div class="card-header " data-background-color="red">
		      Utenti attivi
		  </div>
		  <div class="card-content">
			    <div class="table-responsive">
			     <table class="table table-striped" id="users">
			      <thead>
			      <tr>
                        <th>ID
                        <th>Nome
                        <th>Cell
                        <th>Email
                        <th>Status
                        <th>Piano
                        <th>Ruolo
                        <th>Azioni
			      </tr>
			      </thead>
			      
                    $tr
			      
			      </table
			    </div>
			  </div><!-- /.box-body -->
			</div><!-- /.box -->
		</div>
	    </div>
	</section><!-- /.content -->

EOD;

$Page->AddToFooter = <<<EOD
<script>

$(document).ready(function() {
    $('#users').DataTable( {
        dom: 'PfBlrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
        stateSave: true,
        "pageLength": 25
    });
});

</script>
EOD;
}
echo $Page->Output($Body);

?>
