<?php
/**
 * Enhanced DnDSections with Group Field System
 * 
 * @package HvnlyNab\Api\Type\Builders
 * @since 2.0.0
 */

namespace HvnlyNab\Api\Type\Builders;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use HvnlyNab\Api\Type\Builders\DefaultTabSectionsData;

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

class DnDSections
{
    private $storage_key = 'hvnly_property_builder.sections';
    private $namespace = 'hvnlynab/v1';
    private $route_base = 'pb-dnd-sections';
    
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'routes']);
    }

    /**
     * Register REST API routes
     */
    public function routes()
    {
        // GET all sections
        register_rest_route($this->namespace, '/' . $this->route_base, [
            'methods' => 'GET',
            'callback' => [$this, 'get_all'],
            'permission_callback' => [$this, 'get_per'],
        ]);

        // POST save all tabs
        register_rest_route($this->namespace, '/' . $this->route_base, [
            'methods' => 'POST',
            'callback' => [$this, 'save_all'],
            'permission_callback' => [$this, 'create_per'],
        ]);

        // DELETE all sections
        register_rest_route($this->namespace, '/' . $this->route_base, [
            'methods' => 'DELETE',
            'callback' => [$this, 'delete_all'],
            'permission_callback' => [$this, 'del_per'],
        ]);
    }

    /**
     * Save all tabs/sections with group support
     */
    public function save_all($request)
    {
        try {
            $params = $request->get_json_params();

            if (!isset($params['tabs'])) {
                return new \WP_Error('invalid_data', 'Tabs data is required', ['status' => 400]);
            }

            if (!is_array($params['tabs'])) {
                return new \WP_Error('invalid_data', 'Tabs must be an array', ['status' => 400]);
            }

            $tabs = [];
            foreach ($params['tabs'] as $index => $tab) {
                if (!is_array($tab)) {
                    continue;
                }

                $id = sanitize_text_field($tab['id'] ?? 'sec_' . uniqid());

                $tabs[$id] = [
                    'id' => $id,
                    'title' => sanitize_text_field($tab['title'] ?? 'Untitled Section'),
                    'icon' => sanitize_text_field($tab['icon'] ?? 'fas fa-home'),
                    'fields' => $this->sanitize_fields_with_groups($tab['fields'] ?? []),
                    'order' => intval($tab['order'] ?? $index),
                    'collapsed' => !empty($tab['collapsed']),
                    'required' => !empty($tab['required'])
                ];
            }

            // Reindex tabs by order
            uasort($tabs, function ($a, $b) {
                return $a['order'] - $b['order'];
            });

            $result = update_option($this->storage_key, $tabs);

            return rest_ensure_response([
                'success' => true,
                'data' => array_values($tabs),
                'message' => 'Tabs saved successfully',
                'saved_count' => count($tabs)
            ]);
        } catch (\Exception $e) {
            return new \WP_Error('save_failed', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Sanitize fields with group metadata
     */
    private function sanitize_fields_with_groups($fields)
    {
        if (!is_array($fields)) {
            return [];
        }

        $sanitized_fields = [];

        foreach ($fields as $field) {
            if (!is_array($field)) {
                continue;
            }

            $sanitized_field = [
                'id' => sanitize_text_field($field['id'] ?? 'fld_' . uniqid()),
                'name' => sanitize_text_field($field['name'] ?? $field['id'] ?? 'fld_' . uniqid()),
                'type' => sanitize_text_field($field['type'] ?? 'text'),
                'label' => sanitize_text_field($field['label'] ?? ''),
                'placeholder' => sanitize_text_field($field['placeholder'] ?? ''),
                'required' => !empty($field['required']),
                'adminOnly' => !empty($field['adminOnly']),
                'enabled' => !empty($field['enabled']),
                'locked' => !empty($field['locked']),
                'order' => intval($field['order'] ?? 0),
                'hidden' => !empty($field['hidden'])
            ];

            // Add group metadata if present
            if (!empty($field['group_id'])) {
                $sanitized_field['group_id'] = sanitize_text_field($field['group_id']);
                $sanitized_field['group_type'] = sanitize_text_field($field['group_type'] ?? '');
                $sanitized_field['group_name'] = sanitize_text_field($field['group_name'] ?? '');
                $sanitized_field['group_position'] = intval($field['group_position'] ?? 0);
                $sanitized_field['group_total'] = intval($field['group_total'] ?? 0);
                $sanitized_field['group_base_id'] = sanitize_text_field($field['group_base_id'] ?? '');
                $sanitized_field['metaKey'] = sanitize_text_field($field['metaKey'] ?? '');
                
                // Save group collapsed state
                $sanitized_field['group_collapsed'] = !empty($field['group_collapsed']);
                
                // Add show_in_sidebar ONLY for property_docs group fields
                if (($field['group_type'] ?? '') === 'property_docs' && isset($field['show_in_sidebar'])) {
                    $sanitized_field['show_in_sidebar'] = (bool)$field['show_in_sidebar'];
                }
            }

            // Add map relationship fields
            if (!empty($field['address_field_name'])) {
                $sanitized_field['address_field_name'] = sanitize_text_field($field['address_field_name']);
            }
            if (!empty($field['lat_field_name'])) {
                $sanitized_field['lat_field_name'] = sanitize_text_field($field['lat_field_name']);
            }
            if (!empty($field['lng_field_name'])) {
                $sanitized_field['lng_field_name'] = sanitize_text_field($field['lng_field_name']);
            }
            if (!empty($field['map_field_name'])) {
                $sanitized_field['map_field_name'] = sanitize_text_field($field['map_field_name']);
            }

            // Add conditional fields
            if (!empty($field['condition'])) {
                $sanitized_field['condition'] = [
                    'field' => sanitize_text_field($field['condition']['field'] ?? ''),
                    'value' => sanitize_text_field($field['condition']['value'] ?? '')
                ];
            }

            // Add options for select fields
            if (!empty($field['options']) && is_array($field['options'])) {
                $sanitized_field['options'] = array_map('sanitize_text_field', $field['options']);
            }

            // Add file type for file uploads
            if (!empty($field['fileType'])) {
                $sanitized_field['fileType'] = sanitize_text_field($field['fileType']);
            }

            // Add description/userguide
            if (!empty($field['description'])) {
                $sanitized_field['description'] = sanitize_text_field($field['description']);
            }

            if (!empty($field['userguide'])) {
                $sanitized_field['userguide'] = sanitize_text_field($field['userguide']);
            }

            $sanitized_fields[] = $sanitized_field;
        }

        return $sanitized_fields;
    }

    /**
     * Fetch all sections with group data
     */
    public function get_all()
    {
        try {
            $sections = get_option($this->storage_key, []);
            $has_defaults = false;

            if (empty($sections) || !is_array($sections)) {
                $sections = DefaultTabSectionsData::get_default_sections_for_dnd();
                $has_defaults = true;
                update_option($this->storage_key, $sections);
            }

            // Ensure sections are properly ordered
            uasort($sections, function ($a, $b) {
                return ($a['order'] ?? 0) - ($b['order'] ?? 0);
            });

            // Convert to array values for consistent response
            $sections_array = array_values($sections);

            return rest_ensure_response([
                'success' => true,
                'data' => $sections_array,
                'has_defaults' => $has_defaults,
                'total_sections' => count($sections_array),
                'storage_key' => $this->storage_key
            ]);
        } catch (\Exception $e) {
            return new \WP_Error('fetch_failed', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Delete all sections
     */
    public function delete_all()
    {
        try {
            $result = delete_option($this->storage_key);
            
            return rest_ensure_response([
                'success' => true,
                'message' => 'All sections deleted successfully',
                'data' => [],
                'deleted' => $result
            ]);
        } catch (\Exception $e) {
            return new \WP_Error('delete_failed', $e->getMessage(), ['status' => 500]);
        }
    }

    // === Permission callbacks ===
    public function get_per()
    {
        return current_user_can('manage_options');
    }

    public function create_per()
    {
        return current_user_can('manage_options');
    }

    public function del_per()
    {
        return current_user_can('manage_options');
    }
}