<?php
/*
 * Plugin Name: Devs Accounting
 * Description: A simple wordpress plugin to manage store, checkout, sales, stocks inventory, income, expense, invoice, bills, customers, reports.
 * Version: 1.2.0
 * Author: DevsBrain
 * Author URI: https://devsbrain.com
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: devs-accounting
 *
 * @package devs-accounting
 */

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

/**
 * Define Plugins Contents
 */

define('DEVSACCOUNTING_PATH', trailingslashit(plugin_dir_path(__FILE__)));
define('DEVSACCOUNTING_URL', trailingslashit(plugins_url('/', __FILE__)));
define('DEVSACCOUNTING_PLUGIN_FOLDER_NAME', basename(dirname(__FILE__)));

class DevsAccounting
{
    function __construct()
    {
        add_action('init', array($this, 'devsaccounting_includes'));
        add_action('admin_menu', [$this, 'devsaccounting_create_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'devsaccounting_load_scripts']);
        add_action('enqueue_block_editor_assets', [$this, 'devsaccounting_block_assets']);
        register_activation_hook(__FILE__, array($this, 'devsaccounting_plugin_activate'));
        add_action('template_redirect', array($this, 'custom_template_redirect'));
        add_filter('the_content', [$this, 'checkShortcodesAndEnqueueScript']);
        add_action('init', array($this, 'register_items_post_type'));
        add_filter('single_template', array($this, 'load_custom_template'));
        // new
        add_filter('manage_dac_items_posts_columns', [$this, 'items_columns']);
        add_action('manage_dac_items_posts_custom_column', [$this, 'items_column_content'], 10, 2);
        add_filter('manage_edit-dac_items_sortable_columns', [$this, 'items_sortable_columns']);

        add_action('add_meta_boxes', [$this, 'register_item_metabox']);
        add_action('save_post_dac_items', [$this, 'save_item_meta']);
        add_action('save_post', [$this, 'handle_post_update'], 20, 3);

        add_action('add_meta_boxes', [$this, 'devs_accounting_wc_add_meta_boxes']);
        add_action('wp_ajax_generate_dac_wcpdf', [$this, 'handle_generate_invoice_ajax']);
        add_action('wp_ajax_nopriv_generate_dac_wcpdf', [$this, 'handle_generate_invoice_ajax']);
    }


        public function devs_accounting_wc_add_meta_boxes()
    {
        if (!class_exists('WooCommerce')) return;

        $screens = ['shop_order', 'woocommerce_page_wc-orders'];
        foreach ($screens as $screen) {
            add_meta_box(
                'devs_accounting_wc_invoice',
                __('Accounting Invoice', 'devs-accounting'),
                [$this, 'render_wc_invoice_metabox'],
                $screen,
                'side',
                'high'
            );
        }
    }

    public function render_wc_invoice_metabox($post)
    {
        $order_id = ($post instanceof WP_Post) ? $post->ID : (method_exists($post, 'get_id') ? $post->get_id() : 0);
        if (!$order_id) return;

        $nonce = wp_create_nonce('dac_generate_pdf');
        $url_invoice = admin_url('admin-ajax.php?action=generate_dac_wcpdf&document_type=invoice&order_ids=' . $order_id . '&nonce=' . $nonce);
        $url_packing = admin_url('admin-ajax.php?action=generate_dac_wcpdf&document_type=packing_slip&order_ids=' . $order_id . '&nonce=' . $nonce);
    ?>
        <div class="devs-accounting-wc-meta-box" style="text-align: center; padding: 10px 0;">
            <p style="margin-bottom: 12px; color: #666; font-size: 13px;">
                <?php esc_html_e('Create a professional PDF invoice using the Devs Accounting.', 'devs-accounting'); ?>
            </p>
            <a href="<?php echo esc_url($url_invoice); ?>" class="button button-primary button-large" target="_blank" style="width: 100%; justify-content: center; display: flex; align-items: center; gap: 5px; margin-bottom: 8px;">
                <span class="dashicons dashicons-pdf" style="margin-top: 4px;"></span>
                <?php esc_html_e('PDF Invoice', 'devs-accounting'); ?>
            </a>
            <a href="<?php echo esc_url($url_packing); ?>" class="button button-secondary button-large" target="_blank" style="width: 100%; justify-content: center; display: flex; align-items: center; gap: 5px;">
                <span class="dashicons dashicons-media-text" style="margin-top: 4px;"></span>
                <?php esc_html_e('Packing Slip', 'devs-accounting'); ?>
            </a>
        </div>
    <?php
    }

    /**
     * Handle the generation redirect via AJAX URL (WPO style)
     */
    public function handle_generate_invoice_ajax()
    {
        $order_ids = isset($_GET['order_ids']) ? sanitize_text_field($_GET['order_ids']) : '';

        if (!$order_ids) wp_die('Missing Order IDs');
        
        $ids = explode(',', $order_ids);
        $order_id = intval($ids[0]);

        if (!wp_verify_nonce( $_REQUEST['nonce'] ?? '', 'dac_generate_pdf' )) {
            wp_die('Invalid or missing security token');
        }

        $wc_obj = new DevsAccounting_Wc();
        $order = $wc_obj->get_wc_order($order_id);
        
        if (!$order) wp_die('Order not found');

        $settings_raw = get_option('devsaccounting_settings');
        $settings = json_decode($settings_raw, true);

        $autoload = plugin_dir_path(__FILE__) . 'vendor/autoload.php';
        if (!file_exists($autoload)) {
            wp_die('Dompdf autoloader not found. Please run composer install.');
        }
        require_once $autoload;

        try {
            $options = new \Dompdf\Options();
            $options->set('isHtml5ParserEnabled', true);
            $options->set('isRemoteEnabled', true);
            $options->set('defaultFont', 'DejaVu Sans');
            
            $dompdf = new \Dompdf\Dompdf($options);
            
            ob_start();
            $document_type = isset($_GET['document_type']) ? sanitize_text_field($_GET['document_type']) : 'invoice';
            $template_file = ($document_type === 'packing_slip') ? 'packing-slip-template.php' : 'invoice-template-1.php';
            $template_path = plugin_dir_path(__FILE__) . 'templates/' . $template_file;

            if (!file_exists($template_path)) {
                if (ob_get_level()) ob_end_clean();
                wp_die('Template file not found: ' . esc_html($template_file));
            }
            
            include $template_path;
            $html = ob_get_clean();
            
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('a4', 'portrait');
            $dompdf->render();
            
            $prefix = ($document_type === 'packing_slip') ? 'PackingSlip_' : 'Invoice_';
            $filename = $prefix . ($order['order_no'] ?? $order['id']) . '.pdf';
            
            if (ob_get_level()) ob_end_clean();
            
            $dompdf->stream($filename, ['Attachment' => 0]);
            exit;
        } catch (\Exception $e) {
            if (ob_get_level()) ob_end_clean();
            wp_die('PDF Generation Error: ' . esc_html($e->getMessage()));
        }

        wp_die('Template not found');
    }

    public function register_item_metabox()
    {
        add_meta_box(
            'item_details_metabox',
            __('Item Details', 'devs-accounting'),
            [$this, 'render_item_metabox'],
            'dac_items',
            'side',
            'default'
        );
    }


    public function render_item_metabox($post)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $item = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE post_id = %d",
            $post->ID
        ));

