<?php
//ce fichier contient les fonctions propre à l'application encours
 /* Namespace alias. */
 use PHPMailer\PHPMailer\PHPMailer;
 use PHPMailer\PHPMailer\Exception;


//TODO : NewSelect - WORKSHORE PHP FrameWork 1.0

function findInArrayByColumn($ref,$value,$array) {
  if (!isset($array)) {
      return null;
  }

  foreach ($array as $row) {
      if (isset($row[$ref]) && $row[$ref] === $value) {
          return $row;
      }
  }

  return null; // si aucun row trouvé avec cette référence
}

function NewSelect( 
  $list,
  $selectname,
  $optionrow,
  $valuerow,
  $defaultoption,
  $defaultvalue,
  $isrequired = false
) {
  //afficher une select 
  $required = "";
  if($isrequired) { $required = "required";} else {$required="";}
  //prepare select
  $select =
      '<select class="form-control" name=' .
      $selectname .
      ' '.$required.
      '>
                      <option value="' .
      $defaultoption .
      '" selected>' .
      $defaultvalue .
      '</option>';
  foreach ($list as $row) {
      $select .=
          '<option value="' .
          $row[$optionrow] .
          '">' .
          $row[$valuerow] .
          '</option>';
          $select .= '</select>';
  }
  $select .= '</select>';
  //return select
  return $select;
}
function NewSelectMore( 
  $list,
  $selectname,
  $optionrow,
  $valuerows,
  $defaultoption,
  $defaultvalue,
  $isrequired = false
) {
  //afficher une select 
  $required = "";
if($isrequired) { $required = "required";} else {$required="";}
  //prepare select
  $select =
      '<select class="form-control" name=' .
      $selectname .
      ' '.$required.
      '>
                      <option value="' .
      $defaultoption .
      '" selected>' .
      $defaultvalue .
      '</option>';
  foreach ($list as $row) {
    $valuemore = "";
    foreach($valuerows as $valuerow ){
      $valuemore .= $row[$valuerow].' ';
    }
      $select .=
          '<option value="' .
          $row[$optionrow] .
          '">' .
          $valuemore .
          '</option>';      
  }
  $select .= '</select>';
  //return select
  return $select;
}
//TODO: ShowExtraFields - WORKSHORE PHP FrameWork 1.0
function NewFormExtraFields($object,$values = "",$useDefault = true){
  //get list of extra fields :
  $extrainputs = "";
foreach($_SESSION['CONFIG'][$object]['EXTRAFIELDS'] as $field){
  $required = "";
  $mark = "";
  if($field['null'] == false) {
    $required = "required";
    $mark = "*";
  }

$input = '<label>'.$field['name'].' '.$mark.'</label>';

switch($field['type']){
    case "TEXTE": 
        case "TEL":
            case "EMAIL":
              $value="";
              if(!empty($values[$field['name']])){
                $value = $values[$field['name']];
              }elseif($useDefault && !empty($field['defaultvalue'])){
                $value = $field['defaultvalue'];
              }                                    
             
              $input .= '<input type='.$field['type'].' name="'.$field['name'].'" value="'.$value.'" class="form-control" '.$required.'/>';
    break;
        case "DATE":
                  $value=date('Y-m-d');//today par defaut
                  if(!empty($values[$field['name']])){
                    $value = $values[$field['name']];
                  }elseif($useDefault && !empty($field['defaultvalue'])){
                    $value = $field['defaultvalue'];
                  }                                    

                  $input .= '<input type='.$field['type'].' name="'.$field['name'].'" value="'. date('Y-m-d',$value).'" class="form-control" '.$required.'/>';
        break;
        case "SELECT":
         
     $input .=  '<select class="form-control" name=' . $field['name'] .' '.$required.'>';
   
     if(!empty($values[$field['name']])){
      $input .='<option value="'.$values[$field['name']].'" selected>'.$values[$field['name']].'</option>';
     }elseif($useDefault && !empty($field['defaultvalue'])){
        $input .='<option value="'.$field['defaultvalue'].'" selected>'.$field['defaultvalue'] .'</option>';
     }else{
      $input .='<option value="" selected disabled></option>';
     }
            $list = explode(',',$field['values']);

            foreach ($list as $option) {
                $options .=
                    '<option value="'.$option.'">'.$option.'</option>';                   
            }

    $input .=  $options.'</select>' ;
    break;
}

$extrainputs .= $input;
}
//addMsg('debug','Extras :'.$extrainputs);
return $extrainputs;

}


