<?php
/**
 * ADDON - POP to Fatture in Cloud - Receipts
 */

if (! defined('WP_FATT_CLOUD_RECEIPTS')) {
    define('WP_FATT_CLOUD_RECEIPTS', 'prod');
}

// Define constant.
define('WP_FATT_CLOUD_RECEIPTS_NAME', 'POP to Fatture in Cloud - Receipts');
define('WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN', 'wfc_rc');
define('WP_FATT_CLOUD_RECEIPTS_VERSION', '1.2.1');
define('WP_FATT_CLOUD_RECEIPTS_API', get_option('wfc_api_url'));
// Plugin DIR
define('WP_FATT_CLOUD_RECEIPTS_PLUGIN_DIR', basename(plugin_dir_path(__FILE__)));
// Dirs
define('WP_FATT_CLOUD_RECEIPTS_DIR', plugin_dir_path(__FILE__));
// Uri
define('WP_FATT_CLOUD_RECEIPTS_URL', plugin_dir_url(__FILE__));

/**
 * Load Localisation files.
 *
 * Note: the first-loaded translation file overrides any following ones if the same translation is present.
 *
 * Locales found in:
 *      - WP_LANG_DIR/PLUGIN_LANGUAGE_DIR_PATH/TEXT_DOMAIN-LOCALE.mo
 *      - WP_LANG_DIR/plugins/TEXT_DOMAIN-LOCALE.mo
 */
function wfc_rc_load_plugin_textdomain()
{
    $locale = determine_locale();

    /**
     * Filter to adjust the WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN locale to use for translations.
     */
    $locale = apply_filters('plugin_locale', $locale, WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN);

    unload_textdomain(WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN, true);
    load_textdomain(WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN,
        WP_LANG_DIR . '/woopop-electronic-invoice/addon/to/' . WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN . '-' . $locale . '.mo');
    // Load plugin text-domain.
    load_plugin_textdomain(WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN, false,
        '/' . WC_EL_INV_PLUGIN_DIR . '/addon/to/' . WP_FATT_CLOUD_RECEIPTS_PLUGIN_DIR . '/languages/');
}