        $sku = $item ? $item->sku : '';
        $sale_price = $item ? $item->sale_price : '';
        $stock_limit = $item ? $item->stock_limit : 1;
        $category = $item ? $item->category_id : '';
        $purchase_price = $item ? $item->purchase_price : '';
        $exp_date = $item && $item->exp_date
            ? date('Y-m-d', strtotime($item->exp_date))
            : '';

        $enabled = $item ? $item->enabled : 1;

        $categories = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}dac_categories WHERE deleted_at IS NULL ORDER BY name ASC");

        wp_nonce_field('save_item_meta', 'item_meta_nonce');
        ?>

        <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
            <label>
                <Strong>Status: </Strong>
            </label>
            <label class="switch">
                <input type="hidden" name="item_enabled" value="0">
                <input type="checkbox" name="item_enabled" value="1" <?php checked($enabled, 1); ?>>
                <span class="slider"></span>
            </label>

        </div>

        <p>
            <label><strong>SKU:</strong></label>
            <input type="text" name="item_sku" value="<?php echo esc_attr($sku); ?>" class="widefat">
        </p>
        <div style="display: flex; justify-content: space-between; gap: 10px;">
            <p>
                <label><strong>Purchase Price:</strong></label>
                <input type="number" name="item_purchase_price" value="<?php echo esc_attr($purchase_price); ?>" class="widefat"
                    step="0.01">
            </p>
            <p>
                <label><strong>Sale Price:</strong></label>
                <input type="number" name="item_sale_price" value="<?php echo esc_attr($sale_price); ?>" class="widefat"
                    step="0.01">
            </p>
        </div>
        <p>
            <label><strong>Category:</strong></label>
            <select name="item_category" class="widefat" style="width: 85%">
                <option value="">Select Category</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo esc_attr($cat->id); ?>" <?php selected((int) $category, (int) $cat->id); ?>>
                        <?php echo esc_html($cat->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </p>
        <div style="display: flex; justify-content: space-between; gap: 10px;">
            <p style="flex:1">
                <label><strong>Stock:</strong></label>
                <input type="number" name="item_stock_limit" value="<?php echo esc_attr(max(1, intval($stock_limit))); ?>"
                    class="widefat" min="1" step="1">
            </p>
            <p style="flex:1">
                <label><strong>Expiry Date:</strong></label>
                <input type="date" name="item_exp_date" value="<?php echo esc_attr($exp_date); ?>" class="widefat">
            </p>
        </div>

        <?php
        $selected_taxes = [];

        if ($item) {
            $selected_taxes = array_map('intval', $wpdb->get_col(
                $wpdb->prepare(
                    "SELECT tax_id FROM {$wpdb->prefix}dac_item_tax WHERE item_id = %d",
                    $item->id
                )
            ));

        }
        $taxes = $wpdb->get_results(
            "SELECT id, tax_name FROM {$wpdb->prefix}dac_taxes ORDER BY tax_name ASC"
        );
        ?>

        <p>
    <label><strong>Tax:</strong></label>
        <?php foreach ($taxes as $tax): ?>
            <label style="display:block; margin-bottom:4px;">
                <input type="checkbox"
                       name="item_tax[]"
                       value="<?php echo esc_attr($tax->id); ?>"
                    <?php checked(in_array((int) $tax->id, $selected_taxes, true)); ?>
                >
                <?php echo esc_html($tax->tax_name); ?>
            </label>
        <?php endforeach; ?>
   
</p>


        <?php
        $existing_meta = [];
        if ($item && !empty($item->meta)) {
            $decoded = json_decode($item->meta, true);
            if (is_array($decoded)) {
                $existing_meta = $decoded;
            }
        }
        ?>

        <p><strong>Meta:</strong></p>
        <div id="item-meta-wrapper">
            <?php if (!empty($existing_meta)): ?>
                <?php foreach ($existing_meta as $meta): ?>
                    <div class="item-meta-row" style="display:flex; gap:8px; margin-bottom:6px; align-items:center;">
                        <input type="text" name="item_meta_name[]" value="<?php echo esc_attr($meta['meta_name']); ?>"
                            placeholder="Meta Name" class="widefat">
                        <input type="text" name="item_meta_value[]" value="<?php echo esc_attr($meta['meta_value']); ?>"
                            placeholder="Meta Value" class="widefat">
                        <button type="button" class="button remove-meta" onclick="removeItemMetaRow(this)">X</button>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="item-meta-row" style="display:flex; gap:8px; margin-bottom:6px; align-items:center;">
                    <input type="text" name="item_meta_name[]" placeholder="Meta Name" class="widefat">
                    <input type="text" name="item_meta_value[]" placeholder="Meta Value" class="widefat">
                    <button type="button" class="button remove-meta" onclick="removeItemMetaRow(this)">X</button>
                </div>
            <?php endif; ?>
        </div>

        <button type="button" class="button" onclick="addItemMetaRow()">+ Add Meta</button>

        <script>
            function addItemMetaRow() {
                const wrapper = document.getElementById('item-meta-wrapper');
                const div = document.createElement('div');
                div.className = 'item-meta-row';
                div.style.display = 'flex';
                div.style.gap = '8px';
                div.style.marginBottom = '6px';
                div.style.alignItems = 'center';

                div.innerHTML = `
        <input type="text" name="item_meta_name[]" placeholder="Meta Name" class="widefat">
        <input type="text" name="item_meta_value[]" placeholder="Meta Value" class="widefat">
        <button type="button" class="button remove-meta" onclick="removeItemMetaRow(this)">X</button>
    `;
                wrapper.appendChild(div);
            }

            function removeItemMetaRow(button) {
                const row = button.parentNode;
                row.parentNode.removeChild(row);
            }
        </script>




        <?php
    }

    public function save_item_meta($post_id)
    {
        if (!isset($_POST['item_meta_nonce']) || !wp_verify_nonce($_POST['item_meta_nonce'], 'save_item_meta'))
            return;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return;
        if (wp_is_post_revision($post_id))
            return;
        if (!current_user_can('edit_post', $post_id))
            return;

        $sku = isset($_POST['item_sku']) ? sanitize_text_field($_POST['item_sku']) : '';
        $sale_price = isset($_POST['item_sale_price']) ? floatval($_POST['item_sale_price']) : 0;
        $purchase_price = isset($_POST['item_purchase_price']) ? floatval($_POST['item_purchase_price']) : 0;
        $stock_limit = isset($_POST['item_stock_limit']) ? max(1, intval($_POST['item_stock_limit'])) : 1;
        $category_id = isset($_POST['item_category']) ? intval($_POST['item_category']) : 0;
        $exp_date = isset($_POST['item_exp_date']) ? sanitize_text_field($_POST['item_exp_date']) : '';
        $enabled = isset($_POST['item_enabled']) ? intval($_POST['item_enabled']) : 1;

        $name = get_the_title($post_id);
        $description = wp_strip_all_tags(get_post_field('post_content', $post_id));

        $thumbnail_id = get_post_thumbnail_id($post_id);
        $image = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : '';

        $data = [
            'post_id' => $post_id,
            'name' => $name,
            'description' => $description,
            'image' => $image,
            'sku' => $sku,
            'sale_price' => $sale_price,
            'purchase_price' => $purchase_price,
            'stock_limit' => $stock_limit,
            'category_id' => $category_id,
            'exp_date' => $exp_date,
            'enabled' => $enabled,
        ];

        $meta_data = [];

        if (!empty($_POST['item_meta_name']) && !empty($_POST['item_meta_value'])) {

            $names = (array) $_POST['item_meta_name'];
            $values = (array) $_POST['item_meta_value'];

            foreach ($names as $index => $name) {

                $name = sanitize_text_field($name);
                $value = sanitize_text_field($values[$index] ?? '');

                if ($name !== '' && $value !== '') {
                    $meta_data[] = [
                        'meta_name' => $name,
                        'meta_value' => $value,
                    ];
                }
            }
        }

        $data['meta'] = !empty($meta_data) ? wp_json_encode($meta_data) : null;


        $this->save_to_dac_items_only($post_id, $data);
        $tax_id = isset($_POST['item_tax']) ? intval($_POST['item_tax']) : 0;

        $tax_ids = [];

        if (!empty($_POST['item_tax']) && is_array($_POST['item_tax'])) {
            $tax_ids = array_map('intval', $_POST['item_tax']);
        }

        $this->save_item_taxes($post_id, $tax_ids);



    }

    private function save_item_taxes($post_id, $tax_ids)
    {
        global $wpdb;

        $item_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}dac_items WHERE post_id = %d",
                $post_id
            )
        );

        if (!$item_id)
            return;

        $table = $wpdb->prefix . 'dac_item_tax';

        $wpdb->delete($table, ['item_id' => $item_id]);

        foreach ($tax_ids as $tax_id) {
            $wpdb->insert($table, [
                'item_id' => $item_id,
                'tax_id' => $tax_id,
            ], ['%d', '%d']);
        }
    }


    public function save_to_dac_items_only($post_id, $data)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_name WHERE post_id = %d",
            $post_id
        ));

        if ($exists) {
            $result = $wpdb->update($table_name, $data, ['post_id' => $post_id]);
            error_log("DEBUG: Updated dac_items for post_id: $post_id");
        } else {
            $result = $wpdb->insert($table_name, $data);
            error_log("DEBUG: Inserted into dac_items for post_id: $post_id, ID: " . $wpdb->insert_id);
        }

        if ($wpdb->last_error) {
            error_log("DEBUG: Database error: " . $wpdb->last_error);
        }
    }

    public function sync_featured_image($meta_id, $post_id, $meta_key, $meta_value)
    {
        if ($meta_key !== '_thumbnail_id')
            return;

        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'dac_items')
            return;

        $image = '';
        if ($meta_value && is_numeric($meta_value)) {
            $attachment_url = wp_get_attachment_url($meta_value);
            if ($attachment_url) {
                $image = $attachment_url;
            }
        }

        update_post_meta($post_id, 'image', $image);

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table_name WHERE post_id = %d", $post_id));

        if ($exists) {
            $wpdb->update(
                $table_name,
                ['image' => $image],
                ['post_id' => $post_id]
            );
        } else {
            $wpdb->insert(
                $table_name,
                [
                    'post_id' => $post_id,
                    'name' => get_the_title($post_id),
                    'description' => wp_strip_all_tags(get_post_field('post_content', $post_id)),
                    'image' => $image,
                    'sku' => '',
                    'sale_price' => 0,
                    'purchase_price' => 0,
                    'stock_limit' => 1,
                    'category_id' => 0,
                    'enabled' => 1
                ]
            );
        }
    }

    public function sync_featured_image_delete($meta_ids, $post_id, $meta_key, $meta_value)
    {
        if ($meta_key !== '_thumbnail_id')
            return;

        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'dac_items')
            return;

        delete_post_meta($post_id, 'image');

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $wpdb->update(
            $table_name,
            ['image' => ''],
            ['post_id' => $post_id]
        );
    }

    public function custom_template_redirect()
    {
        $pieces = explode("/", $GLOBALS['wp']->request ?? '');
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);

        if (!is_array($settings)) return;

        $enqueue_assets = function () {
            wp_enqueue_script(
                'devs-accounting-front-js',
                DEVSACCOUNTING_URL . 'build/frontend.js',
                ['wp-element'],
                null,
                true
            );

            wp_enqueue_style(
                'devs-accounting-front-style',
                DEVSACCOUNTING_URL . 'build/index.css'
            );

            wp_localize_script('devs-accounting-front-js', 'devsAccountingApi', [
                'apiUrl' => home_url('/wp-json'),
                'nonce' => wp_create_nonce('wp_rest'),

            ]);
        };


        // Invoice Page
        if (!empty($settings['invoice_page']) && $pieces[0] === $settings['invoice_page']) {
            $enqueue_assets();
            get_header();
            echo do_shortcode('[devsaccounting_invoice]');
            get_footer();
            exit;
        }

        // Register Page (no frontend.js, only CSS)
        if (!empty($settings['register_page']) && $pieces[0] === $settings['register_page']) {
            get_header();
            echo "<link rel='stylesheet' href='" . esc_url(DEVSACCOUNTING_URL . "/build/index.css") . "' media='all' />";
            echo do_shortcode('[devsaccounting_register]');
            get_footer();
            exit;
        }

        // Login Page (no frontend.js, only CSS)
        if (!empty($settings['login_page']) && $pieces[0] === $settings['login_page']) {
            get_header();
            echo "<link rel='stylesheet' href='" . esc_url(DEVSACCOUNTING_URL . '/build/index.css') . "' media='all' />";
            echo do_shortcode('[devsaccounting_login]');
            get_footer();
            exit;
        }

        // Purchase Page
        if (!empty($settings['purchase_page']) && $pieces[0] === $settings['purchase_page']) {
            $enqueue_assets();
            get_header();
            echo do_shortcode('[devsaccounting_purchase]');
            get_footer();
            exit;
        }

        // Profile Page
        if (!empty($settings['profile_page']) && $pieces[0] === $settings['profile_page']) {
            $enqueue_assets();
            get_header();
            echo do_shortcode('[devsaccounting_profile]');
            get_footer();
            exit;
        }
        if (!empty($settings['all_items_page']) && $pieces[0] === $settings['all_items_page']) {
            $enqueue_assets();
            get_header();
            echo do_shortcode('[devsaccounting_allItems]');
            get_footer();
            exit;
        }
    }

    public function register_items_post_type()
    {
        $labels = array(
            'name' => _x('Items', 'Post type general name', 'devs-accounting'),
            'singular_name' => _x('Item', 'Post type singular name', 'devs-accounting'),
            'menu_name' => _x('Items', 'Admin Menu text', 'devs-accounting'),
            'name_admin_bar' => _x('Item', 'Add New on Toolbar', 'devs-accounting'),
            'add_new' => __('Add New', 'devs-accounting'),
            'add_new_item' => __('Add New Item', 'devs-accounting'),
            'new_item' => __('New Item', 'devs-accounting'),
            'edit_item' => __('Edit Item', 'devs-accounting'),
            'view_item' => __('View Item', 'devs-accounting'),
            'all_items' => __('All Items', 'devs-accounting'),
            'search_items' => __('Search Items', 'devs-accounting'),
            'parent_item_colon' => __('Parent Items:', 'devs-accounting'),
            'not_found' => __('No items found.', 'devs-accounting'),
            'not_found_in_trash' => __('No items found in Trash.', 'devs-accounting'),
            'featured_image' => _x('Item Image', 'Overrides the "Featured Image" phrase', 'devs-accounting'),
            'set_featured_image' => _x('Set item image', 'Overrides the "Set featured image" phrase', 'devs-accounting'),
            'remove_featured_image' => _x('Remove item image', 'Overrides the "Remove featured image" phrase', 'devs-accounting'),
            'use_featured_image' => _x('Use as item image', 'Overrides the "Use as featured image" phrase', 'devs-accounting'),
            'archives' => _x('Item archives', 'The post type archive label', 'devs-accounting'),
            'insert_into_item' => _x('Insert into item', 'Overrides the "Insert into post" phrase', 'devs-accounting'),
            'uploaded_to_this_item' => _x('Uploaded to this item', 'Overrides the "Uploaded to this post" phrase', 'devs-accounting'),
            'filter_items_list' => _x('Filter items list', 'Screen reader text', 'devs-accounting'),
            'items_list_navigation' => _x('Items list navigation', 'Screen reader text', 'devs-accounting'),
            'items_list' => _x('Items list', 'Screen reader text', 'devs-accounting'),
        );

        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => false,
            'query_var' => true,
            'rewrite' => array('slug' => 'dac_items'),
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'menu_icon' => 'dashicons-cart',
            'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
            'show_in_rest' => true,
        );

        register_post_type('dac_items', $args);
    }

    public function load_custom_template($template)
    {
        if (is_singular('dac_items')) {
            $custom = DEVSACCOUNTING_PATH . 'templates/single-items.php';

            if (file_exists($custom)) {
                return $custom;
            }
        }
        return $template;
    }


    function devsaccounting_plugin_activate()
    {
        add_role(
            'devaccount_viewer',
            'DevAccounting Viewer',
            array(
                'devaccount_viewer' => true,
                'read' => true,
            )
        );
        include DEVSACCOUNTING_PATH . 'migrations/devs-accounting-migration.php';
    }

    function devsaccounting_load_scripts($hook)
    {
    
        $plugin_data = get_file_data(
        __FILE__,
        array('Version' => 'Version'),
        'plugin'
        );

        $asset_version = $plugin_data['Version'] ?? false;
            
    
        if (isset($_GET['page']) && strpos($_GET['page'], 'devs-accounting') === 0) {
            wp_enqueue_script(
                'devs-accounting-admin-js',
                plugin_dir_url(__FILE__) . 'build/admin.js',
                ['wp-element'],
                $asset_version,
                true
            );
            wp_localize_script('devs-accounting-admin-js', 'devsAccountingApi', [
                'apiUrl' => home_url('/wp-json'),
                'nonce' => wp_create_nonce('wp_rest'),
                'locale' => get_locale(),
                'isWooCommerceActive' => class_exists('WooCommerce'),
            ]);

            wp_enqueue_script(
                'devs-accounting-feedback-js',
                plugin_dir_url(__FILE__) . 'build/feedback.js',
                ['wp-element'],
                $asset_version,
                true
            );

            wp_enqueue_style(
                'devs-accounting-style',
                plugin_dir_url(__FILE__) . 'build/index.css'
            );
        }

        wp_localize_script('devs-accounting-feedback-js', 'devsAccountingDeactivation', [
            'pluginSlug' => 'devs-accounting-pro',
        ]);
    }

    public function checkShortcodesAndEnqueueScript($content)
    {
        $plugin_data = get_file_data(
        __FILE__,
        array('Version' => 'Version'),
        'plugin'
        );

        $asset_version = $plugin_data['Version'] ?? false;
        
        $shortcodes = [
            'devsaccounting_invoice',
            'devsaccounting_purchase',
            'devsaccounting_login',
            'devsaccounting_register',
            'devsaccounting_profile',
            'devsaccounting_allItems',
        ];

        foreach ($shortcodes as $shortcode) {
            if (has_shortcode($content, $shortcode)) {
                wp_enqueue_script(
                    'devs-accounting-front-js',
                    DEVSACCOUNTING_URL . 'build/frontend.js',
                    ['wp-element'],
                    $asset_version,
                    true
                );
                wp_enqueue_style(
                    'devs-accounting-front-style',
                    DEVSACCOUNTING_URL . 'build/index.css'
                );

                wp_localize_script('devs-accounting-front-js', 'devsAccountingApi', [
                    'apiUrl' => home_url('/wp-json'),
                    'nonce' => wp_create_nonce('wp_rest'),
                ]);
                break;
            }
        }

        return $content;
    }

    public function devsaccounting_includes()
    {
        $current_user = wp_get_current_user();
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-items.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-contact.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-invoice.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-setting.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-accounts.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-transactions.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-categories.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-taxes.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-transfer.php';
        require DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-order-status.php';

        if (file_exists(DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-purchases.php')) {
            include DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-purchases.php';
        }
        if (file_exists(DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-wc.php')) {
            include DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-wc.php';
        }
        if (file_exists(DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-user.php')) {
            include DEVSACCOUNTING_PATH . 'classes/class-devs-accounting-user.php';
        }
        if (file_exists(DEVSACCOUNTING_PATH . 'inc/devs-accounting-pro-shortcode.php')) {
            include DEVSACCOUNTING_PATH . 'inc/devs-accounting-pro-shortcode.php';
        }
        if (file_exists(DEVSACCOUNTING_PATH . 'inc/devs-accounting-auth.php')) {
            include DEVSACCOUNTING_PATH . 'inc/devs-accounting-auth.php';
        }

        include DEVSACCOUNTING_PATH . 'inc/devs-accounting-shortcode.php';
        include DEVSACCOUNTING_PATH . 'inc/devs-accounting-helper.php';

        include DEVSACCOUNTING_PATH . 'inc/devs-accounting-image-modal.php';
    }

    public function items_columns($columns)
    {
        $columns['image'] = __('Image', 'devs-accounting');
        $columns['sku'] = __('SKU', 'devs-accounting');
        $columns['sale_price'] = __('Sale Price', 'devs-accounting');
        $columns['stock_limit'] = __('Stock', 'devs-accounting');
        $columns['category_id'] = __('Category', 'devs-accounting');
        $columns['enabled'] = __('Enabled', 'devs-accounting');

        return $columns;
    }

    public function items_column_content($column, $post_id)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        // Get item data from dac_items table ONLY
        $item = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE post_id = %d",
            $post_id
        ));

        if (!$item) {
            // No data in dac_items yet
            switch ($column) {
                case 'image':
                    echo '<span style="color: #999; font-size: 12px;">No image</span>';
                    break;
                default:
                    echo '—';
            }
            return;
        }

        switch ($column) {
            case 'image':
                if (!empty($item->image)) {
                    echo "<img src='" . esc_url($item->image) . "' width='50' height='50' style='object-fit: cover; border-radius: 4px;' />";
                } else {
                    echo '<span style="color: #999; font-size: 12px;">No image</span>';
                }
                break;

            case 'sku':
                echo esc_html($item->sku ?: '—');
                break;

            case 'sale_price':
                echo $item->sale_price ? '$' . esc_html(number_format($item->sale_price, 2)) : '—';
                break;

            case 'stock_limit':
                echo esc_html($item->stock_limit ?: '—');
                break;

            case 'category_id':
                if ($item->category_id) {
                    $category = $wpdb->get_var($wpdb->prepare(
                        "SELECT name FROM {$wpdb->prefix}dac_categories WHERE id = %d",
                        $item->category_id
                    ));
                    echo esc_html($category ?: 'N/A');
                } else {
                    echo '—';
                }
                break;

            case 'enabled':
                echo $item->enabled ? '<span style="color: green;">✓</span>' : '<span style="color: red;">✗</span>';
                break;
        }
    }

    public function items_sortable_columns($columns)
    {
        $columns['sku'] = 'sku';
        $columns['sale_price'] = 'sale_price';
        return $columns;
    }

    public function devsaccounting_create_admin_menu()
    {
        $capability = 'manage_options';
        $slug = 'devs-accounting';

        if (current_user_can('devaccount_viewer')) {
            $capability = 'devaccount_viewer';
        }

        add_menu_page(
            'Devs Accounting',
            'Devs Accounting',
            $capability,
            'devs-accounting',
            [$this, 'devsaccounting_menu_page_template'],
            'dashicons-calculator'
        );

        add_submenu_page(
            'devs-accounting',
            'Tools',
            'Tools',
            $capability,
            'devs-accounting-tools',
            [$this, 'devsaccounting_menu_page_template']
        );

        add_submenu_page(
            'devs-accounting',
            'Settings',
            'Settings',
            $capability,
            'devs-accounting-settings',
            [$this, 'devsaccounting_menu_page_template']
        );

        add_submenu_page(
            'devs-accounting',
            'Items',
            'Items',
            $capability,
            'edit.php?post_type=dac_items'
        );

        add_submenu_page(
            'woocommerce',
            'Order Status',
            'Order Status',
            'manage_options',
            'devs-accounting-order-status',
            [$this, 'devsaccounting_menu_page_template']
        );
    }

    function devsaccounting_block_assets()
    {
        wp_enqueue_script(
            'devsaccounting-block',
            plugin_dir_url(__FILE__) . 'build/ItemsBlock.js',
            array('wp-blocks', 'wp-editor', 'wp-components'),
            filemtime(plugin_dir_path(__FILE__) . 'build/ItemsBlock.js'),
            true
        );

        wp_enqueue_style(
            'devsaccounting-block-editor-styles',
            plugin_dir_url(__FILE__) . 'build/index.css',
            array('wp-edit-blocks'),
            filemtime(plugin_dir_path(__FILE__) . 'build/index.css')
        );
    }

    public function devsaccounting_menu_page_template()
    {
        $current_page = $_GET['page'] ?? 'devs-accounting';
        echo '<div class="devs-accounting-wrapper">';
        echo '<div id="devsaccounting_admin" data-page="' . esc_attr($current_page) . '"></div>';
        echo '</div>';
    }


    public function sync_item_meta_changes($meta_id, $post_id, $meta_key, $meta_value)
    {
        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'dac_items')
            return;

        $sync_keys = [
            'sku',
            'sale_price',
            'purchase_price',
            'stock_limit',
            'category_id',
            'exp_date',
            'enabled'
        ];

        if ($meta_key !== 'force_sync' && !in_array($meta_key, $sync_keys)) {
            return;
        }

        wp_cache_delete($post_id, 'post_meta');

        $name = get_the_title($post_id);
        $description = wp_strip_all_tags(get_post_field('post_content', $post_id));

        $thumbnail_id = get_post_thumbnail_id($post_id);
        $image = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : '';

        $data = [
            'post_id' => $post_id,
            'name' => $name,
            'description' => $description,
            'image' => $image,
            'sku' => get_post_meta($post_id, 'sku', true),
            'sale_price' => floatval(get_post_meta($post_id, 'sale_price', true) ?: 0),
            'purchase_price' => floatval(get_post_meta($post_id, 'purchase_price', true) ?: 0),
            'stock_limit' => intval(get_post_meta($post_id, 'stock_limit', true) ?: 1),
            'category_id' => intval(get_post_meta($post_id, 'category_id', true) ?: 0),
            'exp_date' => get_post_meta($post_id, 'exp_date', true),
            'enabled' => intval(get_post_meta($post_id, 'enabled', true) ?: 1),
        ];

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_name WHERE post_id = %d",
            $post_id
        ));


        if ($exists) {
            $result = $wpdb->update($table_name, $data, ['post_id' => $post_id]);
        } else {
            $result = $wpdb->insert($table_name, $data);
        }

        if ($wpdb->last_error) {
            error_log("DEBUG: Database error: " . $wpdb->last_error);
        }
    }


    public function sync_item_meta_deletions($meta_ids, $post_id, $meta_key, $meta_value)
    {
        $post = get_post($post_id);
        if (!$post || $post->post_type !== 'dac_items')
            return;

        $sync_keys = [
            'sku',
            'sale_price',
            'purchase_price',
            'stock_limit',
            'category_id',
            'exp_date',
            'enabled'
        ];

        if (!in_array($meta_key, $sync_keys))
            return;

        $this->sync_item_meta_changes(0, $post_id, $meta_key, '');
    }

    public function handle_post_update($post_id, $post, $update)
    {
        if ($post->post_type !== 'dac_items')
            return;

        if (!$update)
            return;

        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';

        $thumbnail_id = get_post_thumbnail_id($post_id);
        $image = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : '';

        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_name WHERE post_id = %d",
            $post_id
        ));

        if ($exists) {
            $wpdb->update(
                $table_name,
                ['image' => $image, 'name' => $post->post_title],
                ['post_id' => $post_id]
            );
        } else {
            $wpdb->insert(
                $table_name,
                [
                    'post_id' => $post_id,
                    'name' => $post->post_title,
                    'description' => wp_strip_all_tags($post->post_content),
                    'image' => $image,
                    'sku' => '',
                    'sale_price' => 0,
                    'purchase_price' => 0,
                    'stock_limit' => 1,
                    'category_id' => 0,
                    'enabled' => 1
                ]
            );
        }
    }

}

$dev_account = new DevsAccounting();