<?php

// +-------------------------------------------------+
// | 2002-2012 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: mailing_empr.class.php,v 1.37.2.1.2.2 2025/10/08 12:19:27 qvarin Exp $

if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access");

use Pmb\Animations\Controller\MailingController;

global $class_path, $include_path;
require_once($class_path."/campaigns/campaign.class.php");
require_once($class_path.'/emprunteur_datas.class.php');
require_once($include_path."/mailing.inc.php");
require_once($include_path."/mail.inc.php");

class mailing_empr {

    const TYPE_CADDIE = 1;
    const TYPE_SEARCH_PERSO = 2;
    const TYPE_EMPR = 3;

	public $id_list;
	public $total = 0;
	public $total_envoyes = 0;
	public $envoi_KO = 0;
	public $email_cc = '';
	public $sended_bcc = false;
	public $object_tpl = '';
	public $content_tpl = '';
	public $attachments = [];
	public $files = [];
	public $associated_campaign = '';
	public $associated_num_campaign = 0;
	public $type;
	public $error = false;
	public $mailtpls;

	public function __construct($id_list=0, $email_cc='', $type = self::TYPE_CADDIE) {
	    $this->id_list = intval($id_list);
		$this->email_cc = trim($email_cc);
		$this->type = $type;
	}

	public function get_mailtpls() {
	    if (!isset($this->mailtpls)) {
	        $this->mailtpls = new mailtpls();
	    }
	    return $this->mailtpls;
	}

