<?php

/**
 * General Settings Controller V1
 *
 * @package Licenzo\Http\Controller\Api\V1
 */

namespace Licenzo\Http\Controller\Api\V1;

use Licenzo\Helper\Settings;
use Licenzo\Framework\Http\Request;
use Licenzo\Helper\Settings\EmailNotificationSetting;
use Licenzo\Http\Traits\HandlesErrors;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}
class OnBoardingController
{
    use HandlesErrors;
    /**
     * Update general settings
     *
     * @param Request $request
     * @return array
     */
    /**
     * Handle full onboarding update (all steps)
     */

    /**
     * 1️⃣ WooCommerce status
     */
    public function woocommerceStatus()
    {
        $data = [
            'installed' => class_exists('WooCommerce'),
            'active'    => is_plugin_active('woocommerce/woocommerce.php'),
            'version'   => defined('WC_VERSION') ? WC_VERSION : null,
        ];
        return [
            'success' => true,
            'data' => $data,
        ];
    }


    // check product existence in WooCommerce

    public function wooProductExist()
    {
        $args = [
            'status' => 'publish',
        ];
        $products = wc_get_products($args);
        return [
            'success' => true,
            'exists' => !empty($products),
            'count' => count($products),
        ];
    }


    public function setup(Request $request)
    {
        $data = $request->getSafe([
            'woocommerce'  => null,
            'productSetup' => null,
            'general'      => null,
            'license'      => null,
            'notification' => null,
        ]);
        // Sanitize nested arrays
        foreach (['woocommerce', 'productSetup', 'general', 'license', 'notification'] as $key) {
            if (is_array($data[$key] ?? null)) {
                $data[$key] = array_map('sanitize_text_field', $data[$key]);
            }
        }

        try {
            if (!empty($data['woocommerce'])) {
                Settings::updateWooCommerceSettings($data['woocommerce']);
            }
            if (!empty($data['productSetup'])) {
                Settings::updateProductSetupSettings($data['productSetup']);
            }

            if (!empty($data['general'])) {
                Settings::updateGeneralSettings($data['general']);
            }

            if (!empty($data['license'])) {
                Settings::updateLicenseSettings($data['license']);
            }

            if (!empty($data['notification'])) {
                EmailNotificationSetting::update([
                    'customer_welcome'    => $data['notification']['customer_welcome'],
                    'license_activation'  => $data['notification']['license_activation'],
                    'license_expiration'  => $data['notification']['license_expiration'],
                    'maximum_activations' => $data['notification']['maximum_activations'],
                ]);
            }

            return $this->successResponse([
                'woocommerce' =>  Settings::getWooCommerceSettings(),
                'productSetup' => Settings::getProductSetupSettings(),
                'general'      => Settings::getGeneralSettings(),
                'license'      => Settings::getLicenseSettings(),
                'subscription' => Settings::getSubscriptionSettings(),
            ], __('Onboarding completed successfully', 'licenzo'));
        } catch (\Exception $e) {
            return $this->handleError($e, __('Failed to complete onboarding', 'licenzo'));
        }
    }
}
