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

class SIMPINBY_Actions {

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

  public function handle_actions() {
    if (!current_user_can("manage_options")) return;

    global $wpdb;
    $invoice_table = $wpdb->prefix . "simpinby_invoices";

    // Toggle Status
    if (isset($_GET["toggle_status"])) {
      $id = intval($_GET["toggle_status"]);
      check_admin_referer("simpinby_toggle_status_" . $id);

      $current = $wpdb->get_var($wpdb->prepare("SELECT status FROM $invoice_table WHERE id=%d", $id));
      if ($current) {
        $new = ($current === "paid") ? "unpaid" : "paid";
        $wpdb->update($invoice_table, ["status" => $new], ["id" => $id]);
      }

      wp_safe_redirect(esc_url_raw(admin_url("admin.php?page=simpinby-invoices")));
      exit;
    }

    // Archive Invoice
    if (isset($_GET["archive"])) {
      $id = intval($_GET["archive"]);
      check_admin_referer("simpinby_archive_" . $id);

      $wpdb->update($invoice_table, ["is_archived" => 1], ["id" => $id]);

      wp_safe_redirect(esc_url_raw(admin_url("admin.php?page=simpinby-invoices")));
      exit;
    }
    // Unarchive Invoice
    if (isset($_GET["unarchive"])) {
        $id = intval($_GET["unarchive"]);
        check_admin_referer("simpinby_unarchive_" . $id);

        $wpdb->update($invoice_table, ["is_archived" => 0], ["id" => $id]);

        wp_safe_redirect(esc_url_raw(admin_url("admin.php?page=simpinby-invoices&show=archived")));
        exit;
    }

  }
}
