<?php

require __DIR__ . '/vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

date_default_timezone_set("Asia/Jerusalem");

$month = date("m",strtotime("-1 day"));
$year = date("Y",strtotime("-1 day"));
$day = date("d",strtotime("-1 day"));
$content_time = date("His");

$start = $year . "-" . $month . "-" . $day . " " . "00:00:00";
$end = $year . "-" . $month . "-" . $day . " " . "23:59:59";

$host_ip = $_SERVER['HOST_IP'];
$db_user = $_SERVER['DB_USER'];
$db_pass = $_SERVER['DB_PASS'];
$db_name = $_SERVER['DB_NAME'];

$con = mysqli_connect($host_ip, $db_user, $db_pass, $db_name);

if (mysqli_connect_errno()) {
  echo "Failed to connect to SQL: " . mysqli_connect_error();
}

$api_key = $_SERVER['SENDGRID_API_KEY'];
$server_name = $_SERVER['SERVER_NAME'];
$subject = $server_name . " AntiBot Report";

use SendGrid\Mail\Mail;

$email = new Mail();
$email->setFrom("t-office@tenecall.com", "Tenecall AntiBot Report");
$email->setSubject($subject);
//$email->addTo("nasirhafeez2002@gmail.com", "Nasir Hafeez");
$email->addTo("hello@tenecall.com", "Tenecall Admin");

$tables = ['ANTIBOT1', 'ANTIBOT2'];
$file_names = array();
$row_counts = array();

foreach ($tables as $table_name) {
  $file_name = $year . "_" . $month . "_" . $day . "_" . $content_time. "_" . $table_name . ".csv";

  $result = mysqli_query($con, "SELECT 'id', 'phone', 'mac', 'apmac', 'site', 'last_updated' UNION ALL SELECT * FROM `$table_name` WHERE last_updated >= '$start' AND last_updated <= '$end'");
  $fp = fopen($file_name, 'w');
  while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
  {
    fputcsv($fp, $row);
  }
  fclose($fp);

  $file_encoded = base64_encode(file_get_contents($file_name));
  $email->addAttachment(
    $file_encoded,
    "text/csv",
    $file_name,
    "attachment"
  );

  if(!$result){
    $row_cnt = 0;
  } else {
    $row_cnt = $result->num_rows - 1;
  }

  array_push($file_names, $file_name);
  array_push($row_counts, $row_cnt);
}

mysqli_close($con);

unlink($file_names[0]);
unlink($file_names[1]);

// Email body content
$htmlContent = '
  <h3>Summary</h3>
  <p>Total Records AntiBot 1: ' . $row_counts[0] . '</p>
  <p>Total Records AntiBot 2: ' . $row_counts[1] . '</p>';

$email->addContent(
  "text/html", $htmlContent
);

$sendgrid = new \SendGrid($api_key);
try {
  $response = $sendgrid->send($email);
//  print $response->statusCode() . "\n";
//  print_r($response->headers());
//  print $response->body() . "\n";
} catch (Exception $e) {
//  echo 'Caught exception: ' . $e->getMessage() . "\n";
}
