<?php

/**
 * Anbaarak | Best Inventory management plugin for WooCommerce.
 * All rights reserved for WP LEGEND team (wplegend.ir)
 */

namespace Anbarak;

if (!defined('WPINC')) {
    die;
}

define('ANBARAK_VERSION',   '1.0.0');

define('ANBARAK_PRODUCTS_PER_PAGE', 50);
define('ANBARAK_PRODUCTS_LOW_STOCK_THRESHOLD', get_option('woocommerce_notify_low_stock_amount', 5));
define('ANBARAK_PRODUCTS_OUT_OF_STOCK_THRESHOLD', get_option('woocommerce_notify_no_stock_amount', 0));

define('ANBARAK_URL', plugin_dir_url(__FILE__));
define('ANBARAK_PATH', plugin_dir_path(__FILE__));
define('ANBARAK_VIEW_PATH', plugin_dir_path(__FILE__) . 'admin/views/');
define('ANBARAK_DIRNAME', dirname(plugin_basename(__FILE__)));

define('ANBARAK_PURCHASES_EXPENSE_TAG_NAME', 'Product Purchase');

class plugin
{
    /**
     * Static property to hold our singleton instance
     *
     */
    public static $instance = false;

    /**
     * Class constructor
     */
    public function __construct()
    {
        global $wpdb;

        require_once ANBARAK_PATH . 'includes/classes/Tables.php';
        require_once ANBARAK_PATH . 'includes/classes/ProductsInfo.php';

        // add helpers
        require_once ANBARAK_PATH . 'includes/helpers/expenses.php';

        require_once ANBARAK_PATH . 'includes/helpers/permission.php';
        require_once ANBARAK_PATH . 'includes/helpers.php';
        require_once ANBARAK_PATH . 'includes/helpers/notifications.php';

        // add global hooks that needed also in front
        require_once ANBARAK_PATH . 'includes/hooks.php';

        // WP Admin stuff
        if (is_admin()) {
            $this->initAdmin();
        }
    }

    /**
     * If an instance exists, this returns it.  If not, it creates one and
     * returns it.
     *
     * @return anbarak
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function initAdmin()
    {
        // Add top menu
        add_action('admin_menu', array($this, 'addTopMenus'));

        if ($this->isInAnbarakPage()) {
            if ($this->isFullscreen()) {
                add_filter('admin_body_class', fn($c) => $c . ' full-page');
            }
        }

        // include common helpers
        require_once ANBARAK_PATH . 'includes/helpers/template.php';
        require_once ANBARAK_PATH . 'includes/helpers/expenses.php';
        require_once ANBARAK_PATH . 'includes/helpers/expenses_tags.php';
        require_once ANBARAK_PATH . 'includes/helpers/stats.php';

        require_once ANBARAK_PATH . 'includes/classes/Html.php';

        /**
         * required file for creating & updating plugin table.
         * included after all common helper functions.
         */
        require_once ANBARAK_PATH . 'includes/upgrade.php';

        add_action('admin_init', function () {
            $this->startAnbarakUi();
        });