	public function get_mailtpls_content_form() {
	    global $msg, $base_path;

	    return "
        <div class='row'>
	       <label class='etiquette' >".$msg["admin_mailtpl_sel"]."</label>
	       <div class='row'>
    	       <div class='left'>
    	           ".$this->get_mailtpls()->get_sel('mailtpl_id',0)."
                   <input type='button' class='bouton' value=\" ".$msg["admin_mailtpl_insert"]." \"
    				onClick=\"insert_template(document.getElementById('mailtpl_id'), document.getElementById('f_objet_mail'), document.getElementById('f_message')); return false; \" />
                </div>
    			<div class='right'>
    				".(SESSrights & ADMINISTRATION_AUTH ? "<a onclick=\"parent.location='".$base_path."/admin.php?categ=mailtpl&sub=build'\" style='cursor:pointer;'>".$msg['admin_mailtpl_title']."</a>" : "")."
    			</div>
    		</div>
    	</div>";
	}

	public function get_content_form() {
	    global $msg, $deflt_associated_campaign;

	    $mailtpls_content_form = '';
	    if($this->get_mailtpls()->get_count_tpl()) {
	        $mailtpls_content_form = $this->get_mailtpls_content_form();
	    }
	    $interface_content_form = new interface_content_form(static::class);
	    $interface_content_form->add_element('f_objet_mail', 'empr_mailing_form_obj_mail')
	    ->add_input_node('text', $this->object_tpl)
	    ->set_class('saisie-80em');
	    $interface_content_form->add_element('f_message', 'empr_mailing_form_message')
	    ->add_textarea_node($this->content_tpl, 100, 20);

	    $interface_content_form->add_element('selvars', 'admin_mailtpl_form_selvars')
	    ->add_html_node(mailtpl::get_selvars());
	    $sel_img=mailtpl::get_sel_img();
	    if($sel_img) {
	        $interface_content_form->add_element('sel_img', 'admin_mailtpl_form_sel_img')
	        ->add_html_node($sel_img);
	    }

	    $interface_content_form->add_element('attachments', 'empr_mailing_form_message_piece_jointe')
	    ->set_label($msg["empr_mailing_form_message_piece_jointe"]." (".ini_get('upload_max_filesize').")")
	    ->add_html_node(mailtpl::get_attachments_content_form());
	    $interface_content_form->add_element('associated_campaign', 'associated_campaign', 'flat')
	    ->add_input_node('boolean', $deflt_associated_campaign);
	    return $mailtpls_content_form.$interface_content_form->get_display();
	}

	public function get_form() {
	    global $msg;

	    $interface_form = new interface_circ_mailing_form('form_message');
	    $interface_form->set_enctype('multipart/form-data');
	    switch ($this->type) {
	        case self::TYPE_EMPR :
	            $interface_form->set_idempr($this->id_list);
	            break;
	        default:
	            $interface_form->set_idemprcaddie($this->id_list);
	            break;
	    }
	    $interface_form->set_mailtpls($this->get_mailtpls())
        ->set_label($msg['empr_mailing_titre_form'])
	    ->set_content_form($this->get_content_form());
	    return $interface_form->get_display();
	}

	protected function get_src_visualizer() {
	    switch ($this->type) {
	        case self::TYPE_EMPR :
	            return "./circ/caddie/action/visu_message.php";
	            break;
	        case self::TYPE_CADDIE :
	        case self::TYPE_SEARCH_PERSO :
	            return "./visu_message.php";
	    }
	}

	public function get_visualizer() {
	    global $msg, $charset;

	    return "
        <div class='row'>
			<label class='etiquette'>
                ".htmlentities($msg['empr_mailing_form_obj_mail'], ENT_QUOTES, $charset)."
            </label>
        </div>
		<div class='row'>
			".htmlentities($this->object_tpl,ENT_QUOTES,$charset)."
		</div>
		<div class='row'>
			<label class='etiquette'>
                ".htmlentities($msg['empr_mailing_form_message'], ENT_QUOTES, $charset)."
            </label>
        </div>
		<div class='row'>
			<span class='center'>
				<iframe id='visu_message' name='visu_message' frameborder='2' scrolling='yes' width='80%' height='700' src='".$this->get_src_visualizer()."'></iframe>
			</span>
		</div>
		";
	}

	public function set_properties_from_form() {
	    global $associated_campaign, $associated_num_campaign;

	    $this->associated_campaign  = (isset($associated_campaign) ? intval($associated_campaign) : 0);
	    $this->associated_num_campaign  = (isset($associated_num_campaign) ? intval($associated_num_campaign) : 0);
	}

	public function set_attachments_from_form() {
	    global $base_path;
	    global $files_post, $count_files;

	    $this->attachments = array();
	    $this->files = array();
	    $this->error = false;
	    if(is_array($_FILES['pieces_jointes_mailing']['tmp_name']) && count($_FILES['pieces_jointes_mailing']['tmp_name'])){
	        foreach ( $_FILES['pieces_jointes_mailing']['tmp_name'] as $key => $tmp_file ) {
	            if(trim($_FILES['pieces_jointes_mailing']['name'][$key]) && $_FILES['pieces_jointes_mailing']['size'][$key]){
	                $to_file = $base_path.'/temp/'.basename($tmp_file);
	                $from_file = $_FILES['pieces_jointes_mailing']['name'][$key];
	                if (!@move_uploaded_file($tmp_file,$to_file)) {
	                    /* Fail to copy %s, Contact your admin... */
	                    $this->error = 1;
	                }else{
	                    $this->attachments[] = array("nomfichier"=>$from_file,"contenu"=>file_get_contents($to_file));
	                    $this->files[]=array("name"=>$from_file,"location"=>$to_file);
	                }
	            }elseif(trim($_FILES['pieces_jointes_mailing']['name'][$key])){
	                $this->error = 2;
	            }
	        }
	    }elseif(!empty($count_files)) {
	        $this->files=unserialize(urldecode($files_post));
	        if (is_array($this->files)) {
    	        foreach ( $this->files as $key => $val ) {
    	            if($tmp=@file_get_contents($val["location"])){
    	                $this->attachments[]=array("nomfichier"=>$val["name"],"contenu"=>$tmp);
    	            }
    	        }
	        }
	    }
	}

	public function send($paquet_envoi=0) {
	    global $dbh, $charset;
		global $pmb_mail_delay;

		if ($this->id_list) {
			// ajouter les tags <html> si besoin :
			if (strpos(substr($this->content_tpl, 0, 50), "<html") === false) {
		        $this->content_tpl = "<!DOCTYPE html><html lang='".get_iso_lang_code()."'><head><meta charset=\"".$charset."\" /></head><body>".$this->content_tpl."</body></html>";
		    }

			$emprs = $this->get_empr_list($paquet_envoi);
			$n_envoi = count($emprs);
			$ienvoi=0;
			$this->envoi_KO=0;

			if ($n_envoi) {
    			if($this->associated_campaign) {
    				if($this->associated_num_campaign) {
    					$campaign = new campaign($this->associated_num_campaign);
    				} else {
    					$campaign = new campaign();
    					$campaign->set_type('mailing');
    					$campaign->set_label($this->object_tpl);
    					$saved = $campaign->save();
    					//On conserve l'identifiant de la nouvelle campagne pour les autres paquets
    					if($saved) {
    						$this->associated_num_campaign = $campaign->get_id();
    					}
    				}
    			}
    			while ($ienvoi<$n_envoi) {
    				$destinataire = $emprs[$ienvoi];
    				$mail_mailing = new mail_mailing();
    				$mail_mailing->set_mail_to_id($destinataire->id_empr)
    						->set_destinataire($destinataire)
    						->set_object_tpl($this->object_tpl)
    						->set_content_tpl($this->content_tpl)
    						->set_mail_attachments($this->attachments)
    						->set_associated_campaign($this->associated_campaign)
    						->set_associated_num_campaign($this->associated_num_campaign);
    				$mail_mailing->set_mailing($this);
    				$envoi_OK = $mail_mailing->send_mail();

    				if ($pmb_mail_delay*1) {
    				    sleep((int)$pmb_mail_delay*1/1000);
    				    if(!pmb_mysql_ping($dbh)) {
    				        $dbh = connection_mysql();
    				    }
    				}

    				if ($envoi_OK) {
    					$this->sended_bcc=true;
    				}
    				$this->update_flag($envoi_OK, $destinataire->id_empr);

    				$ienvoi++;
    			}
			}
			$this->total_envoyes=(($this->total_envoyes+$ienvoi)*1)-$this->envoi_KO;
		}
	}

	protected function _get_query_base($paquet_envoi = 0) {
	    global $msg;

	    return "SELECT *,
            DATE_FORMAT(NOW(), '".$msg["format_date"]."') AS aff_empr_day_date,
            DATE_FORMAT(empr_date_adhesion, '".$msg["format_date"]."') AS aff_empr_date_adhesion,
            DATE_FORMAT(empr_date_expiration, '".$msg["format_date"]."') AS aff_empr_date_expiration,
            DATEDIFF(empr_date_expiration, CURDATE()) AS nb_days_before_expiration,
			DATE_FORMAT(last_loan_date, '".$msg["format_date"]."') AS aff_last_loan_date
        FROM empr";
	}

	protected function get_empr_from_search_perso() {
	    $search_perso = new search_perso($this->id_list, 'EMPR');
	    $my_search = $search_perso->get_instance_search();
	    $my_search->unserialize_search($search_perso->query);
	    $table_tempo = $my_search->make_search();

	    if (!$this->total) {
            $sql = "select count(*) from $table_tempo";
            $sql_result = pmb_mysql_query($sql);
            $this->total = pmb_mysql_result($sql_result, 0, 0);
	    }
	    $query = $this->_get_query_base()." WHERE id_empr IN(
            SELECT id_empr FROM $table_tempo
        )";
	    $emprs = [];
	    $result = pmb_mysql_query($query);
	    if (pmb_mysql_num_rows($result)) {
	        while ($row = pmb_mysql_fetch_object($result)) {
	            $emprs[] = $row;
	        }
	    }
	    return $emprs;
	}

	protected function get_empr_from_caddie($paquet_envoi = 0) {
	    if (!$this->total) {
            $sql = "select count(*) from empr_caddie_content where (flag='' or flag is null or flag=2) and empr_caddie_id=".$this->id_list;
            $sql_result = pmb_mysql_query($sql);
            $this->total = pmb_mysql_result($sql_result, 0, 0);
	    }

	    $query = $this->_get_query_base()." JOIN empr_caddie_content ON object_id=id_empr
            WHERE (flag='' or flag is null) AND empr_caddie_id=".$this->id_list;
	    if ($paquet_envoi) {
	        $query .= " limit 0,$paquet_envoi ";
	    }
	    $emprs = [];
	    $result = pmb_mysql_query($query);
	    if (pmb_mysql_num_rows($result)) {
	        while ($row = pmb_mysql_fetch_object($result)) {
	            $emprs[] = $row;
	        }
	    }
	    return $emprs;
	}

	protected function get_empr_from_id() {
	    $query = $this->_get_query_base()." WHERE id_empr = ".$this->id_list;
	    $emprs = [];
	    $result = pmb_mysql_query($query);
	    if (pmb_mysql_num_rows($result)) {
	        $emprs[] = pmb_mysql_fetch_object($result);
	        $this->total = 1;
	    }
	    return $emprs;
	}

	protected function get_empr_list($paquet_envoi = 0) {
	    switch ($this->type) {
	        case self::TYPE_CADDIE :
	            return $this->get_empr_from_caddie($paquet_envoi);
	        case self::TYPE_SEARCH_PERSO :
	            return $this->get_empr_from_search_perso();
	        case self::TYPE_EMPR :
	            return $this->get_empr_from_id();
	    }
	}

	public function get_formatted_data() {
	    global $charset;

	    $data=array();
	    $data['total'] = $this->total;
	    $data['sub']="envoi";
	    $data['total_envoyes'] = $this->total_envoyes;
	    $data['f_objet_mail'] = htmlentities($this->object_tpl, ENT_QUOTES,$charset);
	    $data['f_message'] = htmlentities($this->content_tpl, ENT_QUOTES,$charset);
	    $data['idemprcaddie'] = $this->id_list;
	    $data['files_post'] = urlencode(serialize($this->files));
	    $data['count_files'] = count($this->files);
	    $data['associated_campaign'] = $this->associated_campaign;
	    $data['associated_num_campaign'] = $this->associated_num_campaign;
	    return $data;
	}

	// Fonction qui construit un formulaire qui relance
	public function build_reload_form($time_out, $action, $name, $n_envoi_restant=0) {
	    global $current_module, $msg;

	    $form = "
        <form class='form-$current_module' name=\"$name\" method=\"post\" action=\"$action\">
            <h3>".$this->object_tpl."</h3>
            <div class='form-contenu'>";

	    $hidden_param = $this->get_formatted_data();
	    foreach ($hidden_param as $cle => $params) {
	        $form .= "<input name=\"$cle\" type='hidden' value=\"$params\">";
	    }
	    $recap_comptes_encours = $msg['empr_mailing_recap_comptes_encours'];
	    $recap_comptes_encours = str_replace("!!total_envoyes!!", $this->total_envoyes, $recap_comptes_encours) ;
	    $recap_comptes_encours = str_replace("!!total!!", $this->total, $recap_comptes_encours) ;
	    $recap_comptes_encours = str_replace("!!n_envoi_restant!!", $n_envoi_restant, $recap_comptes_encours) ;
	    $form .= "
                <div class='row'>".
                    $recap_comptes_encours."
                </div>";
	    $form .= "
	       </div>";
	    if ($time_out<0) {
	        $form .= "
            <div class='row'>
                <input type=submit class=bouton value='".$msg['form_recharge_bt_continuer']."' />
            </div>";
	    }
	    $form .= "</form>";
	    switch ($time_out) {
	        case 0:
	            $form .= "<script>document.".$name.".submit();</script>";
	            break;
	        case -1:
	            break;
	        default:
	            $form .= "<script>setTimeout(\"document.".$name.".submit()\",".$time_out.");</script>";
	            break;
	    }
	    return $form;
	}

	protected function is_sended_bcc() {
		return $this->sended_bcc;
	}

	protected function update_flag($envoi_OK, $iddest) {
	    if (self::TYPE_CADDIE == $this->type) {
    	    if ($envoi_OK) {
    	        pmb_mysql_query("update empr_caddie_content set flag='1' where object_id='".$iddest."' and empr_caddie_id=".$this->id_list) or die ("Couldn't update empr_caddie_content !");
    	    } else {
    	        pmb_mysql_query("update empr_caddie_content set flag='2' where object_id='".$iddest."' and empr_caddie_id=".$this->id_list) or die ("Couldn't update empr_caddie_content !");
    	        $this->envoi_KO++;
    	    }
	    }
	}

	public function reset_flag_not_sended() {
	    pmb_mysql_query("update empr_caddie_content set flag='' where flag='2' and empr_caddie_id=".$this->id_list) or die ("Couldn't update empr_caddie_content !");
	}
} //mailing_empr class end
