<?php

/**
 * Plugin Name: Buy With Digikala
 * Plugin URI: https://digify.shop/
 * Description: امکان خرید از سایت توسط دیجی کالا
 * Version: 1.3.1
 * Author: دیجیفای
 * Author URI: https://digify.shop/
 * License: GPL2
 * Text Domain: bwdk
 * Domain Path: /languages
 * Requires Plugins: woocommerce
 *  Requires at least: 5.6
 *  Tested up to: 6.8
 *  Requires PHP: 7.4
 */

// Define plugin version constant
if ( ! defined( 'BWDK_VERSION' ) ) {
    define( 'BWDK_VERSION', '1.3.1' );
}

// Define plugin file constant
if ( ! defined( 'BWDK_PLUGIN_FILE' ) ) {
    define( 'BWDK_PLUGIN_FILE', __FILE__ );
}

// Define metadata URL constant for auto-updates
if ( ! defined( 'BWDK_UPDATE_METADATA_URL' ) ) {
    define( 'BWDK_UPDATE_METADATA_URL', 'https://plugins.digifyprime.net/bwdk/metadata.json' );
}

use BWDK\Support\Activate;
use BWDK\Support\Deactive;


if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if (!function_exists('dd')) {
    function dd($data)
    {
        $trace      = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS , 2);
        $selfFile   = isset($trace[0]['file']) ? $trace[0]['file'] : '';
        $selfLine   = isset($trace[0]['line']) ? $trace[0]['line'] : '';
        $callerFile = isset($trace[1]['file']) ? $trace[1]['file'] : '';
        $callerLine = isset($trace[1]['line']) ? $trace[1]['line'] : '';
        $class      = isset($trace[1]['class']) ? $trace[1]['class'] : '';
        $function   = isset($trace[1]['function']) ? $trace[1]['function'] : '';
        echo "<pre style='display: block; text-align: left; direction: ltr; background-color: #fff; border: 1px solid #9e4e00; border-radius: 5px; padding: 7px; border-left-width: 7px; margin: 10px; font-size: 13px;'>";
        echo "Called from file: {$callerFile}\n";
        echo "Called from line: {$callerLine}\n";
        if ($class) {
            echo "Class: {$class}\n";
        }
        if ($function) {
            echo "Function/Method: {$function}\n";
            echo "Line (dd): {$selfLine}\n";
        }
        echo "-----------------------------\n";
        var_dump($data);
        echo '</pre>';
        exit();
    }
}



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

if ( ! function_exists( 'bwdk_is_digiexpress_enabled' ) ) {
    /**
     * Whether DigiExpress admin UI is enabled (order meta box, actions, DX notices).
     * Default false when option is missing (rollout-safe).
     */
    function bwdk_is_digiexpress_enabled(): bool {
        return get_option( \BWDK\Support\Constant::OPTION_BWDK_ENABLE_DIGIEXPRESS, '0' ) === '1';
    }
}

// Load update checker
require_once __DIR__ . '/src/Support/UpdateChecker.php';
// Order status guard helpers (auto-processing rules)
require_once __DIR__ . '/src/Support/OrderStatusGuards.php';
// New DigiExpress status engine (DX_Status_Engine)
require_once __DIR__ . '/includes/services/digiexpress/class-dx-status-engine.php';
// DigiExpress service (revive/new-shipment decision)
require_once __DIR__ . '/includes/services/class-bwdk-digiexpress-service.php';
// DigiExpress message mapper (bwdk_dx_build_message)
require_once __DIR__ . '/src/Support/DigiExpressMessageMapper.php';
// Jalali / UTC-safe meta datetime formatter (dx_format_jalali_datetime)
require_once __DIR__ . '/includes/helpers/date.php';

(new Activate())->register();
(new Deactive())->register();

// Initialize update checker in admin
add_action( 'init', function () {
    if ( is_admin() ) {
        \BWDK\Support\UpdateChecker::init();
    }
});

add_action('init', function () {
    (new \BWDK\Core\Plugin())->run();
});

/**
 * DigiExpress (BWDK) meta box on order edit screen. Class-based callback; HPOS compatible.
 */