function  sendEmailHtmlSmtp($to, $toName, $subject, $body,$fromEmail="", $fromName="" )
{
  try {
  global $emailNotification,  $_appName;
if(empty($fromEmail)){ $fromEmail =  $emailNotification;}
if(empty($fromName)){ $fromName =  $_appName;}
/* Include the Composer generated autoload.php file. */
//require 'C:\xampp\composer\vendor\autoload.php';

/* If you installed PHPMailer without Composer do this instead: */

require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';


/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
$mail->IsSMTP();
$mail->Mailer = "smtp";

$mail->SMTPDebug  = 0;  
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
$mail->Username   = "amar.rapso@gmail.com";
$mail->Password   = "jnfovbrzlarmwvvv";

/* Open the try/catch block. */

   /* Set the mail sender. */
   $mail->setFrom($fromEmail, $fromName);

   /* Add a recipient. */
   $mail->addAddress($to, $toName);
   addMsg('debug','to:'.$to.'/'.$toName);
   /* Set the subject. */
   $mail->Subject = $subject;

   /* Set the mail message body. */
   $mail->Body = $body;

  $mail->IsHTML(true); 

   /* Finally send the mail. */
   $mail->send();
   return true;
}
catch (Exception $e)
{
   /* PHPMailer exception. */
   //echo $e->errorMessage();
  catcherror($e,"Error sending Email");
  //addlog("Error sending email ".$e->errorMessage());
  return false;
}
catch (\Exception $e)
{
   /* PHP exception (note the backslash to select the global namespace Exception class). */
   catcherror($e,"Error sending Email");
   //addlog("Exception ".$e->errorMessage());
   return false;

}
}


function  sendEmailHtmlSmtpToList($tolist,$subject, $body,$fromEmail="", $fromName="" )
{
  try {
  global $emailNotification,  $_appName;
if(empty($fromEmail)){ $fromEmail =  $emailNotification;}
if(empty($fromName)){ $fromName =  $_appName;}
/* Include the Composer generated autoload.php file. */
//require 'C:\xampp\composer\vendor\autoload.php';

/* If you installed PHPMailer without Composer do this instead: */

require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';


/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
$mail->IsSMTP();
$mail->Mailer = "smtp";

$mail->SMTPDebug  = 0;  
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
//$mail->Username   = "amar.rapso@gmail.com";
//$mail->Password   = "jnfovbrzlarmwvvv";

$mail->Username   = "tel0626090018@gmail.com";
$mail->Password   = "ykiq vlbl grmj gqyb";

/* Open the try/catch block. */

   /* Set the mail sender. */
   $mail->setFrom($fromEmail, $fromName);

   /* Add recipients. */
 
   foreach($tolist as $email => $name)
  {
 
   //  if(!array_search($email,$mail->getToAddresses())){

      $mail->addAddress($email, $name);
      addMsg('debug','to:'.$email.'/'.$name);
   // }
    
  }
  

   /* Set the subject. */
   $mail->Subject = $subject;

   /* Set the mail message body. */
   $mail->Body = $body;

  $mail->IsHTML(true); 

   /* Finally send the mail. */
   $mail->send();
   return true;
}
catch (Exception $e)
{
   /* PHPMailer exception. */
   //echo $e->errorMessage();
  catcherror($e,"Error sending Email");
  //addlog("Error sending email ".$e->errorMessage());
  return false;
}
catch (\Exception $e)
{
   /* PHP exception (note the backslash to select the global namespace Exception class). */
   catcherror($e,"Error sending Email");
   //addlog("Exception ".$e->errorMessage());
   return false;

}
}



