<?php

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

class AIEO_DMM_Branch_Scanner extends AIEO_DMM_Module_Base {

    public function get_id() { return 'branch_scanner'; }
    public function get_label() { return __('Branch Stock Scanner', 'ai-eshop-optimizer'); }
    public function get_priority() { return 74; } 
    public function get_group() { return 'product_management'; }

    public function is_pro_locked() { return true; }
    public function get_pro_promo() {
        return array(
            'title'       => __('Branch Stock Scanner', 'ai-eshop-optimizer'),
            'description' => __('Multi-branch / multi-warehouse stock visibility from inside the WooCommerce admin. Scan a SKU or barcode and see availability per location, transfer history, and per-branch sell-through — so staff in store #2 stop telling customers a SKU is out of stock when #4 has six on the shelf.', 'ai-eshop-optimizer'),
            'bullets'     => array(
                __('Per-branch stock counters with one-click rebalance.', 'ai-eshop-optimizer'),
                __('Barcode scanner UI optimised for handheld + tablet on the warehouse floor.', 'ai-eshop-optimizer'),
                __('Integrates with the ERP Bridge for live-from-truck updates.', 'ai-eshop-optimizer'),
            ),
        );
    }

    const SCAN_NONCE_ACTION = 'aieo_dmm_scan';

    public function register_hooks() {
        
        add_action('wp_ajax_aieo_dmm_branch_save', array($this, 'ajax_save_branch'));
        add_action('wp_ajax_aieo_dmm_branch_delete', array($this, 'ajax_delete_branch'));

        
        add_action('wp_ajax_aieo_dmm_scanner_staff_lookup', array($this, 'ajax_staff_lookup'));
        add_action('wp_ajax_aieo_dmm_scanner_staff_update', array($this, 'ajax_staff_update'));

        
        add_action('wp_ajax_aieo_dmm_scanner_customer_lookup', array($this, 'ajax_customer_lookup'));
        add_action('wp_ajax_nopriv_aieo_dmm_scanner_customer_lookup', array($this, 'ajax_customer_lookup'));

        
        add_shortcode('aieo_dmm_branch_scanner', array($this, 'shortcode_staff_scanner'));
        add_shortcode('aieo_dmm_customer_scanner', array($this, 'shortcode_customer_scanner'));
    }

