<?php

namespace GriffinForms\Items;

class Form extends \GriffinForms\Items\Format
{
    protected $row_groups = array();
    protected $user_action;
    protected $autoresponder;
    protected $save_entries = 1;
    protected $limit_entries;
    protected $availability_window;
    protected $progress_bar;
    protected $lifetime_submission_count;
    protected $access_level;
    protected $submission_edit;
    protected $alert_emails = '';
    protected $notifications = null;
    protected $submit_method;
    protected $autofill;
    protected $formpages;
    protected $origin;
    protected $submit_label;
    protected $conditional_logic;
    protected $form_theme;
    protected $has_payment_field = null;
    protected $compliance_mode;
    protected $compliance_profile;
    protected $compliance_flags;
    protected $layout_version;
    protected $layout_hash;
    
    protected function setAutofill()
    {
        $this->autofill = 1;
    }

    protected function setComplianceMode()
    {
        $this->compliance_mode = 0;
    }

    protected function setComplianceProfile()
    {
        $this->compliance_profile = 'standard';
    }

    protected function setComplianceFlags()
    {
        $this->compliance_flags = array(
            'mode' => 'inherit',
            'store_ip' => 0,
            'store_user_agent' => 0,
            'retention_days' => 0
        );
    }

    protected function setLayoutVersion()
    {
        $this->layout_version = 0;
    }

    protected function setLayoutHash()
    {
        $this->layout_hash = '';
    }
    
    protected function setLimitEntries()
    {
        $this->limit_entries = array(
            'toggle' => false,
            'limit' => 100,
            'message' => ''
        );
    }

    protected function setAvailabilityWindow()
    {
        $this->availability_window = array(
            'toggle' => false,
            'start_utc' => '',
            'end_utc' => '',
            'pre_message' => '',
            'post_message' => ''
        );
    }

    protected function setProgressBar()
    {
        $this->progress_bar = array(
            'toggle' => false,
            'style' => 'stepper',
            'show_page_headings' => true
        );
    }

    protected function setLifetimeSubmissionCount()
    {
        $this->lifetime_submission_count = 0;
    }
    
    protected function setAccessLevel()
    {
        $this->access_level = array(
            'access' => 'public_access',
            'role_access' => false,
            'roles' => ''
        );
    }

    protected function setSubmissionEdit()
    {
        $this->submission_edit = array(
            'toggle' => false,
            'original_submitters' => false,
            'email_owners' => false,
            'role_access' => false,
            'user_access' => false,
            'email_fields' => array(),
            'roles' => array(),
            'users' => array(),
            'max_edits' => 0,
            'time' => array(
                'mode' => 'none',
                'start_ts' => 0,
                'end_ts' => 0,
                'duration_days' => 0,
                'duration_hours' => 0,
                'pre_message' => '',
                'post_message' => '',
            ),
        );
    }
    
    protected function setUserAction()
    {
        $this->user_action = array(
            'type' => 'do_nothing',
            'message' => '',
            'url' => ''
        );
    }
    
    protected function setFormStyle()
    {
        $this->form_style = 0;
    }

    protected function setConditionalLogic()
    {
        $this->conditional_logic = [
            'all' => [
                ['item' => 'field', 'item_id' => '2', 'attribute' => 'value', 'evaluator' => 'greater_than', 'input' => '5']
            ],
            'any' => [],
            'actions' => [
                ['item' => 'field', 'item_id' => '5', 'attribute' => 'value', 'action' => 'set', 'input' => '10']
            ]
        ];
    }

    public function getRulesCount() {
        if (empty($this->conditional_logic) || !is_array($this->conditional_logic)) {
            return 0;
        }
        return count($this->conditional_logic);
    }

    public function getFormTheme()
    {
        return $this->form_theme;
    }

    /**
     * Return all field IDs within this form, or fetch specific columns for those fields.
     *
     * @param array $columns
     * @return array
     */
    public function getFormFields(array $columns = array()): array
    {
        $field_ids = $this->collectFieldIds();

        if (empty($field_ids)) {
            return array();
        }

        if (empty($columns)) {
            return $field_ids;
        }

        $columns = array_values(array_filter(array_map('sanitize_key', $columns)));
        if (empty($columns)) {
            return $field_ids;
        }

        if (!in_array('id', $columns, true)) {
            $columns[] = 'id';
        }

        global $wpdb;
        $table = $this->config->getTable('field');

        if (empty($table)) {
            return array();
        }

        $select_columns = implode(',', array_map(static function ($column) {
            return '`' . esc_sql($column) . '`';
        }, $columns));

        $placeholders = implode(',', array_fill(0, count($field_ids), '%d'));
        $order_clause = implode(',', array_map('intval', $field_ids));

        $sql = "SELECT {$select_columns} FROM {$table} WHERE id IN ($placeholders)";
        if (!empty($order_clause)) {
            $sql .= " ORDER BY FIELD(id, {$order_clause})";
        }

        $results = $wpdb->get_results(
            $wpdb->prepare($sql, $field_ids),
            ARRAY_A
        );

        return $results ? $results : array();
    }

    /**
     * Determine if this form contains at least one payment field.
     *
     * @return bool
     */
    public function hasPaymentField(): bool
    {
        if ($this->has_payment_field !== null) {
            return (bool) $this->has_payment_field;
        }

        $fields = $this->getFormFields(array('field_type'));
        foreach ($fields as $field) {
            $type = isset($field['field_type']) ? strtolower((string) $field['field_type']) : '';
            if ($type === 'payment') {
                $this->has_payment_field = true;
                return true;
            }
        }

        $this->has_payment_field = false;
        return false;
    }

    /**
     * Collect raw field IDs from the loaded form structure.
     *
     * @return array
     */
    protected function collectFieldIds(): array
    {
        if (!$this->isLoaded()) {
            return array();
        }

        $page_ids = $this->getProp('formpages');
        if (empty($page_ids) || !is_array($page_ids)) {
            return array();
        }

        $field_ids = array();

        foreach ($page_ids as $page_id) {
            $page_item = new \GriffinForms\Items\FormPage();
            if (!$page_item->loadItem($page_id)) {
                continue;
            }

            $row_ids = $page_item->getProp('pagerows');
            if (empty($row_ids) || !is_array($row_ids)) {
                continue;
            }

            foreach ($row_ids as $row_id) {
                $row_item = new \GriffinForms\Items\PageRow();
                if (!$row_item->loadItem($row_id)) {
                    continue;
                }

                $column_ids = $row_item->getProp('rowcolumns');
                if (empty($column_ids) || !is_array($column_ids)) {
                    continue;
                }

                foreach ($column_ids as $column_id) {
                    $column_item = new \GriffinForms\Items\RowColumn();
                    if (!$column_item->loadItem($column_id)) {
                        continue;
                    }

                    $column_fields = $column_item->getProp('fields');
                    if (empty($column_fields) || !is_array($column_fields)) {
                        continue;
                    }

                    foreach ($column_fields as $field_id) {
                        $field_ids[] = absint($field_id);
                    }
                }
            }
        }

        return array_values(array_filter(array_unique($field_ids)));
    }
}
