<?php
include("include/functions.php");
require_once("include/connect.inc");

require __DIR__ . '/phpmailer/PHPMailer.php';
require __DIR__ . '/phpmailer/SMTP.php';
require __DIR__ . '/phpmailer/Exception.php';
require __DIR__ . '/phpmailer/OAuth.php';

mysqli_query($link, "SET character_set_results=utf8");



$mitt = '';
$dest = '';
//$s_prefix='nos';
$s_prefix = 'wa';
//	$message='refresh '.date('H:i:s').'*   ';
$message = '';
$urlbase = '..Public'; //upload

$d = date('Y-m-d');
$parts = explode('-', $d);
$dw = date("w", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));
//Recupera email mittente/destinatario dal DB
$query = "SELECT * FROM " . $s_prefix . "_config WHERE id=1 AND enabled=1";
$values = mysqli_query($link, $query) or die('Query failed: ' . mysqli_error($link));
while ($result = mysqli_fetch_array($values, MYSQLI_ASSOC)) {
	$mitt = "fayza.lahzouz@gmail.com"; //$result['email_1'];
	$dest = "fayza.lahzouz@bitonlive.com"; //$result['email_2'];
}
unset($result);
mysqli_free_result($values);

echo '<b>RADIO NOSTALGIA - UPLOAD MANAGER</b><br>Controllo notiziari caricati.<br><br><u>N O N&nbsp;&nbsp;C H I U D E R E&nbsp;&nbsp;L A&nbsp;&nbsp;P A G I N A</u><br><br>';
echo date('Y-m-d H:i:s') . '<br>';

//Recupera tutte le edizioni dal DB
$sql = "SELECT a.*, b.description FROM " . $s_prefix . "_editions a LEFT JOIN " . $s_prefix . "_editionstype b ON a.idtype=b.id ORDER BY a.maxtimeup, b.description";

echo $sql . "<br/>";

$val = mysqli_query($link, $sql) or die('Query failed: ' . mysqli_error($link));
while ($row = mysqli_fetch_array($val, MYSQLI_ASSOC)) {
	//Ciclo sulle edizioni valide per oggi
	if (substr($row['days'], $dw, 1) == 1) { // il giorno � valido
		$now = strtotime("now");
		$maxtime = strtotime($d . ' ' . formatHHMM($row['maxtimeup'] / 1000));
		//echo strtotime("2015-09-23 17:45").'****'.strtotime("2015-09-23 17:46").'<br>';
		echo $now - $maxtime . "<br/>";
		if (($now - $maxtime) > 0 && ($now - $maxtime) < 65) {
			echo 'tra 0 e 65 <br/>';
			$path = $urlbase . '/' . $row['path'];
			if (substr($path, (strlen($path) - 1)) != '/') $path = $path . '/';
			$filename = $path. $row['name'] . '_' . $parts[0] . '-' . $parts[1] . '-' . $parts[2] . '_' . str_replace(":", ".", formatHHMM($row['timeedition'] / 1000)) . '.mp3';
			if (!file_exists($filename)) {
				echo 'esiste <br/>';
				$message .= date('Y-m-d H:i:s') . '  ' . $row['description'] . '  ' . formatHHMM($row['timeedition'] / 1000) . ' (' . formatHHMM($row['maxtimeup'] / 1000) . ') ' . $filename . "\r\n";
				echo $message . '<br>';
			}
		}
	}
}

/*
Controlla solo le edizioni valide per il giorno della settimana corrente.
Confronta l’ora attuale con maxtimeup dell’edizione.
Se il file non esiste entro 65 secondi dopo il tempo massimo, aggiunge un messaggio nella variabile $message.
Mostra sul browser l’elenco dei file mancanti.
*/

unset($row);
mysqli_free_result($val);


/*
Se $message contiene almeno un file mancante, invia un’email al destinatario con l’elenco dei file non caricati.*/
if ($message != '') {
	echo 'Invio ...';
	$subject = 'NOSTALGIA - MANCA FILE';
	$headers = 'From: ' . $mitt . "\r\n" .
		'Reply-To: ' . $mitt . "\r\n" .
		'X-Mailer: PHP/' . phpversion();

	//mail($dest, $subject, $message, $headers);

	try {
		$mail = new PHPMailer\PHPMailer\PHPMailer(true);
		$fromEmail    = 'fayza.lahzouz@bitonlive.com';
		$fromName     = 'Bitonlive';

		$mail->isSMTP();
		$mail->SMTPAuth = true;
		$mail->Host = 'sandbox.smtp.mailtrap.io';
		$mail->Port = 2525;
		$mail->Username = 'd1b462cb734726';
		$mail->Password = 'fbd16aa54303d2';
		$mail->SMTPSecure = ''; // niente TLS/SS
		$mail->SMTPAutoTLS = false; // disabilita auto STARTTLS
		$mail->SMTPOptions = [
			'ssl' => [
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true,
			],
		];
		$mail->SMTPDebug = 2; // Mostra log dettagliato della connessione SMTP
		$mail->Debugoutput = 'html';


		// Disabilita verifica SSL (equivalente a 'stream' di Laravel)

		//$mail->setFrom($mitt, 'Nostalgia');
		// Mittente
		$mail->setFrom($fromEmail, $fromName);
		$mail->addAddress($mitt);

		$mail->Subject = $subject;
		$mail->Body    = $message;

		$mail->send();
		echo 'Email inviata (Mailtrap).';
	} catch (Exception $e) {
		echo "Errore invio email: {$mail->ErrorInfo}";
	}
}
