<?php

/**
 * Plugin Name: Buy With Digikala
 * Plugin URI: https://digify.shop/
 * Description: امکان خرید از سایت توسط دیجی کالا
 * Version: 1.2.9
 * 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.2.9' );
}

// 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';

// Load update checker
require_once __DIR__ . '/src/Support/UpdateChecker.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();
});

/**
 * 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);