// Init
$bootstrap = function () {

    // Load Localisation files.
    wfc_rc_load_plugin_textdomain();

    // Plugin check
    if (class_exists('\WooPoPToFattureInCloud\Api') &&
        method_exists('\WooPoPToFattureInCloud\Api', 'fattureInCloudReceiptsApi') &&
        \WooPoPToFattureInCloud\Functions\isWooCommerceActive() &&
        class_exists('WcElectronInvoice\\Plugin')
    ) {
        /**
         *  OAuthFlow - Append scope receipts
         */
        add_filter('wfc-oauth_flow_after_defined_access_permission', function ($scopes) {
            $permissionRec = WooPoPToFattureInCloud\Functions\filterInput($_POST, 'permissionRec', FILTER_VALIDATE_INT);
            if (1 === $permissionRec) {
                $scopes = "receipts:a " . $scopes;
            }

            return $scopes;
        });

        /**
         * Create Receipt
         */
        add_action('wfc-create_invoice', function ($issuedDocumentInv, $body) {
            if ($issuedDocumentInv instanceof \FattureInCloud\Model\CreateIssuedDocumentResponse) {

                // Created issuedDocument Receipt ?
                if ('receipt' === $body['data']['type'] && $issuedDocumentInv->valid()) {
                    // Get user company data
                    $userAndCompanies = \WooPoPToFattureInCloud\Functions\getUserAndCompanies();

                    $amountNet   = 0;
                    $amountGross = 0;
                    if (! empty($body['data']['items_list'])) {
                        foreach ($body['data']['items_list'] as $index => $item) {
                            $body['data']['items_list'][$index]['in_ddt'] = true;

                            // Convert key
                            $body['data']['items_list'][$index]['amount_net']   = $body['data']['items_list'][$index]['net_price'];
                            $body['data']['items_list'][$index]['amount_gross'] = $body['data']['items_list'][$index]['gross_price'];

                            // Unset unnecessary key
                            unset($body['data']['items_list'][$index]['net_price']);
                            unset($body['data']['items_list'][$index]['gross_price']);

                            // Set amount
                            $amountNet   += $body['data']['items_list'][$index]['net_price'];
                            $amountGross += $body['data']['items_list'][$index]['gross_price'];
                        }
                    }

                    $receiptBody = array(
                        'data'                => array(
                            'date'             => $body['data']['date'],
                            'numeration'       => apply_filters('wfc_rc-numeration', $body['data']['numeration']),
                            'amount_net'       => $amountNet,
                            'amount_gross'     => $amountGross,
                            'use_gross_prices' => false,
                            // till_receipt / sales_receipt
                            'type'             => apply_filters('wfc_rc-data_type', 'till_receipt'),
                            'description'      => $body['data']['subject'],
                            'payment_account'  => array(
                                'type' => $body['data']['payments_list'][0]['payment_account']['type'],
                                'name' => $body['data']['payments_list'][0]['payment_account']['name'],
                                'id'   => $body['data']['payments_list'][0]['payment_account']['id'],
                            ),
                            'items_list'       => $body['data']['items_list'],
                        ),
                        'autocomplete_number' => true,
                    );

                    /**
                     * Filter body
                     */
                    $receiptBody = apply_filters('wfc_rc-receipt_body', $receiptBody);

                    // Create Receipts instance
                    $fattureInCloudReceiptsApi = \WooPoPToFattureInCloud\Api::fattureInCloudReceiptsApi();
                    $createReceipt             = $fattureInCloudReceiptsApi->createReceipt(
                        $userAndCompanies->companyID,
                        new \FattureInCloud\Model\CreateReceiptRequest($receiptBody),
                        $fattureInCloudReceiptsApi::contentTypes['createReceipt'][0]
                    );

                    $msgFn = null;
                    $msgFn = function ($message) use ($createReceipt, &$msgFn) {
                        remove_filter('wfc-create_invoice_message', $msgFn, 20);
                        if ($createReceipt->valid()) {
                            // Store meta id
                            $orderID = WooPoPToFattureInCloud\Functions\filterInput($_POST, 'orderID',
                                FILTER_UNSAFE_RAW);
                            $order   = wc_get_order($orderID);
                            if (is_object($order)) {
                                $order->update_meta_data('wfc-receipt_id', $createReceipt->getData()->getId());
                                // Save
                                $order->save();
                                // Message
                                $message = $message . "<br>" .
                                           __('Receipt Document created successfully!',
                                               WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN
                                           );
                            }
                        } else {
                            $message = json_encode($createReceipt->getData()->listInvalidProperties());
                        }

                        return $message;
                    };
                    add_filter('wfc-create_invoice_message', $msgFn, 20);

                    $codeFn = null;
                    $codeFn = function ($code) use ($createReceipt, &$codeFn) {
                        remove_filter('wfc-create_invoice_code', $codeFn, 20);
                        if ($createReceipt->valid()) {
                            $code = 200;
                        } else {
                            $code = 422;
                        }

                        return $code;
                    };
                    add_filter('wfc-create_invoice_code', $codeFn, 20);

                    $extraFn = null;
                    $extraFn = function ($extraResult) use ($createReceipt, &$extraFn) {
                        remove_filter('wfc-create_invoice_extra_result', $extraFn, 20);

                        return json_encode($createReceipt);
                    };
                    add_filter('wfc-create_invoice_extra_result', $extraFn, 20);
                }
            }
        }, 20, 2);

        /**
         * Delete Receipt
         */
        add_action('wfc-delete_receipt', function () {
            // Get user company data
            $userAndCompanies = \WooPoPToFattureInCloud\Functions\getUserAndCompanies();
            $orderID          = WooPoPToFattureInCloud\Functions\filterInput($_POST, 'id', FILTER_UNSAFE_RAW);
            $order            = wc_get_order($orderID);
            if (! $order || is_wp_error($order)) {
                return;
            }

            try {
                $fattureInCloudReceiptsApi = \WooPoPToFattureInCloud\Api::fattureInCloudReceiptsApi();
                $docID                     = $order->get_meta('wfc-receipt_id');
                $fattureInCloudReceiptsApi->deleteReceipt(
                    (int)$userAndCompanies->companyID,
                    (int)$docID,
                    $fattureInCloudReceiptsApi::contentTypes['deleteReceipt'][0]
                );

                $order->delete_meta_data('wfc-receipt_id');
                // Save
                $order->save();

                add_filter('wfc-delete_receipt_message', function ($message) use ($docID) {
                    // Message
                    return $message . "<br>" .
                           sprintf(esc_html__(
                               'Receipt Document ID %s successfully deleted',
                               WP_FATT_CLOUD_RECEIPTS_TEXTDOMAIN
                           ), $docID);
                }, 10);
            } catch (Exception $e) {
                // Not found
                if (404 === $e->getCode()) {
                    // Delete document meta id
                    $order->delete_meta_data('wfc-receipt_id');
                    // Save
                    $order->save();
                }
            }
        }, 20);
    }
};

if (did_action('init')) {
    $bootstrap();
} else {
    add_action('init', $bootstrap, 30);
}