    public function render_subtab() {
        $this->render_template('branch-scanner.php', array(
            'branches'         => $this->fetch_branches(),
            'recent_log'       => $this->fetch_recent_log(25),
            'recent_preorders' => $this->fetch_recent_preorders(50),
            'preorder_summary' => $this->fetch_preorder_summary_by_supplier(),
        ));
    }

    
    private function fetch_recent_preorders($limit = 50) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_supplier_preorders';
        if (!aieo_dmm_table_exists($table)) { return array(); }
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT p.*, b.label AS branch_label
               FROM {$table} p
               LEFT JOIN {$wpdb->prefix}aieo_dmm_branches b ON b.id = p.branch_id
              ORDER BY p.created_at DESC
              LIMIT %d",
            (int) $limit
        ), ARRAY_A);
        if (!is_array($rows)) { return array(); }
        
        foreach ($rows as &$r) {
            $r['product_title']  = $r['product_id']       ? get_the_title((int) $r['product_id']) : '';
            $r['supplier_name']  = $r['supplier_term_id'] ? (function ($id) { $t = get_term((int) $id); return ($t && !is_wp_error($t)) ? $t->name : ''; })($r['supplier_term_id']) : '';
            $r['brand_name']     = $r['brand_term_id']    ? (function ($id) { $t = get_term((int) $id); return ($t && !is_wp_error($t)) ? $t->name : ''; })($r['brand_term_id']) : '';
        }
        return $rows;
    }

    
    private function fetch_preorder_summary_by_supplier() {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_supplier_preorders';
        if (!aieo_dmm_table_exists($table)) { return array(); }
        $rows = $wpdb->get_results(
            "SELECT supplier_term_id,
                    COUNT(*)            AS line_count,
                    SUM(requested_qty)  AS total_qty,
                    MAX(created_at)     AS most_recent_at
               FROM {$table}
              WHERE fulfilled = 0
              GROUP BY supplier_term_id
              ORDER BY total_qty DESC",
            ARRAY_A
        );
        if (!is_array($rows)) { return array(); }
        foreach ($rows as &$r) {
            $r['supplier_name'] = $r['supplier_term_id']
                ? (function ($id) { $t = get_term((int) $id); return ($t && !is_wp_error($t)) ? $t->name : '— unresolved —'; })($r['supplier_term_id'])
                : '— unresolved —';
        }
        return $rows;
    }

    public function fetch_branches() {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branches';
        if (!aieo_dmm_table_exists($table)) {
            return array();
        }
        
        $rows = $wpdb->get_results("SELECT * FROM {$table} ORDER BY sort_order ASC, label ASC", ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    public function fetch_enabled_branches() {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branches';
        if (!aieo_dmm_table_exists($table)) {
            return array();
        }
        
        $rows = $wpdb->get_results("SELECT * FROM {$table} WHERE enabled = 1 ORDER BY sort_order ASC, label ASC", ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    private function fetch_recent_log($limit = 25) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branch_scan_log';
        if (!aieo_dmm_table_exists($table)) {
            return array();
        }
        
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d",
            (int) $limit
        ), ARRAY_A);
        return is_array($rows) ? $rows : array();
    }

    
    
    

    public function ajax_save_branch() {
        AIEO_DMM::verify_ajax_request();

        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branches';
        if (!aieo_dmm_table_exists($table)) {
            wp_send_json_error(array('message' => __('Table missing.', 'ai-eshop-optimizer')));
        }

        $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0;
        $slug = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
        $label = isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : '';
        $stock_table = isset($_POST['stock_table']) ? sanitize_text_field(wp_unslash($_POST['stock_table'])) : '';
        $match_col = isset($_POST['match_col']) ? sanitize_key(wp_unslash($_POST['match_col'])) : 'gtin';
        $enabled = !empty($_POST['enabled']) ? 1 : 0;
        $sort_order = isset($_POST['sort_order']) ? (int) $_POST['sort_order'] : 0;
        
        
        
        $soft1_id_raw = isset($_POST['soft1_id']) ? trim((string) wp_unslash($_POST['soft1_id'])) : '';
        $soft1_id = ($soft1_id_raw === '') ? null : (int) $soft1_id_raw;

        if ($slug === '' || $label === '' || $stock_table === '') {
            wp_send_json_error(array('message' => __('Slug, label and stock table are required.', 'ai-eshop-optimizer')));
        }
        
        if (!aieo_dmm_table_exists($stock_table)) {
            wp_send_json_error(array('message' => sprintf(
                
                __('Table "%s" does not exist in the database.', 'ai-eshop-optimizer'),
                $stock_table
            )));
        }

        $data = array(
            'slug' => $slug,
            'label' => $label,
            'stock_table' => $stock_table,
            'match_col' => $match_col,
            'enabled' => $enabled,
            'sort_order' => $sort_order,
            'soft1_id' => $soft1_id,
        );
        $formats = array('%s', '%s', '%s', '%s', '%d', '%d', '%d');

        if ($id > 0) {
            $wpdb->update($table, $data, array('id' => $id), $formats, array('%d'));
        } else {
            $existing = $wpdb->get_var($wpdb->prepare(
                
                "SELECT id FROM {$table} WHERE slug = %s",
                $slug
            ));
            if ($existing) {
                wp_send_json_error(array('message' => __('A branch with that slug already exists.', 'ai-eshop-optimizer')));
            }
            $wpdb->insert($table, $data, $formats);
            $id = (int) $wpdb->insert_id;
        }
        wp_send_json_success(array('id' => $id, 'message' => __('Branch saved.', 'ai-eshop-optimizer')));
    }

    public function ajax_delete_branch() {
        AIEO_DMM::verify_ajax_request();

        $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0;
        if ($id <= 0) {
            wp_send_json_error(array('message' => __('Invalid id.', 'ai-eshop-optimizer')));
        }
        global $wpdb;
        $wpdb->delete($wpdb->prefix . 'aieo_dmm_branches', array('id' => $id), array('%d'));
        wp_send_json_success();
    }

    
    
    

    public function shortcode_staff_scanner($atts) {
        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please log in to use the staff scanner.', 'ai-eshop-optimizer') . '</p>';
        }
        if (!current_user_can('manage_woocommerce') && !current_user_can('edit_products')) {
            return '';
        }

        $branches = $this->fetch_enabled_branches();
        $nonce = wp_create_nonce(self::SCAN_NONCE_ACTION);

        ob_start();
        ?>
        <div class="aieo-dmm-staff-scanner" data-nonce="<?php echo esc_attr($nonce); ?>">
            <label for="aieo-dmm-branch-select"><?php esc_html_e('Branch', 'ai-eshop-optimizer'); ?></label>
            <select id="aieo-dmm-branch-select">
                <?php foreach ($branches as $b) : ?>
                    <option value="<?php echo esc_attr($b['slug']); ?>"
                            data-table="<?php echo esc_attr($b['stock_table']); ?>"
                            data-match="<?php echo esc_attr($b['match_col']); ?>">
                        <?php echo esc_html($b['label']); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <label for="aieo-dmm-barcode-input"><?php esc_html_e('Scan or enter barcode', 'ai-eshop-optimizer'); ?></label>
            <input type="text" id="aieo-dmm-barcode-input" inputmode="numeric" autocomplete="off">

            <div class="aieo-dmm-scanner-result" style="display:none"></div>
        </div>
        <?php
        $this->enqueue_scanner_assets();
        return ob_get_clean();
    }

    public function ajax_staff_lookup() {
        check_ajax_referer(self::SCAN_NONCE_ACTION, 'nonce');
        if (!current_user_can('manage_woocommerce') && !current_user_can('edit_products')) {
            wp_send_json_error(array('message' => __('Forbidden.', 'ai-eshop-optimizer')));
        }

        $barcode = isset($_POST['barcode']) ? sanitize_text_field(wp_unslash($_POST['barcode'])) : '';
        $branch_slug = isset($_POST['branch']) ? sanitize_key(wp_unslash($_POST['branch'])) : '';
        if ($barcode === '' || $branch_slug === '') {
            wp_send_json_error(array('message' => __('Missing barcode or branch.', 'ai-eshop-optimizer')));
        }
        $branch = $this->get_branch_by_slug($branch_slug);
        if (!$branch) {
            wp_send_json_error(array('message' => __('Unknown branch.', 'ai-eshop-optimizer')));
        }

        global $wpdb;
        $table = $branch['stock_table'];
        $match = $branch['match_col'];
        
        if (!in_array($match, array('gtin', 'sku', 'product_id', 'barcode'), true)) {
            wp_send_json_error(array('message' => __('Unsupported match column.', 'ai-eshop-optimizer')));
        }
        $row = $wpdb->get_row($wpdb->prepare(
            
            "SELECT * FROM {$table} WHERE {$match} = %s LIMIT 1",
            $barcode
        ), ARRAY_A);

        if (!$row) {
            $this->log_scan($barcode, 'missing', (int) $branch['id']);
            wp_send_json_error(array('message' => __('Barcode not found in branch table.', 'ai-eshop-optimizer')));
        }
        wp_send_json_success(array('row' => $row));
    }

    public function ajax_staff_update() {
        check_ajax_referer(self::SCAN_NONCE_ACTION, 'nonce');
        if (!current_user_can('manage_woocommerce') && !current_user_can('edit_products')) {
            wp_send_json_error(array('message' => __('Forbidden.', 'ai-eshop-optimizer')));
        }

        $barcode = isset($_POST['barcode']) ? sanitize_text_field(wp_unslash($_POST['barcode'])) : '';
        $branch_slug = isset($_POST['branch']) ? sanitize_key(wp_unslash($_POST['branch'])) : '';
        $field = isset($_POST['field']) ? sanitize_key(wp_unslash($_POST['field'])) : '';
        $value = isset($_POST['value']) ? (float) $_POST['value'] : 0.0;

        $allowed_fields = array('existing_stock', 'desired_qty');
        if (!in_array($field, $allowed_fields, true)) {
            wp_send_json_error(array('message' => __('Unsupported field.', 'ai-eshop-optimizer')));
        }

        $branch = $this->get_branch_by_slug($branch_slug);
        if (!$branch) {
            wp_send_json_error(array('message' => __('Unknown branch.', 'ai-eshop-optimizer')));
        }
        global $wpdb;
        $table = $branch['stock_table'];
        $match = $branch['match_col'];
        if (!in_array($match, array('gtin', 'sku', 'product_id', 'barcode'), true)) {
            wp_send_json_error(array('message' => __('Unsupported match column.', 'ai-eshop-optimizer')));
        }

        
        
        
        $this->set_trigger_context('barcode_scan');

        
        
        
        
        $prior_row = $wpdb->get_row($wpdb->prepare(
            
            "SELECT * FROM {$table} WHERE {$match} = %s LIMIT 1",
            $barcode
        ), ARRAY_A);

        $updated = $wpdb->query($wpdb->prepare(
            
            "UPDATE {$table} SET `{$field}` = %f WHERE {$match} = %s",
            $value,
            $barcode
        ));

        
        
        
        
        
        
        

        wp_send_json_success(array(
            'updated' => (int) $updated,
            'message' => __('Stock updated.', 'ai-eshop-optimizer'),
        ));
    }

    
    private function append_supplier_preorder(array $prior_row, $branch_id, $requested_qty) {
        global $wpdb;
        $log_table = $wpdb->prefix . 'aieo_dmm_supplier_preorders';
        if (!aieo_dmm_table_exists($log_table)) { return; }

        $product_id = isset($prior_row['product_id']) ? (int) $prior_row['product_id'] : 0;
        if ($product_id <= 0) { return; }

        
        
        
        $brand_id    = null;
        $supplier_id = null;
        $brand_terms = wp_get_object_terms($product_id, 'product_brand', array('fields' => 'ids'));
        if (!is_wp_error($brand_terms) && !empty($brand_terms)) {
            $brand_id = (int) $brand_terms[0];
            if (class_exists('AIEO_DMM_Brand_Extras_Data')) {
                $brand_extras = AIEO_DMM_Brand_Extras_Data::get('product_brand', $brand_id);
                if (!empty($brand_extras['supplier_term_id'])) {
                    $supplier_id = (int) $brand_extras['supplier_term_id'];
                }
            }
        }

        $wpdb->insert($log_table, array(
            'supplier_term_id' => $supplier_id,
            'brand_term_id'    => $brand_id,
            'product_id'       => $product_id,
            'branch_id'        => (int) $branch_id,
            'scanned_user_id'  => (int) get_current_user_id(),
            'requested_qty'    => (int) $requested_qty,
            'prior_existing'   => isset($prior_row['existing_stock']) ? (int) $prior_row['existing_stock'] : null,
            'fulfilled'        => 0,
            'created_at'       => current_time('mysql', true),
        ));
    }

    
    private function set_trigger_context($origin_type) {
        global $wpdb;

        $user = wp_get_current_user();
        $user_login = ($user && $user->ID) ? (string) $user->user_login : 'nopriv';

        
        
        $wpdb->query($wpdb->prepare('SET @ORIGIN_TYPE = %s', (string) $origin_type));
        $wpdb->query($wpdb->prepare('SET @ORIGIN_USER = %s', $user_login));
    }

    
    
    

    public function shortcode_customer_scanner($atts) {
        $nonce = wp_create_nonce(self::SCAN_NONCE_ACTION);
        ob_start();
        ?>
        <div class="aieo-dmm-customer-scanner" data-nonce="<?php echo esc_attr($nonce); ?>">
            <p><?php esc_html_e('Scan a product barcode with your camera or type it below.', 'ai-eshop-optimizer'); ?></p>
            <button type="button" class="aieo-dmm-start-camera"><?php esc_html_e('Start camera', 'ai-eshop-optimizer'); ?></button>
            <video class="aieo-dmm-scanner-video" style="display:none;max-width:100%;"></video>

            <label for="aieo-dmm-cust-barcode-input"><?php esc_html_e('Or enter barcode', 'ai-eshop-optimizer'); ?></label>
            <input type="text" id="aieo-dmm-cust-barcode-input" inputmode="numeric" autocomplete="off">
            <button type="button" class="aieo-dmm-lookup-barcode"><?php esc_html_e('Look up', 'ai-eshop-optimizer'); ?></button>

            <div class="aieo-dmm-customer-result" style="display:none"></div>
        </div>
        <?php
        $this->enqueue_scanner_assets();
        return ob_get_clean();
    }

    public function ajax_customer_lookup() {
        check_ajax_referer(self::SCAN_NONCE_ACTION, 'nonce');

        $barcode = isset($_POST['barcode']) ? sanitize_text_field(wp_unslash($_POST['barcode'])) : '';
        if ($barcode === '' || strlen($barcode) > 64) {
            wp_send_json_error(array('message' => __('Please scan a valid barcode.', 'ai-eshop-optimizer')));
        }

        
        $product_id = 0;
        if (function_exists('wc_get_product_id_by_sku')) {
            $product_id = (int) wc_get_product_id_by_sku($barcode);
        }
        if ($product_id === 0) {
            
            global $wpdb;
            $product_id = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key IN ('_sku','_gtin','_barcode','_global_unique_id') AND meta_value = %s LIMIT 1",
                $barcode
            ));
        }
        if ($product_id <= 0 || !function_exists('wc_get_product')) {
            wp_send_json_error(array('message' => __('Product not found.', 'ai-eshop-optimizer')));
        }
        $product = wc_get_product($product_id);
        if (!$product || !$product->is_purchasable()) {
            wp_send_json_error(array('message' => __('This product is not available for purchase.', 'ai-eshop-optimizer')));
        }

        
        $price = (float) $product->get_price();
        if (class_exists('AIEO_DMM_Pricing_Engine')) {
            $price = (float) AIEO_DMM_Pricing_Engine::instance()->get_effective_price($product_id, null, (float) $product->get_regular_price());
        }

        $image = wp_get_attachment_image_url($product->get_image_id(), 'medium');

        wp_send_json_success(array(
            'product_id' => $product_id,
            'title'      => $product->get_name(),
            'price'      => wc_price($price),
            'image_url'  => $image ? $image : '',
            'add_to_cart_url' => $product->add_to_cart_url(),
            'permalink'  => get_permalink($product_id),
        ));
    }

    private function get_branch_by_slug($slug) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branches';
        if (!aieo_dmm_table_exists($table)) {
            return null;
        }
        
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE slug = %s AND enabled = 1",
            $slug
        ), ARRAY_A);
        return $row;
    }

    private function log_scan($barcode, $status, $branch_id = 0) {
        global $wpdb;
        $table = $wpdb->prefix . 'aieo_dmm_branch_scan_log';
        if (!aieo_dmm_table_exists($table)) {
            return;
        }
        $user = wp_get_current_user();
        $wpdb->insert($table, array(
            'barcode'    => (string) $barcode,
            'status'     => (string) $status,
            'branch_id'  => $branch_id > 0 ? $branch_id : null,
            'user_id'    => $user && $user->ID ? (int) $user->ID : null,
            'user_login' => $user && $user->ID ? (string) $user->user_login : null,
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? substr(sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])), 0, 255) : null,
        ), array('%s', '%s', '%d', '%d', '%s', '%s'));
    }

    private function enqueue_scanner_assets() {
        wp_enqueue_script(
            'aieo-dmm-scanner',
            AIEO_URI . 'assets/js/dmm-scanner.js',
            array('jquery'),
            AIEO_VERSION,
            true
        );
        wp_localize_script('aieo-dmm-scanner', 'aieoDmmScanner', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'i18n' => array(
                'cameraUnavailable' => __('Camera or BarcodeDetector unavailable in this browser.', 'ai-eshop-optimizer'),
                'scanning' => __('Scanning…', 'ai-eshop-optimizer'),
                'notFound' => __('Product not found.', 'ai-eshop-optimizer'),
                'addToCart' => __('Add to cart', 'ai-eshop-optimizer'),
                'viewProduct' => __('View product', 'ai-eshop-optimizer'),
            ),
        ));
    }
}
