<?php

declare(strict_types=1);

namespace Instinctor\Services;

use Instinctor\Core\Config;


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

/**
 * Checkout Configuration Service
 * Manages checkout layout, fields, and settings
 */
class CheckoutConfig
{
    private const OPTION_KEY = 'instinctor_checkout_config';

    public static function getDefaults(): array
    {
        return [
            'layout' => 'one-page', // one-page, multi-step, express
            'style' => 'modern', // modern, classic, minimal
            'guest_checkout' => true,
            'create_account_option' => true,
            'email_first' => true, // Capture email first for abandoned cart
            'show_coupon' => true,
            'show_gift_card' => true,
            'express_payments' => [
                'enabled' => false,
                'apple_pay' => false,
                'google_pay' => false,
                'link' => false, // Stripe Link
            ],
            'order_bumps' => [],
            'fields' => self::getDefaultFields(),
            'field_order' => ['email', 'name', 'address', 'phone', 'notes'],
        ];
    }

    public static function getDefaultFields(): array
    {
        return [
            'email' => [
                'id' => 'email',
                'type' => 'email',
                'label' => 'Email',
                'placeholder' => 'you@example.com',
                'required' => true,
                'enabled' => true,
                'width' => 'full',
                'section' => 'contact',
                'order' => 0,
                'locked' => true, // Cannot be deleted
            ],
            'first_name' => [
                'id' => 'first_name',
                'type' => 'text',
                'label' => 'First name',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'half',
                'section' => 'billing',
                'order' => 1,
                'locked' => true,
            ],
            'last_name' => [
                'id' => 'last_name',
                'type' => 'text',
                'label' => 'Last name',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'half',
                'section' => 'billing',
                'order' => 2,
                'locked' => true,
            ],
            'company' => [
                'id' => 'company',
                'type' => 'text',
                'label' => 'Company',
                'placeholder' => '',
                'required' => false,
                'enabled' => false,
                'width' => 'full',
                'section' => 'billing',
                'order' => 3,
                'locked' => false,
            ],
            'address_1' => [
                'id' => 'address_1',
                'type' => 'text',
                'label' => 'Address',
                'placeholder' => 'Street address',
                'required' => true,
                'enabled' => true,
                'width' => 'full',
                'section' => 'billing',
                'order' => 4,
                'locked' => true,
                'autocomplete' => 'address',
            ],
            'address_2' => [
                'id' => 'address_2',
                'type' => 'text',
                'label' => 'Apartment, suite, etc.',
                'placeholder' => '',
                'required' => false,
                'enabled' => true,
                'width' => 'full',
                'section' => 'billing',
                'order' => 5,
                'locked' => false,
            ],
            'city' => [
                'id' => 'city',
                'type' => 'text',
                'label' => 'City',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'half',
                'section' => 'billing',
                'order' => 6,
                'locked' => true,
            ],
            'state' => [
                'id' => 'state',
                'type' => 'text',
                'label' => 'State',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'half',
                'section' => 'billing',
                'order' => 7,
                'locked' => true,
            ],
            'postcode' => [
                'id' => 'postcode',
                'type' => 'text',
                'label' => 'ZIP code',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'half',
                'section' => 'billing',
                'order' => 8,
                'locked' => true,
            ],
            'country' => [
                'id' => 'country',
                'type' => 'country',
                'label' => 'Country',
                'placeholder' => '',
                'required' => true,
                'enabled' => true,
                'width' => 'full',
                'section' => 'billing',
                'order' => 9,
                'locked' => true,
            ],
            'phone' => [
                'id' => 'phone',
                'type' => 'tel',
                'label' => 'Phone',
                'placeholder' => '',
                'required' => false,
                'enabled' => true,
                'width' => 'full',
                'section' => 'contact',
                'order' => 10,
                'locked' => false,
            ],
            'custom_field' => [
                'id' => 'custom_field',
                'type' => 'text',
                'label' => 'Custom field',
                'placeholder' => '',
                'required' => false,
                'enabled' => false,
                'width' => 'full',
                'section' => 'billing',
                'order' => 11,
                'locked' => false,
            ],
            'notes' => [
                'id' => 'notes',
                'type' => 'textarea',
                'label' => 'Order notes',
                'placeholder' => 'Special instructions for delivery...',
                'required' => false,
                'enabled' => false,
                'width' => 'full',
                'section' => 'additional',
                'order' => 12,
                'locked' => false,
            ],
        ];
    }

