<?php
/**
 * Bizmart — Demo data admin helpers.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */

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

if (!function_exists('bizmart_demo_data_get_components')) {
    function bizmart_demo_data_get_components(): array {
        $components = [
            'core' => [
                'label' => 'Bizmart Core',
                'description' => 'WooCommerce products, stock, and order activity used by the dashboard.',
                'installed' => true,
                'active' => defined('BIZMART_CORE_LOADED') && function_exists('wc_get_orders'),
                'default' => true,
            ],
        ];

        $plugins_dir = dirname(dirname(dirname(__FILE__)));
        $addon_file = '';
        if (defined('BIZMART_ADDON_DIR')) {
            $addon_file = BIZMART_ADDON_DIR . 'bizmart-stock-finance-invoice.php';
        } else {
            foreach (array('bizmart-stock-finance-invoice', 'bizmart-addon', 'bizmart-addon-master') as $folder) {
                if (file_exists("$plugins_dir/$folder/bizmart-stock-finance-invoice.php")) {
                    $addon_file = "$plugins_dir/$folder/bizmart-stock-finance-invoice.php";
                    break;
                } elseif (file_exists("$plugins_dir/$folder/bizmart-addon.php")) {
                    $addon_file = "$plugins_dir/$folder/bizmart-addon.php";
                    break;
                }
            }
        }

        if (defined('BIZMART_ADDON_DIR') || ($addon_file && file_exists($addon_file))) {
            $components['addon'] = [
                'label' => 'Bizmart Addon',
                'description' => 'Suppliers, invoices, payments, expenses, and cashflow records.',
                'installed' => true,
                'active' => function_exists('bizmart_ensure_financial_schema') && function_exists('bizmart_update_invoice_financials'),
                'default' => function_exists('bizmart_ensure_financial_schema'),
            ];
        }

        $pos_file = '';
        if (defined('BIZMART_POS_DIR')) {
            $pos_file = BIZMART_POS_DIR . 'bizmart-pos.php';
        } else {
            foreach (array('bizmart-pos', 'bizmart-pos-master') as $folder) {
                if (file_exists("$plugins_dir/$folder/bizmart-pos.php")) {
                    $pos_file = "$plugins_dir/$folder/bizmart-pos.php";
                    break;
                }
            }
        }

        if (defined('BIZMART_POS_DIR') || ($pos_file && file_exists($pos_file))) {
            $components['pos'] = [
                'label' => 'Bizmart POS',
                'description' => 'Registers, sessions, cash movements, and POS-tagged orders.',
                'installed' => true,
                'active' => class_exists('Bizmart_POS_DB') && class_exists('Bizmart_POS_Session'),
                'default' => class_exists('Bizmart_POS_DB') && class_exists('Bizmart_POS_Session'),
            ];
        }

        return $components;
    }
}

if (!function_exists('bizmart_demo_data_get_last_manifest')) {
    function bizmart_demo_data_get_last_manifest(): array {
        $manifest = get_option('bizmart_demo_seed_manifest_v1', []);
        return is_array($manifest) ? $manifest : [];
    }
}

if (!function_exists('bizmart_demo_data_get_last_summary')) {
    function bizmart_demo_data_get_last_summary(): array {
        $manifest = bizmart_demo_data_get_last_manifest();
        return (isset($manifest['summary']) && is_array($manifest['summary'])) ? $manifest['summary'] : [];
    }
}

if (!function_exists('bizmart_demo_data_has_seed')) {
    function bizmart_demo_data_has_seed(): bool {
        return !empty(bizmart_demo_data_get_last_manifest());
    }
}

if (!function_exists('bizmart_demo_data_get_selected_components')) {
    function bizmart_demo_data_get_selected_components($raw_components): array {
        $available = bizmart_demo_data_get_components();
        $selected = [];

        foreach ((array) $raw_components as $component) {
            $component = sanitize_key((string) $component);
            if ($component !== '' && isset($available[$component]) && !empty($available[$component]['active'])) {
                $selected[] = $component;
            }
        }

        if (!$selected) {
            foreach ($available as $key => $component) {
                if (!empty($component['default']) && !empty($component['active'])) {
                    $selected[] = $key;
                }
            }
        }

        return array_values(array_unique($selected));
    }
}

if (!function_exists('bizmart_demo_data_get_seeder')) {
    function bizmart_demo_data_get_seeder() {
        $seeder_file = BIZMART_CORE_DIR . 'includes/demo-data-seeder.php';

        if (!file_exists($seeder_file)) {
            if (defined('BIZMART_ADDON_DIR')) {
                $seeder_file = BIZMART_ADDON_DIR . 'demo-data-seeder.php';
            }
        }

        if (!file_exists($seeder_file)) {
            $plugins_dir = dirname(dirname(dirname(__FILE__)));
            $dirs = glob($plugins_dir . '/*/demo-data-seeder.php');
            if (!empty($dirs)) {
                $seeder_file = $dirs[0];
            }
        }

        if (!file_exists($seeder_file)) {
            throw new Exception('Bizmart demo seeder is not installed.');
        }

        require_once $seeder_file;

        if (!class_exists('Bizmart_Demo_Data_Seeder')) {
            throw new Exception('Bizmart demo seeder could not be loaded.');
        }

        return new Bizmart_Demo_Data_Seeder();
    }
}

if (!function_exists('bizmart_demo_data_handle_settings_action')) {
    function bizmart_demo_data_handle_settings_action(string $action, $raw_components): array {
        try {
            $seeder = bizmart_demo_data_get_seeder();

            if ($action === 'cleanup') {
                return ['notice' => $seeder->cleanup_existing_seed(), 'error' => ''];
            }

            $components = bizmart_demo_data_get_selected_components($raw_components);
            if (!$components) {
                return ['notice' => '', 'error' => 'Select at least one active Bizmart component to import demo data.'];
            }

            return ['notice' => $seeder->generate_demo_data($components), 'error' => ''];
        } catch (Exception $exception) {
            return ['notice' => '', 'error' => $exception->getMessage()];
        } catch (Throwable $throwable) {
            return ['notice' => '', 'error' => $throwable->getMessage()];
        }
    }
}