<?php
require 'mailer/src/Exception.php';         //knihovna mail
require 'mailer/src/PHPMailer.php';
require 'mailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;


require_once("db_connect.php");




date_default_timezone_set("Europe/Paris");
$key="tPmAT5Ab3j7F9";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
  	if($key==test_input($_POST["key"])){
        
        $location = test_input($_POST["location"]);
        $type=test_input($_POST["type"]);
        $url=test_input($_POST["url"]);
        $url=str_replace("/public_html/","",$url); //odsrtanění /public_html
        $time=date("d.m.Y - G:i");
        


      
        
       $sql = "INSERT INTO sensor (location, type, url, time) VALUES ('" . $location . "', '" . $type . "', '" . $url . "', '" . $time . "' )"; //upload
        
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";


           

            $mail = new PHPMailer;                                          //mail start
            $mail->isSMTP();    
            $mail->Host = "smtp.gmail.com";
            $mail->SMTPAuth = true;
            $mail->Username = $mailuser;
            $mail->Password = $mailpassword;
            $mail->SMTPSecure = "tls";
            $mail->Port = 587;
            $mail->CharSet = "utf-8"; 
            $mail->isHTML();
            $mail->setFrom("espcam363@gmail.com", "Be secured"); 


            $sql2 = "SELECT us_mail FROM users WHERE send_mail=1";      //adresáti
            $result = $conn->query($sql2);

            if ($result->num_rows > 0) {
                    while($adress = $result->fetch_assoc()) {
                        $mail->addAddress($adress["us_mail"]);
                    }
            } else {
                echo "0 results";
            }

            $mail->addAttachment($url);   //příloha
            $mail->Subject = "Upozornění";      
            $mail->Body = "Zachycen pohyb v místě : " . $location;

            if($mail->send()){
                if($p>1){
                  echo"Emaily byly odeslány($p)";
                }else{
                echo "Email byl odeslán";
                }
            }else{
                echo $mail->ErrorInfo;
            }                                                           //mail end



        } 
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    
        $conn->close();
   }else{
   	echo "Wrong key";
   }

}
else {
    echo "No data POSTed with HTTP POST.";
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>