add_action( 'plugins_loaded', function () {
    if ( is_admin() && bwdk_is_digiexpress_enabled() ) {
        new \BWDK\Admin\BWDK_Admin_DX_Meta_Box();
    }
}, 20 );

/**
 * Stub for old DigiExpress meta box callback. Prevents fatal if cached/old code still registers it.
 * The real meta box is rendered by BWDK_Admin_DX_Meta_Box::render_meta_box().
 */
if ( ! function_exists( 'bwdk_render_digi_express_meta_box' ) ) {
    function bwdk_render_digi_express_meta_box( $post ) {
        if ( function_exists( 'bwdk_is_digiexpress_enabled' ) && ! bwdk_is_digiexpress_enabled() ) {
            return;
        }
        echo '<p>' . esc_html__( 'لطفاً صفحه را یک‌بار رفرش کنید.', 'bwdk' ) . '</p>';
    }
}

/**
 * Render BWDK receiver_name and receiver_phone in WooCommerce admin order edit → Shipping section.
 * HPOS compatible: uses $order->get_meta().
 */
if ( ! function_exists( 'bwdk_render_receiver_name_in_admin' ) ) {
    function bwdk_render_receiver_name_in_admin( $order ) {
        if ( ! $order instanceof \WC_Order ) {
            return;
        }

        $receiver_name = $order->get_meta( '_bwdk_receiver_name' );

        // Fallback: read from stored BWDK raw JSON (destination_address) for legacy orders
        if ( empty( $receiver_name ) && class_exists( '\BWDK\Support\Constant' ) ) {
            $raw_json = $order->get_meta( \BWDK\Support\Constant::META_BWDK_JSON_CB );
            if ( is_string( $raw_json ) ) {
                $raw_json = json_decode( $raw_json, true );
            }
            if ( ! empty( $raw_json ) && is_array( $raw_json ) ) {
                $dest = $raw_json['destination_address'] ?? null;
                if ( is_array( $dest ) ) {
                    $receiver_name = trim( (string) ( $dest['receiver_name'] ?? '' ) );
                }
            }
        }

        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            error_log( '[BWDK] render hook fired order_id=' . $order->get_id() . ' meta_name=' . $receiver_name );
        }

        if ( is_string( $receiver_name ) ) {
            $receiver_name = trim( $receiver_name );
        }
        if ( $receiver_name ) {
            echo '<p><strong>نام گیرنده (دیجی‌کالا):</strong> ' . esc_html( $receiver_name ) . '</p>';
        }
    }
}

add_action( 'init', function () {
    if ( is_admin() && function_exists( 'wc_get_order' ) ) {
        add_action( 'woocommerce_admin_order_data_after_shipping_address', 'bwdk_render_receiver_name_in_admin', 10, 1 );
    }
}, 20 );



add_action( 'template_redirect', function () {
    if ( ! function_exists( 'is_order_received_page' ) || ! is_order_received_page() ) {
        return;
    }

    if ( WC()->cart && WC()->cart->get_cart_contents_count() > 0 ) {
        return;
    }

    $order_id = absint( get_query_var( 'order-received' ) );

    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }


    $bad_statuses = array( 'failed', 'cancelled', 'pending' );
    if ( ! in_array( $order->get_status(), $bad_statuses, true ) ) {
        return;
    }


    foreach ( $order->get_items() as $item ) {
        if ( ! $item instanceof WC_Order_Item_Product ) {
            continue;
        }

        $qty      = (int) $item->get_quantity();
        $product  = $item->get_product();

        if ( ! $product || ! $product->is_purchasable() ) {
            continue;
        }

        $product_id   = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();
        $variation_id = $product->is_type( 'variation' ) ? $product->get_id() : (int) $item->get_variation_id();
        $variations   = array();


        if ( $variation_id ) {
            $variation_product = wc_get_product( $variation_id );
            if ( $variation_product ) {
                $variations = $variation_product->get_attributes();
            }
        }

        WC()->cart->add_to_cart( $product_id, $qty, $variation_id, $variations );
    }

    foreach ( $order->get_coupon_codes() as $code ) {
        WC()->cart->apply_coupon( $code );
    }

} ,100);




