<?php
if (!defined('ABSPATH')) exit;

class SIMPINBY_Mail_Actions {

  public function __construct() {
    add_action("admin_init", [$this, "handle_send_email"]);
  }

  
  public function handle_send_email() {

      if (!current_user_can("manage_options")) return;

      if (isset($_GET["send_email"]) && isset($_GET["id"])) {

          $invoice_id = intval($_GET["id"]);

          check_admin_referer("simpinby_send_email_" . $invoice_id);

          global $wpdb;

          $customers = $wpdb->prefix . "simpinby_customers";
          $invoice_table = $wpdb->prefix . "simpinby_invoices";

          $customer_email = $wpdb->get_var($wpdb->prepare("
              SELECT c.email
              FROM $invoice_table inv
              LEFT JOIN $customers c ON c.id = inv.customer_id
              WHERE inv.id=%d
          ", $invoice_id));

          $res = SIMPINBY_Mail::send_invoice_email($invoice_id, $customer_email);

          $msg = $res["success"] ? "sent" : "failed";

          $redirect_url = admin_url(
              "admin.php?page=simpinby-invoices&action=view&id={$invoice_id}&mail={$msg}"
          );

          $redirect_url = add_query_arg(
              '_wpnonce',
              wp_create_nonce('simpinby_view_invoice_' . $invoice_id),
              $redirect_url
          );

          wp_safe_redirect($redirect_url);
          exit;
      }
  }
}
