<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class DevsAccounting_Item
{
    private $user;

    public function __construct($user)
    {
        $this->user = $user;
        add_action('rest_api_init', [$this, 'item_api_endpoint']);
    }


    public function item_api_endpoint()
    {
        register_rest_route('devs-accounting/v1', '/add-item', array(
            'methods' => 'POST',
            'callback' => [$this, 'save_item_data'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/items', array(
            'methods' => 'GET',
            'callback' => [$this, 'get_items'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/inventories', array(
            'methods' => 'GET',
            'callback' => [$this, 'get_inventories'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/update-item-inventory', array(
            'methods' => 'POST',
            'callback' => [$this, 'update_item_inventory'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ));

        register_rest_route('devs-accounting/v1', '/show-item/(?P<id>\d+)', array(
            'methods' => 'GET',
            'callback' => [$this, 'get_single_item'],
            'permission_callback' => function () {
                return true;
            },
        ));

        register_rest_route('devs-accounting/v1', '/delete-item/(?P<id>\d+)', array(
            'methods' => 'GET',
            'callback' => [$this, 'delete_single_item'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ));
        register_rest_route('devs-accounting/v1', '/export-items', array(
            'methods' => 'GET',
            'callback' => [$this, 'export_items'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ));
        register_rest_route('devs-accounting/v1', '/import-items', [
            'methods' => 'POST',
            'callback' => [$this, 'import_items'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ]);

        register_rest_route('devs-accounting/v1', '/sample-items', [
            'methods' => 'GET',
            'callback' => [$this, 'sample_items_download'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ]);
        register_rest_route('devs-accounting/v1', '/toggle-item/(?P<id>\d+)', array(
            'methods' => 'POST',
            'callback' => [$this, 'toggle_item_enabled'],
            'permission_callback' => [$this, 'verify_items_nonce'],
        ));
    }

    public function verify_items_nonce($request)
    {
        $nonce = $request->get_header('X-WP-Nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('rest_forbidden', esc_html__('Invalid nonce.', 'devs-accounting'), array('status' => 403));
        }
        return true;
    }

	public function get_items($request)
    {
        global $wpdb;

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

        $page = max(1, intval($request['page'] ?? 1));
        $per_page = max(1, intval($request['per_page'] ?? 10));
        $offset = ($page - 1) * $per_page;

        $search = sanitize_text_field($request['search'] ?? '');
        $search_condition = '';
        $search_param = [];

        if (!empty($search)) {
            $search_condition = "AND (di.name LIKE %s OR di.description LIKE %s)";
            $search_param = ['%' . $wpdb->esc_like($search) . '%', '%' . $wpdb->esc_like($search) . '%'];
        }

        // Fetch dac_items
        $items = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table_name di WHERE di.deleted_at IS NULL $search_condition ORDER BY di.id DESC LIMIT %d OFFSET %d",
                array_merge($search_param, [$per_page, $offset])
            )
        );

        // Override with postmeta if posts exist
        foreach ($items as &$item) {
            $post_id = $wpdb->get_var($wpdb->prepare(
                "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='item_id' AND meta_value=%d",
                $item->id
            ));

            if ($post_id) {
                $item->name = get_post_field('post_title', $post_id) ?: $item->name;

                // Clean description from Gutenberg blocks
                $description = get_post_field('post_content', $post_id) ?: $item->description;
                $description = preg_replace('/<!-- wp:.*?-->/', '', $description);
                $description = preg_replace('/<!-- \/wp:.*?-->/', '', $description);
                $description = preg_replace('/<p>\s*<\/p>/', '', $description);
                $item->description = trim($description);

                $item->image = has_post_thumbnail($post_id) ? get_the_post_thumbnail_url($post_id) : null;

                $item->sku           = get_post_meta($post_id, 'sku', true) ?: $item->sku;
                $item->sale_price    = get_post_meta($post_id, 'sale_price', true) ?: $item->sale_price;
                $item->stock_limit   = get_post_meta($post_id, 'stock_limit', true) ?: $item->stock_limit;
                $item->category_name = get_post_meta($post_id, 'category_name', true) ?: $item->category_name;
                $item->purchase_price= get_post_meta($post_id, 'purchase_price', true) ?: $item->purchase_price;
                $item->exp_date      = get_post_meta($post_id, 'exp_date', true) ?: $item->exp_date;

                $item->enabled = get_post_meta($post_id, 'enabled', true) ?: $item->enabled;
            }

            $item->folder_name = DEVSACCOUNTING_PLUGIN_FOLDER_NAME;
        }

        $total_items = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE deleted_at IS NULL $search_condition",
                $search_param
            )
        );

        $response = [
            'data' => $items,
            'total_items' => intval($total_items),
            'total_pages' => ceil($total_items / $per_page),
            'current_page' => $page,
            'per_page' => $per_page,
        ];

        return rest_ensure_response($response);
    }


    public function get_inventories($request)
    {
        global $wpdb;
        $item_id = $request['id'];
        $table_name = $wpdb->prefix . 'dac_inventories';

        $item_id = intval($item_id);
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE item_id = %d", $item_id), ARRAY_A);

        if (empty($results)) {
            return new WP_Error('no_inventories_found', esc_html__('No inventories found.', 'devs-accounting'), array('status' => 404));
        }

        return rest_ensure_response($results);
    }

    public function get_single_item($request)
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_items';
        $inventories_table = $wpdb->prefix . 'dac_inventories';

        $item_id = $request->get_param('id');

        if (empty($item_id)) {
            return new WP_Error('invalid_item_id', esc_html__('Invalid item ID', 'devs-accounting'), array('status' => 400));
        }

        if (isset($request['type']) && !empty($request['type']) && $request['type'] == 'product' && class_exists('DevsAccounting_Wc')) {
            $item = (new DevsAccounting_Wc)->get_wc_single_product($item_id);
        } else {
            $item = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM $table_name WHERE id = %d",
                $item_id
            ));
        }

        if ($item) {
            $item->folder_name = DEVSACCOUNTING_PLUGIN_FOLDER_NAME;
            $item->meta = !empty($item->meta) ? json_decode($item->meta, true) : array();

            $inventories = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $inventories_table WHERE item_id = %d",
                $item_id
            ));
            $item->inventories = $inventories;

            return rest_ensure_response($item);
        } else {
            return new WP_Error('item_not_found', esc_html__('Item not found', 'devs-accounting'), array('status' => 404));
        }
    }

    public function delete_single_item($request)
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'dac_items';
        $item_id = isset($request['id']) ? intval($request['id']) : 0;

        if ($item_id <= 0) {
            return new WP_Error('invalid_item_id', esc_html__('Invalid item ID', 'devs-accounting'), array('status' => 400));
        }

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

        if (!$existing_item) {
            return new WP_Error('item_not_found', esc_html__('Item not found', 'devs-accounting'), array('status' => 404));
        }

        $current_time = gmdate('Y-m-d H:i:s');

        $result = $wpdb->update(
            $table_name,
            array(
                'deleted_at' => $current_time,
            ),
            array('id' => $item_id)
        );

        if ($result === false) {
            return new WP_Error('soft_delete_failed', esc_html__('Failed to soft delete item', 'devs-accounting'), array('status' => 500));
        }

        return rest_ensure_response(array('message' => esc_html__('Item soft deleted successfully', 'devs-accounting')));
    }

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

        $item_id = $request->get_param('id');
        $is_update = !empty($item_id);

        if ($is_update && !is_numeric($item_id)) {
            return new WP_Error('invalid_item_id', __('Invalid item ID', 'devs-accounting'), ['status' => 400]);
        }

        // Sanitize inputs
        $name            = sanitize_text_field($request['name'] ?? '');
        $description     = sanitize_textarea_field($request['description'] ?? '');
        $sale_price      = floatval($request['sale_price'] ?? -1);
        $category_id     = intval($request['category_id'] ?? -1);
        $stock_limit     = intval($request['stock_limit'] ?? -1);
        $sku             = sanitize_text_field($request['sku'] ?? '');
        $purchase_price  = floatval($request['purchase_price'] ?? -1);
        $enabled         = intval($request['enabled'] ?? 1);
        $exp_date        = sanitize_text_field($request['exp_date'] ?? '');
        $meta            = isset($request['meta']) ? (is_array($request['meta']) ? json_encode($request['meta']) : $request['meta']) : null;

        // Validate required fields
        if (empty($name) || $sale_price < 0 || $category_id <= 0 || $stock_limit < 0 || empty($sku) || $purchase_price < 0) {
            return new WP_Error('invalid_data', __('Invalid data provided.', 'devs-accounting'), ['status' => 400]);
        }

        // === IMAGE HANDLING ===
        $image_full_path = '';
        if (!empty($_FILES['image']['name'])) {

            if (!function_exists('wp_handle_upload')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }

            $sanitized_file = [
                'name' => sanitize_file_name($_FILES['image']['name']),
                'type' => sanitize_mime_type($_FILES['image']['type']),
                'tmp_name' => sanitize_text_field($_FILES['image']['tmp_name']),
                'error' => absint($_FILES['image']['error']),
                'size' => absint($_FILES['image']['size']),
            ];

            $uploaded_file = devsaccounting_validate_file($sanitized_file);
            if (isset($uploaded_file['error_msg'])) {
                return new WP_Error('file_error', $uploaded_file['error_msg'], ['status' => 400]);
            }

            $file_type = wp_check_filetype($uploaded_file['name']);
            $allowed = ['image/png','image/jpeg','image/webp','image/gif'];

            if (!in_array($file_type['type'], $allowed)) {
                return new WP_Error('type_error', __('Invalid file type.', 'devs-accounting'), ['status' => 400]);
            }

            $movefile = wp_handle_upload($uploaded_file, ['test_form' => false]);
            if (!empty($movefile['url'])) {
                $image_full_path = esc_url_raw($movefile['url']);
            }
        }
        elseif (!empty($request['image_url'])) {
            $image_full_path = esc_url_raw($request['image_url']);
        }
        elseif ($is_update) {
            $existing = $wpdb->get_row($wpdb->prepare("SELECT image FROM $table_name WHERE id = %d", $item_id));
            $image_full_path = $existing->image ?? '';
        }

        // ===== DATA FOR TABLE =====
        $data = [
            'name'           => $name,
            'description'    => $description,
            'sale_price'     => $sale_price,
            'category_id'    => $category_id,
            'stock_limit'    => $stock_limit,
            'sku'            => $sku,
            'purchase_price' => $purchase_price,
            'meta'           => $meta,
            'image'          => $image_full_path,
            'enabled'        => $enabled,
            'exp_date'       => $exp_date,
        ];

        // Load category name
        $category_name = $wpdb->get_var(
            $wpdb->prepare("SELECT name FROM {$wpdb->prefix}dac_categories WHERE id=%d", $category_id)
        );

        // =============== UPDATE =================
        if ($is_update) {

            // Update dac_items table
            $wpdb->update($table_name, $data, ['id' => intval($item_id)]);

            // Get linked post
            $post_id = $wpdb->get_var(
                $wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='item_id' AND meta_value=%d", $item_id)
            );

            if ($post_id) {
                wp_update_post([
                    'ID'          => $post_id,
                    'post_title'  => $name,
                    'post_content'=> $description,
                    'post_name'   => sanitize_title($name),
                ]);

                // Update post meta fields
                foreach ([
                    'sale_price'     => $sale_price,
                    'purchase_price' => $purchase_price,
                    'stock_limit'    => $stock_limit,
                    'sku'            => $sku,
                    'image_url'      => $image_full_path,
                    'category_name'  => $category_name,
                    'exp_date'       => $exp_date,
                    'enabled'        => $enabled,
                ] as $key => $value) {
                    update_post_meta($post_id, $key, $value);
                }

                // Featured image
                if (!empty($image_full_path)) {
                    $img_id = attachment_url_to_postid($image_full_path);
                    if ($img_id) set_post_thumbnail($post_id, $img_id);
                }
            }

            return ['message'=>'Item updated','success'=>true,'item_id'=>$item_id,'post_id'=>$post_id];
        }

        // =============== CREATE =================
        $wpdb->insert($table_name, $data);
        $insert_id = $wpdb->insert_id;

        if ($insert_id) {
            $post_id = wp_insert_post([
                'post_title'   => $name,
                'post_content' => $description,
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_type'    => 'items',
                'meta_input'   => [
                    'item_id'        => $insert_id,
                    'sale_price'     => $sale_price,
                    'purchase_price' => $purchase_price,
                    'stock_limit'    => $stock_limit,
                    'sku'            => $sku,
                    'image_url'      => $image_full_path,
                    'category_name'  => $category_name,
                    'exp_date'       => $exp_date,
                    'enabled'        => $enabled,
                ]
            ]);

            if ($post_id && $image_full_path) {
                $img_id = attachment_url_to_postid($image_full_path);
                if ($img_id) set_post_thumbnail($post_id, $img_id);
            }

            return ['message'=>'Item created','success'=>true,'item_id'=>$insert_id,'post_id'=>$post_id];
        }

        return ['message'=>'Create failed','success'=>false];
    }
   

    public function toggle_item_enabled($request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dac_items';
        $item_id = (int) $request->get_param('id');

        if ($item_id <= 0) {
            return new WP_Error('invalid_item_id', esc_html__('Invalid item ID', 'devs-accounting'), array('status' => 400));
        }

        $current_item = $wpdb->get_row($wpdb->prepare(
            "SELECT enabled FROM $table_name WHERE id = %d",
            $item_id
        ));

        if (!$current_item) {
            return new WP_Error('item_not_found', esc_html__('Item not found', 'devs-accounting'), array('status' => 404));
        }

        // toggle
        $new_status = $current_item->enabled ? 0 : 1;

        // update table
        $result = $wpdb->update(
            $table_name,
            array('enabled' => $new_status),
            array('id' => $item_id),
            array('%d'),
            array('%d')
        );

        if ($result === false) {
            return new WP_Error('update_failed', esc_html__('Failed to toggle item status', 'devs-accounting'), array('status' => 500));
        }


        $post_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='item_id' AND meta_value=%d",
                $item_id
            )
        );

        if ($post_id) {
            update_post_meta($post_id, 'enabled', $new_status);
        }

        $action = $new_status ? 'enabled' : 'disabled';

        return rest_ensure_response(array(
            'success' => true,
            'enabled' => (bool) $new_status,
            'post_id' => $post_id,
            'message' => esc_html__("Item successfully $action", 'devs-accounting'),
            'action' => $action
        ));
    }


    public function update_item_inventory($request)
    {
        global $wpdb;

        $inventory_table = $wpdb->prefix . 'dac_inventories';
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings);

        $item_id = isset($request['id']) ? intval($request['id']) : 0;
        if (empty($item_id)) {
            return new WP_Error('invalid_item_id', esc_html__('Invalid item ID', 'devs-accounting'), array('status' => 400));
        }

        $errors = array();
        $in_out_qty = intval($request['in_out_qty']);
        if (empty($in_out_qty)) {
            $errors['in_out_qty'] = esc_html__('Qunatity add/substract is required.', 'devs-accounting');
        }
        if (!empty($errors)) {
            $response = array(
                'message' => esc_html__('Validation errors occurred.', 'devs-accounting'),
                'errors' => $errors,
            );
            return new WP_REST_Response($response, 400);
        }


        $remarks = sanitize_text_field($request['remarks']);
        $variant_id = intval($request['variant_id']);

        $data = array(
            'item_id' => $item_id,
            'in_out_qty' => $in_out_qty,
            'remarks' => $remarks,
            'user_id' => $this->user->ID,
            'variant_id' => $variant_id,
        );

        $result = $wpdb->insert($inventory_table, $data);

        if ($result === false) {
            return new WP_Error('insert_failed', esc_html__('Failed to update inventory.', 'devs-accounting'), array('status' => 500));
        }

        if (isset($request['type']) && $request['type'] == 'product' && class_exists('DevsAccounting_Wc')) {
            (new DevsAccounting_Wc)->update_wc_inventory_single_product($item_id, $in_out_qty);
        }

        return rest_ensure_response(array('message' => esc_html__('Inventory updated successfully!', 'devs-accounting'), 'request' => $data));
    }
    public function get_tax_names_by_ids($taxes)
    {
        global $wpdb;
        $tax_table = $wpdb->prefix . 'dac_taxes';

        $tax_ids = explode(';', $taxes);
        $tax_ids = array_map('intval', $tax_ids);
        $tax_names = [];

        foreach ($tax_ids as $tax_id) {
            $result = $wpdb->get_var($wpdb->prepare(
                "SELECT tax_name FROM $tax_table WHERE id = %d",
                $tax_id
            ));
            if ($result) {
                $tax_names[] = $result;
            }
        }

        return implode(', ', $tax_names);
    }

    public function export_items($request)
    {
        global $wpdb;

        $items_table = $wpdb->prefix . 'dac_items';
        $categories_table = $wpdb->prefix . 'dac_categories';
        $item_tax_table = $wpdb->prefix . 'dac_item_tax';
        $inventories_table = $wpdb->prefix . 'dac_inventories';

        // Fetch items along with their details
        $results = $wpdb->get_results(
            "SELECT 
                i.id,
                i.name, 
                i.description, 
                i.sale_price, 
                c.name as category_name, 
                i.stock_limit, 
                i.sku, 
                i.purchase_price, 
                i.meta, 
                i.image,
                GROUP_CONCAT(it.tax_id SEPARATOR '; ') AS tax_ids
            FROM $items_table i
            LEFT JOIN $categories_table c ON i.category_id = c.id
            LEFT JOIN $item_tax_table it ON i.id = it.item_id
            WHERE i.deleted_at IS NULL
            GROUP BY i.id",
            ARRAY_A
        );

        if (empty($results)) {
            return new WP_Error('no_items_found', esc_html__('No items found to export.', 'devs-accounting'), array('status' => 404));
        }

        // Loop through each item and calculate the total quantity from inventories
        foreach ($results as $item) {
            // Calculate the total quantity from the inventories table
            $total_quantity = $wpdb->get_var($wpdb->prepare(
                "SELECT SUM(in_out_qty) 
                FROM $inventories_table 
                WHERE item_id = %d",
                $item['id']
            ));

            // Update the 'quantity' column in the 'items' table with the calculated quantity
            $wpdb->update(
                $items_table,
                ['quantity' => $total_quantity], // Update quantity
                ['id' => $item['id']], // Target the item by ID
                ['%d'], // Format for quantity
                ['%d'] // Format for item_id
            );
        }

        // Then continue to export the data if needed (CSV export code)
        $filename = 'items_export_' . date('Y-m-d') . '.csv';

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        $output = fopen('php://output', 'w');

        $headers = array('Name', 'Description', 'Sale Price', 'Category Name', 'Stock Limit', 'SKU', 'Purchase Price', 'Meta', 'Tax Name', 'Image', 'Quantity');
        fputcsv($output, $headers);

        foreach ($results as $item) {
            $meta = '';
            if (!empty($item['meta'])) {
                $meta_data = json_decode($item['meta'], true);
                if (is_array($meta_data)) {
                    $meta_items = array_map(function ($meta_item) {
                        return $meta_item['meta_name'] . ': ' . $meta_item['meta_value'];
                    }, $meta_data);
                    $meta = implode('; ', $meta_items);
                } else {
                    $meta = $meta_data;
                }
            }

            $tax_names = !empty($item['tax_ids']) ? $this->get_tax_names_by_ids($item['tax_ids']) : '';

            // Get the quantity after updating
            $quantity = $wpdb->get_var($wpdb->prepare(
                "SELECT quantity FROM $items_table WHERE id = %d",
                $item['id']
            ));

            $row = array(
                $item['name'],
                $item['description'],
                $item['sale_price'],
                $item['category_name'],
                $item['stock_limit'],
                $item['sku'],
                $item['purchase_price'],
                $meta,
                $tax_names,
                $item['image'],
                $quantity ?? 0
            );

            fputcsv($output, $row);
        }

        fclose($output);
        exit;
    }



    function insert_category($category_name)
    {
        global $wpdb;
        $category_table = $wpdb->prefix . 'dac_categories';

        $category_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $category_table WHERE name = %s",
            $category_name
        ));

        if (!$category_id) {
            $wpdb->insert($category_table, ['name' => $category_name], ['%s']);
            $category_id = $wpdb->insert_id;
        }

        return $category_id;
    }

    public function insert_item($name, $description, $sale_price, $category_id, $stock_limit, $sku, $purchase_price, $meta, $image)
    {
        global $wpdb;
        $items_table = $wpdb->prefix . 'dac_items';

        $wpdb->insert(
            $items_table,
            [
                'name' => $name,
                'description' => $description,
                'sale_price' => $sale_price,
                'category_id' => $category_id,
                'stock_limit' => $stock_limit,
                'sku' => $sku,
                'purchase_price' => $purchase_price,
                'meta' => $meta,
                'image' => $image
            ],
            ['%s', '%s', '%f', '%d', '%d', '%s', '%f', '%s', '%s']
        );

        return $wpdb->insert_id;
    }

    public function insert_item_taxes($item_id, $taxes)
    {
        global $wpdb;
        $item_tax_table = $wpdb->prefix . 'dac_item_tax';
        $tax_table = $wpdb->prefix . 'dac_taxes';
        $tax_names = array_filter(array_map('trim', explode(',', $taxes)));
        foreach ($tax_names as $tax_name) {
            if (!empty($tax_name)) {
                $tax_id = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM $tax_table WHERE tax_name = %s",
                    $tax_name
                ));

                if ($tax_id) {
                    $wpdb->insert(
                        $item_tax_table,
                        ['item_id' => $item_id, 'tax_id' => $tax_id],
                        ['%d', '%d']
                    );
                }
            }
        }
    }

    public function import_items(WP_REST_Request $request)
    {
        if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            return new WP_Error('upload_error', __('CSV upload failed.', 'devs-accounting'), ['status' => 400]);
        }

        $csv_file = $_FILES['file']['tmp_name'];
        $handle = fopen($csv_file, 'r');

        if (!$handle) {
            return new WP_Error('csv_open_error', __('Could not open CSV file.', 'devs-accounting'), ['status' => 400]);
        }

        global $wpdb;
        $imported = 0;


        $header = fgetcsv($handle);

        while (($row = fgetcsv($handle)) !== false) {

            if (empty(array_filter($row))) {
                continue;
            }

            if (count($row) < 9) {
                continue;
            }

            [$name, $description, $sale_price, $category_name, $stock_limit, $sku, $purchase_price, $meta, $taxes, $image, $quantity] = $row;

            $name = sanitize_text_field($name);
            $description = sanitize_textarea_field($description);
            $sale_price = sanitize_text_field($sale_price);
            $category_name = sanitize_text_field($category_name);
            $stock_limit = (int) $stock_limit;
            $sku = sanitize_text_field($sku);
            $purchase_price = sanitize_text_field($purchase_price);
            $meta = sanitize_textarea_field($meta);
            $taxes = sanitize_text_field($taxes);
            $image = sanitize_text_field($image);
            $quantity = is_numeric($quantity) ? (int) $quantity : 0;

            $meta_array = [];
            $meta_items = explode('; ', $meta);
            foreach ($meta_items as $meta_item) {
                $meta_parts = explode(': ', $meta_item);
                if (count($meta_parts) === 2) {
                    $meta_array[] = [
                        'meta_name' => sanitize_text_field($meta_parts[0]),
                        'meta_value' => sanitize_textarea_field($meta_parts[1]),
                    ];
                }
            }

            $meta_json = json_encode($meta_array);

            $category_id = $this->insert_category($category_name);

            $item_id = $this->insert_item(
                $name,
                $description,
                $sale_price,
                $category_id,
                $stock_limit,
                $sku,
                $purchase_price,
                $meta_json,
                $image
            );

            $this->insert_item_taxes($item_id, $taxes);

            if ($quantity > 0) {
                $this->insert_inventory($item_id, $quantity);
            }

            $imported++;
        }

        fclose($handle);

        if ($imported === 0) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'No items were imported.',
            ], 400);
        } else {
            return new WP_REST_Response([
                'success' => true,
                'message' => "$imported item(s) imported successfully.",
            ]);
        }
    }





    public function insert_inventory($item_id, $quantity)
    {
        global $wpdb;
        $inventories_table = $wpdb->prefix . 'dac_inventories';

        $existing_inventory = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $inventories_table WHERE item_id = %d",
            $item_id
        ));

        if ($existing_inventory) {
            $wpdb->update(
                $inventories_table,
                ['in_out_qty' => $quantity],
                ['item_id' => $item_id],
                ['%d'],
                ['%d']
            );
        } else {
            $wpdb->insert(
                $inventories_table,
                [
                    'item_id' => $item_id,
                    'in_out_qty' => $quantity,
                    'created_at' => current_time('mysql'),
                ],
                ['%d', '%d', '%s']
            );
        }
    }

    public function sample_items_download()
    {
        $filename = 'sample_items.csv';

        $headers = [
            'Name',
            'Description',
            'Sale Price',
            'Category Name',
            'Stock Limit',
            'SKU',
            'Purchase Price',
            'Meta',
            'Tax Name',
            'Image',
            'Quantity'
        ];

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $output = fopen('php://output', 'w');
        fputcsv($output, $headers);
        fclose($output);
        exit;
    }
}

$items = new DevsAccounting_Item($current_user);
