#!/usr/bin/php
<?PHP
/* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
 * Copyright (C) 2005 Laurent Destailleur  <eldy@users.sourceforge.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * $Id$
 * $Source$
 */

/**
        \file       scripts/invoices/factures-impayees-commerciaux.php
        \ingroup    facture
        \brief      Script d'envoi de mails résumé des imapyées par commerciaux
*/

// Test si mode batch
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
    echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n";
    exit;
}

// Recupere root dolibarr
$path=eregi_replace('factures-impayees-commerciaux.php','',$_SERVER["PHP_SELF"]);


require($path."../../htdocs/master.inc.php");
require_once (DOL_DOCUMENT_ROOT."/lib/CMailFile.class.php");


$error = 0;

$sql = "SELECT f.facnumber, f.total_ttc, s.nom, u.name, u.firstname, u.email";
$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
$sql .= " , ".MAIN_DB_PREFIX."societe as s";
$sql .= " , ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql .= " , ".MAIN_DB_PREFIX."user as u";
$sql .= " WHERE f.paye = 0";
$sql .= " AND f.fk_soc = s.rowid";
$sql .= " AND sc.fk_soc = s.rowid";
$sql .= " AND sc.fk_user = u.rowid";
$sql .= " ORDER BY u.email ASC, s.rowid ASC";

if ( $db->query($sql) )
{
    $num = $db->num_rows();
    $i = 0;
    $oldemail = '';
    $message = '';
    $total = '';
    dolibarr_syslog("factures-impayees-commerciaux: ");

    if ($num)
    {
        while ($i < $num)
        {
            $obj = $db->fetch_object();
    
            if ($obj->email <> $oldemail)
            {
                if (strlen($oldemail))
                {
                    envoi_mail($oldemail,$message,$total);    
                }
                $oldemail = $obj->email;
                $message = '';
                $total = 0;
            }
    
            $message .= "Facture ".$obj->facnumber." : ".price($obj->total_ttc)." : ".$obj->nom."\n";
            $total += $obj->total_ttc;
    
            dolibarr_syslog("factures-impayees-commerciaux: ".$obj->email);
            $i++;
        }

        // Si il reste des envois en buffer
        if ($total)
        {
            envoi_mail($oldemail,$message,$total);    
        }
    }
    else
    {
        print "Aucune facture impayée avec des commerciaux directement rattachés\n";
    }
}
else
{
    dolibarr_print_error($db);
    dolibarr_syslog("factures-impayees-commerciaux: Error");
}


function envoi_mail($oldemail,$message,$total)
{
    global $conf;
    
    $subject = "[Dolibarr] Liste des factures impayées";
    $sendto = $oldemail;
    $from = $conf->global->MAIN_EMAIL_FROM;
	$msgishtml = 0;
	
    print "Envoi mail pour $oldemail, total: $total\n";
    dolibarr_syslog("factures-impayees-commerciaux: send mail to $oldemail");

    $allmessage = "Liste des factures impayées à ce jour\n";
    $allmessage .= "Cette liste ne comporte que les factures des sociétés dont vous êtes référencés comme commercial.\n";
    $allmessage .= "\n";
    $allmessage .= $message;
    $allmessage .= "\n";
    $allmessage .= "Total = ".price($total)."\n";

    $mail = new CMailFile($subject,
    $sendto,
    $from,
    $allmessage,
    array(),
    array(),
    array(),
    '',
    '',
    0,
    $msgishtml);

    $mail->errors_to = $errorsto;

    $result=$mail->sendfile();
    if ($result)
    {

    }

}    
    

?>
