<?php

namespace GriffinForms\Includes\ImportExport;

class FormExport extends \GriffinForms\Includes\ImportExport\Format
{
    protected $form_id;
    protected $default_step_data = array(
        'step_name' => '',
        'step_icon' => '',
    );

    public function __construct($form_id) {
        $this->form_id = $form_id;
        $this->setAll();
    }

    // Fetch the form data based on form ID
    public function getFormData() {
        global $wpdb;
        $table = $this->config->getTable('form');
        $form = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $table, $this->form_id), ARRAY_A);
            
        if (!$form) {
            return null;
        }
    
        $form['formpages'] = !empty($form['formpages']) ? $this->maybeDecode($form['formpages']) : [];
        $form['conditional_logic'] = !empty($form['conditional_logic']) ? $this->maybeDecode($form['conditional_logic']) : [];
        $form['pages'] = $this->getPages($form['formpages']);
    
        $json_data = json_encode($form);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->log->add(
                'error',                              // log_type
                'form',                               // item_type
                $this->form_id,                       // item_id
                get_current_user_id(),               // user_id
                'JSON encoding error: ' . json_last_error_msg(), // message
                'json_encoding'                       // category
            );            return null;
        }
    
        return $form;
    }

    // Unserialize fields if they are serialized strings
    protected function unserializeFields($data, $fields) {
        foreach ($fields as $field) {
            if (!empty($data[$field]) && is_string($data[$field]) && is_serialized($data[$field])) {
                $data[$field] = $this->maybeDecode($data[$field]);
            }
        }
        return $data;
    }

    // Get all pages related to the form
    protected function getPages($formpages) {
        global $wpdb;
        $table = $this->config->getTable('formpage');
        $pages = [];

        if (!is_array($formpages)) {
            return $pages;
        }

        foreach ($formpages as $page_id) {
            $page = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $table, $page_id), ARRAY_A);
            
            if ($page) {
                $page = $this->unserializeFields($page, ['pagerows', 'step_data']);
                $page['step_data'] = $this->normalizeStepData($page['step_data'] ?? null);
                $page['rows'] = $this->getRows($page['pagerows']);
                $pages[] = $page;
            }
        }
        return $pages;
    }

    // Get all rows related to the page
    protected function getRows($pagerows) {
        global $wpdb;
        $table = $this->config->getTable('pagerow');
        $rows = [];

        if (!is_array($pagerows)) {
            return $rows;
        }

        foreach ($pagerows as $row_id) {
            $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $table, $row_id), ARRAY_A);

            if ($row) {
                $row = $this->unserializeFields($row, ['rowcolumns']);
                $row['columns'] = $this->getColumns($row['rowcolumns']);
                $rows[] = $row;
            }
        }
        return $rows;
    }

    // Get all columns related to the row
    protected function getColumns($rowcolumns) {
        global $wpdb;
        $table = $this->config->getTable('rowcolumn');
        $columns = [];

        if (!is_array($rowcolumns)) {
            return $columns;
        }

        foreach ($rowcolumns as $column_id) {
            $column = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $table, $column_id), ARRAY_A);

            if ($column) {
                $column = $this->unserializeFields($column, ['fields']);
                $column['field_data'] = $this->getFields($column['fields']);
                $columns[] = $column;
            }
        }
        return $columns;
    }

    // Get all fields related to the column
    protected function getFields($field_ids) {
        global $wpdb;
        $table = $this->config->getTable('field');
        $fields = [];

        if (!is_array($field_ids)) {
            return $fields;
        }

        foreach ($field_ids as $field_id) {
            $field = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $table, $field_id), ARRAY_A);

            if ($field) {
                $field = $this->unserializeFields($field, [
                    'field_options',
                    'default_value',
                    'iterations',
                    'validations',
                    'field_settings'
                ]);
                $fields[] = $field;
            }
        }
        return $fields;
    }

    protected function normalizeStepData($value): array
    {
        if (!is_array($value)) {
            return $this->default_step_data;
        }

        return array(
            'step_name' => isset($value['step_name']) ? sanitize_text_field($value['step_name']) : '',
            'step_icon' => isset($value['step_icon']) ? sanitize_text_field($value['step_icon']) : '',
        );
    }
}