    public static function get(): array
    {
        $saved = Config::get(self::OPTION_KEY, []);
        return array_merge(self::getDefaults(), $saved);
    }

    public static function save(array $config): bool
    {
        // Validate
        $allowed_layouts = ['one-page', 'multi-step', 'express'];
        if (!in_array($config['layout'] ?? '', $allowed_layouts)) {
            $config['layout'] = 'one-page';
        }

        return Config::set(self::OPTION_KEY, $config);
    }

    public static function getFields(): array
    {
        $config = self::get();
        $defaults = self::getDefaultFields();
        $fields = $config['fields'] ?? $defaults;
        
        // Ensure Email field is always present and enabled (it's mandatory)
        if (!isset($fields['email'])) {
            $fields['email'] = $defaults['email'];
        }
        $fields['email']['enabled'] = true;
        $fields['email']['required'] = true;
        
        // Return only enabled fields, sorted by order
        $enabled = array_filter($fields, fn($f) => $f['enabled'] ?? false);
        
        // Sort by custom order only (not by section) to match preview
        uasort($enabled, function($a, $b) {
            return ($a['order'] ?? 0) - ($b['order'] ?? 0);
        });

        return $enabled;
    }

    public static function addField(array $field): bool
    {
        $config = self::get();
        
        if (empty($field['id'])) {
            $field['id'] = 'custom_' . uniqid();
        }

        $field = array_merge([
            'type' => 'text',
            'label' => 'Custom Field',
            'placeholder' => '',
            'required' => false,
            'enabled' => true,
            'width' => 'full',
            'section' => 'additional',
            'locked' => false,
        ], $field);

        $config['fields'][$field['id']] = $field;

        return self::save($config);
    }

    public static function updateField(string $id, array $updates): bool
    {
        $config = self::get();
        
        if (!isset($config['fields'][$id])) {
            return false;
        }

        // Prevent unlocking locked fields
        if ($config['fields'][$id]['locked'] ?? false) {
            unset($updates['locked']);
            unset($updates['id']); // Can't change ID of locked fields
        }

        $config['fields'][$id] = array_merge($config['fields'][$id], $updates);

        return self::save($config);
    }

    public static function removeField(string $id): bool
    {
        $config = self::get();
        
        if (!isset($config['fields'][$id])) {
            return false;
        }

        // Can't remove locked fields
        if ($config['fields'][$id]['locked'] ?? false) {
            return false;
        }

        unset($config['fields'][$id]);

        return self::save($config);
    }

    public static function reorderFields(array $order): bool
    {
        $config = self::get();
        
        $i = 0;
        foreach ($order as $fieldId) {
            if (isset($config['fields'][$fieldId])) {
                $config['fields'][$fieldId]['order'] = $i++;
            }
        }

        return self::save($config);
    }

    public static function getOrderBumps(): array
    {
        $config = self::get();
        return $config['order_bumps'] ?? [];
    }

    public static function addOrderBump(array $bump): bool
    {
        $config = self::get();
        
        $bump = array_merge([
            'id' => 'bump_' . uniqid(),
            'product_id' => null,
            'title' => '',
            'description' => '',
            'discount_type' => 'percent', // percent, fixed
            'discount_value' => 0,
            'enabled' => true,
        ], $bump);

        $config['order_bumps'][$bump['id']] = $bump;

        return self::save($config);
    }

    public static function removeOrderBump(string $id): bool
    {
        $config = self::get();
        
        if (isset($config['order_bumps'][$id])) {
            unset($config['order_bumps'][$id]);
            return self::save($config);
        }

        return false;
    }
}
