<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
    exit("unauthorized");
}

include "../database.php";
require_once "../../plugins/sendgrid/config.php";
require "../../plugins/sendgrid/sendgrid-php.php";

$id = $_POST["id"];

$sql_attendance = "SELECT * FROM attendance WHERE id = $id";
$result_attendance = mysqli_query($con, $sql_attendance);
$attendance = mysqli_fetch_assoc($result_attendance);
$year = $attendance["year"];
$month = sprintf('%02d', $attendance["month"]);

$sql = "SELECT * FROM company_data WHERE name = 'Codice azienda'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$company_code = $row["value"];

$filename = "ORARIO_" . $company_code . "_" . $month . "" . $year . ".txt";

$error = 0;
$email_num = 0;

$sql        = "SELECT * FROM payments_office WHERE send_attendance=1";
$result     = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom("info@n-hub.com", "NH-HR");
    $email->addTo("" . $row["email"] . "", "" . $row["name"] . "");
    $email->SetTemplateId("d-72682764e47a4272bdf631d500ce0eb6");
    $email->addDynamicTemplateData("NHHR_periodo_paghe", "" . $month . "/" . $year . "");

    $file_encoded = base64_encode(file_get_contents("../../../cartellini/" . $filename . ""));
    $email->addAttachment(
        $file_encoded,
        "txt",
        $filename,
        "attachment"
    );

    $sendgrid = new \SendGrid(SENDGRID_API_KEY);
    try {
        $response = $sendgrid->send($email);
        $email_num++;
    } catch (Exception $e) {
        echo 'Caught exception: ' . $e->getMessage() . "\n";
        $error++;
    }
}

if ($error == 0) {
    $sql = "UPDATE attendance SET status = 'Inviato', sent = 1, send_datetime = '" . date("Y-m-d H:i:s") . "'";
    $con->query($sql);

    echo $email_num;
} else {
    echo "error";
}