        // Register devtools pages when in development mode
        if (in_array(wp_get_environment_type(), ['local', 'development'], true) && is_dir(ANBARAK_PATH . 'devtools')) {
            add_action('admin_menu', function () {
                add_submenu_page(
                    'anbarak',
                    __('Simulate', 'anbarak'),
                    __('Simulate', 'anbarak'),
                    'manage_woocommerce',
                    'anbarak-simulate',
                    function () {
                        require_once ANBARAK_PATH . 'devtools/simulate.php';
                    }
                );
            });
        }
    }

    public function isInAnbarakPage()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return isset($_GET['page']) && 'anbarak' === sanitize_text_field(wp_unslash($_GET['page']));
    }

    public function isFullscreen()
    {
        return isset($_COOKIE['anbarak_fullscreen']) && '1' === sanitize_text_field(wp_unslash($_COOKIE['anbarak_fullscreen']));
    }


    // start anbarak when in admin ui
    public function startAnbarakUi()
    {

        if ($this->isInAnbarakPage() && version_compare(get_option('anbarak_version'), ANBARAK_VERSION, '<')) {
            anbarak_die(__('Please disable and enable plugin again to upgrade to the latest version.', 'anbarak'), __('Upgrade is Required!', 'anbarak'));
        }

        if (!class_exists('WooCommerce')) {
            anbarak_die(__('Please install and activate Woocommerce plugin.', 'anbarak'), 'Missing Woocommerce');
        }

        if (!defined('ANBARAK_AJAX_NONCE')) {
            define('ANBARAK_AJAX_NONCE', wp_create_nonce('anbarak-ajax-nonce'));
        }

        // load composer packages
        require_once ANBARAK_PATH . 'vendor/autoload.php';

        require_once ANBARAK_PATH . 'includes/admin-hooks.php';

        require_once ANBARAK_PATH . 'includes/ajax.php';
        require_once ANBARAK_PATH . 'includes/ajax/stock.php';
        require_once ANBARAK_PATH . 'includes/ajax/order.php';
        require_once ANBARAK_PATH . 'includes/ajax/export.php';
        require_once ANBARAK_PATH . 'includes/admin-template-functions.php';

        // fullscreen toggle
        add_action('wp_ajax_anbarak_toggle_fullscreen', function () {
            check_ajax_referer('anbarak-ajax-nonce', 'security');
            anbarak_require_ajax_app_access();
            $value = isset($_POST['fullscreen']) && '1' === sanitize_text_field(wp_unslash($_POST['fullscreen'])) ? '1' : '0';
            setcookie('anbarak_fullscreen', $value, time() + (20 * 365 * 24 * 60 * 60), '/');
            wp_send_json_success();
        });

        // dismiss fullscreen hint
        add_action('wp_ajax_anbarak_dismiss_fullscreen_hint', function () {
            check_ajax_referer('anbarak-ajax-nonce', 'security');
            anbarak_require_ajax_app_access();
            setcookie('anbarak_fullscreen_hint_dismissed', '1', time() + (30 * 24 * 60 * 60), '/');
            wp_send_json_success();
        });

        // add admin script
        add_action('admin_enqueue_scripts', array($this, 'removeOtherScripts'), 900);
        add_action('admin_enqueue_scripts', array($this, 'addAdminScripts'), 990);
    }

    /**
     * Admin scripts
     *
     * @return void
     */
    public function addAdminScripts()
    {
        if (!$this->isInAnbarakPage()) return;

        wp_enqueue_script('jquery');
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_script('password-strength-meter');
        wp_enqueue_script('echarts', plugins_url('admin/libs/echarts.min.js', __FILE__), array(), ANBARAK_VERSION, true);
        wp_enqueue_script('micromodal', plugins_url('admin/libs/micromodal.min.js', __FILE__), array(), true, ANBARAK_VERSION);

        wp_enqueue_script('persian-date', plugins_url('admin/libs/persian-datepicker/persian-date.min.js', __FILE__), array('jquery'), ANBARAK_VERSION, true);
        wp_enqueue_script('perisan-datepicker', plugins_url('admin/libs/persian-datepicker/persian-datepicker.min.js', __FILE__), array('jquery'), ANBARAK_VERSION, true);

        wp_enqueue_script('popper', plugins_url('admin/libs/popper.min.js', __FILE__), array(), true, ANBARAK_VERSION);
        wp_enqueue_script('tippy', plugins_url('admin/libs/tippy-bundle.umd.min.js', __FILE__), array(), true, ANBARAK_VERSION);

        wp_enqueue_style('iconfont', plugins_url('admin/fonts/iconfont/style.css', __FILE__), [], ANBARAK_VERSION);
        wp_enqueue_style('estedad', plugins_url('admin/fonts/estedad/style.css', __FILE__), [], ANBARAK_VERSION);
        wp_enqueue_style('persian-datepicker', plugins_url('admin/libs/persian-datepicker/persian-datepicker.min.css', __FILE__), [], ANBARAK_VERSION);
        wp_add_inline_style(
            'iconfont',
            sprintf(
                '.anbarak-blocker .anbarak-spinner { background-image: url("%s") !important; }',
                esc_url(ANBARAK_URL . 'admin/images/loading.gif')
            )
        );


        $this->remove_wp_styles();
        $this->enqueue_vite_assets();
    }

    /** 
     * remove other plugins css cause css conflict when we are in anbarak 
     */
    public function removeOtherScripts()
    {

        if (!$this->isInAnbarakPage()) return;

        if (!$this->isFullscreen()) return;

        global $wp_styles;

        if (isset($wp_styles->queue) && is_array($wp_styles->queue)) {
            foreach ($wp_styles->queue as $handle) {
                wp_dequeue_style($handle);
                wp_deregister_style($handle);
            }
        }
    }


    function remove_wp_styles()
    {
        if (!$this->isFullscreen()) return;

        wp_deregister_style('wp-admin');
        wp_deregister_style('buttons');
        wp_deregister_style('common');
        wp_deregister_style('forms');
        wp_deregister_style('admin-menu');
        wp_deregister_style('dashboard');
        wp_deregister_style('list-tables');
        wp_deregister_style('edit');
        wp_deregister_style('revisions');
        wp_deregister_style('media');
        wp_deregister_style('themes');
        wp_deregister_style('about');
        wp_deregister_style('nav-menus');
        wp_deregister_style('widgets');
        wp_deregister_style('site-icon');
        wp_deregister_style('l10n');
        wp_deregister_style('code-editor');
    }

    function enqueue_vite_assets()
    {
        $plugin_url = ANBARAK_URL;
        $plugin_path = plugin_dir_path(__FILE__);
        $is_dev = in_array(wp_get_environment_type(), ['local', 'development'], true);
        
        if ($is_dev) {
            
            // DEV mode - load from Vite dev server
            $vite_dev_url = defined('ANBARAK_VITE_DEV_URL') ? ANBARAK_VITE_DEV_URL : 'http://localhost:5173';
            wp_register_script('anbarak-main', $vite_dev_url . '/src/main.js', [], ANBARAK_VERSION, true);
            wp_register_script('anbarak-devtool', ANBARAK_URL . '/devtools/devtool.js', [], ANBARAK_VERSION, true);
        } else {
            // PRODUCTION mode - use manifest
            $manifest_path = $plugin_path . 'build/.vite/manifest.json';
            if (!file_exists($manifest_path)) {
                return;
            }

            $manifest = wp_json_file_decode($manifest_path, ['associative' => true]);
            $entry = $manifest['src/main.js'] ?? null;

            if (!$entry || empty($entry['file'])) {
                return;
            }

            // Enqueue main JS
            wp_register_script(
                'anbarak-main',
                $plugin_url . '/build/' . $entry['file'],
                ['jquery', 'wp-color-picker'],
                ANBARAK_VERSION,
                true
            );

            // Enqueue associated CSS (if any)
            if (!empty($entry['css'])) {
                foreach ($entry['css'] as $index => $css_file) {
                    wp_enqueue_style(
                        'anbarak-style-' . $index,
                        $plugin_url . 'build/' . $css_file,
                        [],
                        ANBARAK_VERSION
                    );
                }
            }
        }

        $translated_data = array(
            'url'       => ANBARAK_URL,
            'ajax_url'  => admin_url('admin-ajax.php'),
            'nonce'     => ANBARAK_AJAX_NONCE,
            'is_jalali' => anbarak_should_use_jalali_date(),
            'default_country' => anbarak_get_order_default_country(),

            'i18n' => array_map('esc_js', [
                'ok'                        => __('Okay', 'anbarak'),
                'cancel'                    => __('Cancel', 'anbarak'),
                'understood'                => __('Understood', 'anbarak'),
                'confirm'                   => __('Confirm', 'anbarak'),
                'are_you_sure'              => __('Are you sure?', 'anbarak'),
                'serial_number'             => __('Serial Number', 'anbarak'),
                'delete_role'               => __('Are you sure want to delete this party type?', 'anbarak'),
                'in_store_sales'            => __('In-Store Sales', 'anbarak'),
                'online_sales'              => __('Online Sales', 'anbarak'),
                'total_sales'               => __('Total Sales Price', 'anbarak'),
                'expenses'                  => __('Expenses Price', 'anbarak'),
                'register_sell'             => __('Are you sure want to register an in-store sale?', 'anbarak'),
                'delete_confirm'            => __('Are you sure want to delete this item?', 'anbarak'),
                'register_buy_quantity'     => __('Please enter number of products bought', 'anbarak'),
                'register_buy_unit_price'   => __('Enter single unit price', 'anbarak'),
                'month_total_sale_price'    => __('Total Sale Price', 'anbarak'),
                'month_online_sale_price'   => __('Total Online Sale Price', 'anbarak'),
                'month_offline_sale_price'  => __('Total In-store Sale Price', 'anbarak'),
                'month_total_expense_price' => __('Total Expense', 'anbarak'),
                'online_sale'               => __('Online Sale', 'anbarak'),
                'offline_sale'              => __('Offline Sale', 'anbarak'),
                'monthly_report'            => __('Monthly Report', 'anbarak'),
                'sale'                      => __('Sale', 'anbarak'),
                'day_of_month'              => __('Day of month', 'anbarak'),
                'months'                    => __('Months', 'anbarak'),
                'price'                     => __('Price', 'anbarak'),
                'create'                    => __('Create', 'anbarak'),
                'save_changes'              => __('Save Changes', 'anbarak'),
                'create_party'              => __('Create Party', 'anbarak'),
                'edit_party'                => __('Edit Party', 'anbarak'),
                'mark_sent'                 => __('Mark as Sent', 'anbarak'),
                'mark_not_sent'             => __('Mark as Not Sent', 'anbarak'),
                'error'                     => __('Error', 'anbarak'),
                'error_creating_type'       => __('Error creating type', 'anbarak'),
                'update_failed'             => __('Update failed', 'anbarak'),
                'delete_failed'             => __('Delete failed', 'anbarak'),
                'error_creating_party'      => __('Error creating party', 'anbarak'),
                'error_saving_party'        => __('Error saving party', 'anbarak'),
                'delete_party'              => __('Delete this party?', 'anbarak'),
                'error_saving_product'      => __('Error saving product', 'anbarak'),
                'request_failed'            => __('Request failed:', 'anbarak'),
                'loading'                   => __('Loading ...', 'anbarak'),
                'not_available'             => __('n/a', 'anbarak'),
                'stock'                     => __('Stock', 'anbarak'),
                'nothing_found'             => __('Nothing found', 'anbarak'),
                'connection_error'          => __('Connection error', 'anbarak'),
                'phone_required_for_user'   => __('Phone number is required for creating user', 'anbarak'),
                'order_creation_failed'     => __('Order creation failed, please try again', 'anbarak'),
                'delete_tag'                => __('Are you sure you want to delete this tag?', 'anbarak'),
                'edit_tag'                  => __('Edit Tag', 'anbarak'),
                'tag_updated'               => __('Tag updated successfully', 'anbarak'),
                'tag_created'               => __('Tag created successfully', 'anbarak'),
                'tag_deleted'               => __('Tag deleted successfully', 'anbarak'),
                'settings_saved'            => __('Settings saved', 'anbarak'),
                'address_province_required' => __('Please enter address and province', 'anbarak'),
                'fetching'                  => __('Fetching...', 'anbarak'),
                'address_not_found'         => __('Address not found', 'anbarak'),
                'get_coordinates'           => __('Get Coordinates from Address', 'anbarak'),
                'generic_error'             => __('An error occurred', 'anbarak'),
                'server_connection_error'   => __('Error connecting to server', 'anbarak'),
                'error_toggling_status'     => __('Error toggling status', 'anbarak'),
                'gross_profit'              => __('Gross Profit', 'anbarak'),
                'last_6_months_sales_stats' => __('Last 6 Months Sales Statistics', 'anbarak'),
                'zoom_chart_hint'           => __('You can zoom on the chart by clicking and dragging', 'anbarak'),
                'sales_gross_profit_chart'  => __('Sales & Gross Profit Chart', 'anbarak'),
                'expense_distribution_chart' => __('Expense Distribution Chart', 'anbarak'),
                'share'                     => __('Share', 'anbarak'),
                'select_province'           => __('Select Province', 'anbarak'),
                'fullscreen_entered'        => __('Fullscreen mode enabled', 'anbarak'),
                'fullscreen_exited'         => __('Fullscreen mode disabled', 'anbarak'),
                'no_notifications'         => __('No Notifications', 'anbarak'),
                'review_request_title'     => __('We need your feedback!', 'anbarak'),
                'review_request_body'      => __('Hi there! This is the first release of Anbarak Lite and we need your support to improve it.', 'anbarak'),
                'review_request_cta'       => __('Your feedback, bug reports, and feature requests help us make Anbarak better for everyone.', 'anbarak'),
                'review_leave_stars'       => __('Leave a 5-star review', 'anbarak'),
                'review_support'           => __('Support & Bug Reports', 'anbarak'),
                'review_remind_later'      => __('Remind me later', 'anbarak'),
                'submit_a_review'          => __('Submit a review', 'anbarak'),
            ]),
        );
        wp_localize_script('anbarak-main', 'anbarak', $translated_data);

        if (!$this->isFullscreen()) {
            wp_add_inline_script('anbarak-main', 'document.body.classList.remove("wp-core-ui");');
        }

        wp_enqueue_script('anbarak-main');

        if ($is_dev) {
            wp_enqueue_script('anbarak-devtool');
        }

        add_filter('script_loader_tag', function ($tag, $handle) {
            if ($handle === 'anbarak-main') {
                return str_replace(' src', ' type="module" src', $tag);
            }
            return $tag;
        }, 10, 2);
    }

    /**
     * adds plugin top menu
     *
     * @return void
     */
    public function addTopMenus()
    {

        add_menu_page(
            __('Anbaarak', 'anbarak'),
            __('Anbaarak', 'anbarak'),
            'manage_woocommerce',
            'anbarak',
            array($this, 'anbarak_main_page'),
            plugin_dir_url(__FILE__) . '/public/images/logo.png',
            75
        );
    }

    /**
     * Plugin's main page
     *
     * @return void
     */
    public function anbarak_main_page()
    {

        include_once plugin_dir_path(__FILE__) . 'admin/views/main.php';
    }
}

// Instantiate our class
$anbarak = plugin::getInstance();
