<?php
/*
Plugin Name: ESIR - WIN Fiskal (fiskalna kasa)
Description: IT Creator has created a plug-in that facilitates the process of issuing invoices. The software fiscal register (plugin) enables the automatic creation and fiscalization of accounts in the Tax Administration of the Republic of Serbia. ESIR WIN Fiskal works and has been tested with the WooCommerce plugin. Align business with legal regulations. Reliable business software for electronic fiscalization. Take advantage of the benefits offered by our software solution. IT Creator is your partner in the process of electronic fiscalization.
Electronic fiscalization brings a series of big changes for which we need to prepare in time. To our business users, we guarantee security and business continuity, professional support and a superior user experience.
License: GPL v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Version: 1.0
*/

if (!defined('ABSPATH'))
  exit; // Exit if accessed directly
require_once __DIR__ . '/mpdf/vendor/autoload.php';
require_once dirname(__DIR__) . '/esir-win-fiskal-fiskalna-kasa/ewfk_functions/ewfk_functions.php';
require_once dirname(__DIR__) . '/esir-win-fiskal-fiskalna-kasa/ewfk_config.php';


// Act on plugin activation
register_activation_hook(__FILE__, "ewfk_activate_myplugin");

// Act on plugin de-activation
register_deactivation_hook(__FILE__, "ewfk_deactivate_myplugin");

register_uninstall_hook(__FILE__, 'ewfk_delete_plugin_database_table');
// Activate Plugin
function ewfk_activate_myplugin()
{

  ewfk_db_myplugin();
}

// De-activate Plugin
function ewfk_deactivate_myplugin()
{

  $ewfk_upload_dir=wp_upload_dir();
  $dir = $ewfk_upload_dir['basedir'];
  ewfk_deleteDir($dir . "/ewfk_settings");
  // Execute tasks on Plugin de-activation
}

function ewfk_delete_plugin_database_table()
{

  global $wpdb;
  $table_name = $wpdb->prefix . 'esir_config';
  $sql = "DROP TABLE IF EXISTS $table_name";
  $wpdb->query($sql);
}

add_action('admin_menu', 'ewfk_my_admin_menu');

add_action('admin_post_submit-settings', 'ewfk_settings_form_action');


add_action('woocommerce_order_status_changed', 'ewfk_bacs_cheque_cod_payment_complete', 10, 4);

function ewfk_bacs_cheque_cod_payment_complete($order_id, $old_status, $new_status, $order)
{

  global $woocommerce, $wp;


  if (isset($wp->query_vars['order-received'])) {
    $order_id = absint($wp->query_vars['order-received']);
  }

  $order = new WC_Order($order_id);
  $ewfk_upload_dir=wp_upload_dir();
  $dir =  $ewfk_upload_dir['basedir'];


  if (!in_array($order->get_payment_method(), array('bacs', 'cheque', 'cod'))) {

    if ($order->get_status() == "processing") {
      $items_from_order = $order->get_items();

      $response = ewfk_api_login();

      $total = $order->get_total();
      $items = array();
      $item = array();
      foreach ($items_from_order as $item_id => $itm) {
        $product = $itm->get_product();
        $item["name"] = ($woocommerce->version < '2.7.0') ? $itm->name : $itm->get_name();
        $item["quantity"] = $itm->get_quantity();
        $item["labels"] = array("A");
        $item["unitPrice"] = ($woocommerce->version < '2.7.0') ? $product->price : $product->get_price();
        $item["totalAmount"] = $itm->get_total();
        $items[] = $item;
        $item = array();
      }

      $data = array(
        'invoiceType' => "Normal",
        'transactionType' => "Sale",
        "payment" => array(array("amount" => $total, "paymentType" => "Card")),
        "items" => $items,
        "cashier" => EWFK_CASHIER,
        'returnSecureToken' => true
      );

      ewfk_api_invoice(json_decode($response)->idToken, $data, $order->get_billing_email());

    }
  }

}

add_action('template_redirect', 'ewfk_woo_custom_redirect_after_purchase');
function ewfk_woo_custom_redirect_after_purchase()
{

  global $wp;

  if (is_checkout() && !empty($wp->query_vars['order-received'])) {

    if ($_SESSION['msg'] !== "Success") {
      wp_redirect(EWFK_PAGE_FAILED);
      $headers = 'From: Fiskalni račun <no-reply@it-creator.rs>' . "\r\n";
      $email = isset($_SESSION['email']) ? sanitize_email($_SESSION['email']) : '';
      if (is_email($email)) {
        wp_mail($email, 'Fiskalni račun - INFO/Greška', 'Poštovani,

Došlo je do greške pri izdavanju fiskalnog računa.
Za dobijanje fiskalnog računa molimo vas da se obratite sa zahtevom za dostavljanje istog.

Hvala na razumevanju', $headers);
        wp_mail(EWFK_NOTIF_EMAIL, 'Fiskalni račun - INFO/Greška', 'Poštovani,

Došlo je do greške pri izdavanju fiskalnog računa. Email korisnika: ' . esc_html($email) . '

Hvala na razumevanju .', $headers);
      }
      exit;
    }
  }
}

function ewfk_tatwerat_startSession()
{
  if (!session_id()) {
    @session_start();
  }
}

add_action('init', 'ewfk_tatwerat_startSession', 1);


function ewfk_my_init_method()
{

  wp_enqueue_script('jquery');
  wp_enqueue_script('carrington-mobile', get_bloginfo('template_directory') . '/js/mobile.js', array('jquery'), '1.0');



}

function ewfk_admin_enqueue()
{
  wp_enqueue_script('custom_js', plugins_url('js/custom-js.js', __FILE__));
  wp_localize_script(
    'custom_js',
    'my_ajax_object',
    array('ajax_url' => admin_url('admin-ajax.php'),'nonce' => wp_create_nonce('test_api'))
  );
}
add_action('admin_enqueue_scripts', 'ewfk_admin_enqueue');


add_action('wp_enqueue_scripts', 'ewfk_my_init_method');

add_action('wp_ajax_test_api_action', 'ewfk_test_api_form_action');

add_action('wp_ajax_get_nonce_action', 'ewfk_get_nonce_action');

