<?php 
    include_once(__DIR__ . "/../config.php");
    include_once(__DIR__ .'/../functions.php');
    function saveMessageDelivery($link, $message_id){
        $cur_time = date("Y-m-d H:i:s");
        $stmt = $link->prepare("UPDATE messages SET status = 'delivered', time_delivered = '$cur_time' WHERE id = ?");
        $stmt->bind_param("i", $message_id);
        $stmt->execute();
    }

    //GET failed emails
    $result = $link->query("SELECT * FROM messages WHERE status <> 'delivered' AND channel = 'email'");

    while ($row = mysqli_fetch_array($result)) {
        if(sendinblue_mail($row["receiver_email"], $row["receiver"], $row["subject"], $row["message"])){
            saveMessageDelivery($link, $row["id"]);
        }
    }