function sendEmailValidation($pccref,$pccname,$toemail,$toname,$fromname)
{
  try {
    $appTitle = $_SESSION['CONFIG']['APPTITLE'];

    //get user email

    if (!empty($toemail)) {
        $subject = $appTitle . " - Vous avez une nouvelle demande de validation";

            
             $msg = '
                    <html>
                    <head>
                    <title>' . $subject . '</title>
                    </head>
                    <body>      
                    <table>       
                    <tr>
                        <td>Bonjour '.$toname.',</td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>Vous avez eu une demande de validation du PCC '.$pccname.' de la part de '.$fromname.'</td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Click sur ce lien pour ouvrir sur le PCC : 
                    <a href="'.$_SESSION['CONFIG']['FULLURL'].'/modules/pcc/pcc.php?a=saisirpcc&ref='.$pccref.'">'.$pccname.'</a>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                        <td><i>' . trad('Please do not replay to this system email') . '</i></td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    '.$appTitle.'
                    </td>
                    </tr>
                    </table>
                    </body>
                    </html>
                    ';

       //if (sendEmailhtml($email, $subject, $msg)) {
        if (sendEmailHtmlSmtp($toemail,$toname, $subject, $msg,"",$fromname)) {            
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
  }
  catch (Exception $e)
  {
     /* PHPMailer exception. */
     //echo $e->errorMessage();
    catcherror($e,"Error sending Email");
    //addlog("Error sending email ".$e->errorMessage());
    return false;
  }
  catch (\Exception $e)
  {
     /* PHP exception (note the backslash to select the global namespace Exception class). */
     catcherror($e,"Error sending Email");
     //addlog("Exception ".$e->errorMessage());
     return false;
  
  }
}


function sendEmailFinValidationPcc($pccref,$pccname,$tolist)
{
  try {
    $appTitle = $_SESSION['CONFIG']['APPTITLE'];

    //get user email

    if (!empty($tolist)) {
        $subject = $appTitle . " - Le PCC a été validé";

            
             $msg = '
                    <html>
                    <head>
                    <title>' . $subject . '</title>
                    </head>
                    <body>      
                    <table>       
                    <tr>
                        <td>Bonjour,</td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>Fin de validation du PCC '.$pccname.'</td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Click sur ce lien pour ouvrir sur le PCC : 
                    <a href="'.$_SESSION['CONFIG']['FULLURL'].'/modules/pcc/pcc.php?a=saisirpcc&ref='.$pccref.'">'.$pccname.'</a>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                        <td><i>' . trad('Please do not replay to this system email') . '</i></td>
                    </tr>
                    <tr>
                    <td>
                    </td>
                    </tr>
                    <tr>
                    <td>
                    '.$appTitle.'
                    </td>
                    </tr>
                    </table>
                    </body>
                    </html>
                    ';

       //if (sendEmailhtml($email, $subject, $msg)) {
        if (sendEmailHtmlSmtpToList($tolist, $subject, $msg)) {            
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
  }
  catch (Exception $e)
  {
     /* PHPMailer exception. */
     //echo $e->errorMessage();
    catcherror($e,"Error sending Email");
    //addlog("Error sending email ".$e->errorMessage());
    return false;
  }
  catch (\Exception $e)
  {
     /* PHP exception (note the backslash to select the global namespace Exception class). */
     catcherror($e,"Error sending Email");
     //addlog("Exception ".$e->errorMessage());
     return false;
  
  }
}

function sendEmailResetPassword($usernameOrEmail)
{
    global $nameofdb, $dbusername, $dbpassword, $dbprefix, $appTitle;

    $dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = "update " . $dbprefix . "users 
    set canresetpassword = 1 , 
    tokenresetpass = PASSWORD(:token)
     WHERE email like :p 
     limit 1";

    addMsg("debug", $query);

    $stmt = $dbh->prepare($query);
    $stmt->bindValue(':p', $usernameOrEmail);
    $ptoken = rand(1111, 9999);
    $stmt->bindValue(':token', $ptoken);

    $stmt->execute();


    if ($stmt) {
        //check if user is updated, and send email

        $stmt = $dbh->prepare("SELECT * FROM " . $dbprefix . "users 
        WHERE email like :p 
         and tokenresetpass like PASSWORD(:token) 
         AND canresetpassword = 1 
         limit 1");

        $stmt->bindValue(':p', $usernameOrEmail);
        $stmt->bindValue(':token', $ptoken);

        $stmt->execute();
        $result = $stmt->fetch();
        //if param isnt an email then get email 
        $email = $result['email'];
        $resetpasstoken = $result['tokenresetpass'];


        if (!empty($email)) {
            $subject = $appTitle . " RESET PASSWORD REQUEST";
            $msg = 'Hello ' . $result['firstname'] . $result['lastname'].",
            Someone has request to reset your password, if you have forgot your password, please 
            click on this link : 
            ".$_SESSION['CONFIG']['FULLURL']."/resetpassword.php?token=" . $resetpasstoken . "
            
            Please ignore this email if you dont want to change your password.
             
             Regards,
             " . $appTitle;

            if (sendEmailHtmlSmtp($email, $result['username'] , $subject, $msg)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
    $dbh = null;
}


