<?php
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

include 'mail.php';
include 'database.php';
include 'image.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_POST = json_decode(file_get_contents("php://input"), true);

    $sender = $_POST['id'];
    $email = strtolower($_POST['email']); 
    $prefix = $_POST['prefix'];
    $ipAddress = $_SERVER['REMOTE_ADDR'];

    $emailList = array(); 

    if ($email === "") {
        echo("Unesite adresu e-pošte ili korisničko ime!");
    } else {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailList[] = $email; 
        } else {
            $file = fopen("mailovi.csv", "r");

            if ($file) {
                while (($line = fgets($file)) !== false) {
                    $line = rtrim($line); 
                    if ($line[0] !== "#") {
                        $lineData = explode(";", $line); 
                        if ($lineData[0] === $email) {
                            $emailList = array_slice($lineData, 1); 
                            break; 
                        }
                    }
                        
                }
                fclose($file);
            } else {
                echo "Pogreška u otvaranju datoteke! "; 
            }
        }

        if (empty($emailList)) {
            echo "Krivo korisničko ime ili adresa! ";
        } else {
            try {
                $time = addToDB($prefix, $emailList, $ipAddress);
                $cleanTime = str_replace(array(' ', '-', ':'), '', $time);
            } catch (Exception $e) {
                $message = $e->getMessage();
                if (strpos($message, "Access denied") === 0) {
                    $cleanTime = "DB Connection failed!";
                    $time = "DB Connection failed!";
                } else {
                    $cleanTime = $message;
                    $time = $message;
                }
            }

            createImg($cleanTime, $sender);

            foreach ($emailList as $email) {
                if (sendMail($sender, $cleanTime, $email, $ipAddress)) {
                    $jsonResponse = json_encode($time);
                } else {
                    $jsonResponse = json_encode("Greška u slanju maila!");
                }
            }

            echo($jsonResponse);
            } 
        }
    }
?>
