<?php
/**
 * Forms Controller
 *
 * @package Freelance_Studio
 */

class FS_Forms_Controller {

    /**
     * Handle the request
     */
    public function handle_request() {
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : 'list';
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handle_post();
            return;
        }

        switch ($action) {
            case 'add':
                $this->add();
                break;
            case 'edit':
                $this->edit($id);
                break;
            case 'responses':
                $this->responses($id);
                break;
            case 'view-response':
                $this->view_response($id);
                break;
            case 'duplicate':
                $this->duplicate($id);
                break;
            case 'export':
                $this->export($id);
                break;
            case 'templates':
                $this->templates();
                break;
            case 'add-template':
                $this->add_template();
                break;
            case 'edit-template':
                $this->edit_template($id);
                break;
            case 'use-template':
                $this->use_template($id);
                break;
            case 'save-as-template':
                $this->save_as_template($id);
                break;
            default:
                $this->index();
                break;
        }
    }

    /**
     * Handle POST requests
     */
    private function handle_post() {
        // Handle template actions
        if (isset($_POST['template_action'])) {
            $this->handle_template_post();
            return;
        }
        
        if (!isset($_POST['fs_form_nonce']) || !wp_verify_nonce($_POST['fs_form_nonce'], 'fs_save_form')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }

        $action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        $id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;

        // Parse fields from form
        $fields = array();
        if (isset($_POST['fields']) && is_array($_POST['fields'])) {
            foreach ($_POST['fields'] as $index => $field) {
                $field_data = array(
                    'id' => sanitize_text_field($field['id']),
                    'type' => sanitize_text_field($field['type']),
                    'label' => sanitize_text_field($field['label']),
                    'required' => isset($field['required']) ? 1 : 0,
                    'placeholder' => isset($field['placeholder']) ? sanitize_text_field($field['placeholder']) : '',
                    'help_text' => isset($field['help_text']) ? sanitize_text_field($field['help_text']) : '',
                    'order' => intval($index),
                );
                
                // Type-specific options
                if (in_array($field['type'], array('single_choice', 'multiple_choice', 'dropdown'))) {
                    $options = array();
                    if (isset($field['options']) && is_array($field['options'])) {
                        foreach ($field['options'] as $opt) {
                            if (!empty($opt)) {
                                $options[] = sanitize_text_field($opt);
                            }
                        }
                    }
                    $field_data['options'] = $options;
                }
                
                // Scale options
                if ($field['type'] === 'scale') {
                    $field_data['min'] = isset($field['min']) ? intval($field['min']) : 1;
                    $field_data['max'] = isset($field['max']) ? intval($field['max']) : 10;
                    $field_data['min_label'] = isset($field['min_label']) ? sanitize_text_field($field['min_label']) : '';
                    $field_data['max_label'] = isset($field['max_label']) ? sanitize_text_field($field['max_label']) : '';
                }
                
                // File upload options
                if ($field['type'] === 'file_upload') {
                    $field_data['allowed_types'] = isset($field['allowed_types']) ? sanitize_text_field($field['allowed_types']) : 'pdf,doc,docx,jpg,png';
                    $field_data['max_size'] = isset($field['max_size']) ? intval($field['max_size']) : 10;
                }
                
                // File download options
                if ($field['type'] === 'file_download') {
                    $field_data['file_id'] = isset($field['file_id']) ? intval($field['file_id']) : 0;
                    $field_data['file_url'] = isset($field['file_url']) ? esc_url_raw($field['file_url']) : '';
                    $field_data['file_name'] = isset($field['file_name']) ? sanitize_text_field($field['file_name']) : '';
                }
                
                // Content for headings/paragraphs
                if (in_array($field['type'], array('heading', 'paragraph'))) {
                    $field_data['content'] = isset($field['content']) ? wp_kses_post($field['content']) : '';
                }
                
                // Conditional logic
                if (!empty($field['conditional_logic']['enabled'])) {
                    $rules = array();
                    if (isset($field['conditional_logic']['rules']) && is_array($field['conditional_logic']['rules'])) {
                        foreach ($field['conditional_logic']['rules'] as $rule) {
                            if (!empty($rule['field_id'])) {
                                $rules[] = array(
                                    'field_id' => sanitize_text_field($rule['field_id']),
                                    'operator' => sanitize_text_field($rule['operator'] ?? 'equals'),
                                    'value' => sanitize_text_field($rule['value'] ?? ''),
                                );
                            }
                        }
                    }
                    
                    if (!empty($rules)) {
                        $field_data['conditional_logic'] = array(
                            'enabled' => 1,
                            'action' => sanitize_text_field($field['conditional_logic']['action'] ?? 'show'),
                            'logic' => sanitize_text_field($field['conditional_logic']['logic'] ?? 'all'),
                            'rules' => $rules,
                        );
                    }
                }
                
                $fields[] = $field_data;
            }
        }

        // Parse settings
        $settings = array(
            'submit_button_text' => isset($_POST['settings']['submit_button_text']) ? sanitize_text_field(wp_unslash($_POST['settings'])['submit_button_text']) : __('Submit', 'freelance-studio'),
            'success_message' => isset($_POST['settings']['success_message']) ? sanitize_textarea_field(wp_unslash($_POST['settings'])['success_message']) : __('Thank you for your submission!', 'freelance-studio'),
            'notification_email' => isset($_POST['settings']['notification_email']) ? sanitize_email(wp_unslash($_POST['settings'])['notification_email']) : '',
            'max_responses' => isset($_POST['settings']['max_responses']) ? intval($_POST['settings']['max_responses']) : 0,
            'close_date' => isset($_POST['settings']['close_date']) ? sanitize_text_field(wp_unslash($_POST['settings'])['close_date']) : '',
            'show_in_portal' => isset($_POST['settings']['show_in_portal']) ? 1 : 0,
        );

        $data = array(
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'description' => sanitize_textarea_field(wp_unslash($_POST['description'] ?? '')),
            'project_id' => !empty($_POST['project_id']) ? intval($_POST['project_id']) : null,
            'client_id' => !empty($_POST['client_id']) ? intval($_POST['client_id']) : null,
            'status' => sanitize_text_field(wp_unslash($_POST['status'] ?? 'draft')),
            'fields' => $fields,
            'settings' => $settings,
        );

        if ($action === 'update' && $id) {
            $result = FS_Form::update($id, $data);
            $message = $result !== false ? 'updated' : 'error';
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit&id=' . $id . '&message=' . $message));
        } else {
            $form_id = FS_Form::create($data);
            if ($form_id) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit&id=' . $form_id . '&message=created'));
            } else {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=add&message=error'));
            }
        }
        exit;
    }

    /**
     * List all forms
     */
    public function index() {
        $status_filter = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : null;
        $client_filter = isset($_GET['client_id']) ? intval($_GET['client_id']) : null;
        
        $args = array();
        if ($status_filter) {
            $args['status'] = $status_filter;
        }
        if ($client_filter) {
            $args['client_id'] = $client_filter;
        }
        
        $forms = FS_Form::get_all($args);
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Form::get_statuses();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Form created successfully.', 'freelance-studio'),
            'updated' => __('Form updated successfully.', 'freelance-studio'),
            'deleted' => __('Form deleted successfully.', 'freelance-studio'),
            'duplicated' => __('Form duplicated successfully.', 'freelance-studio'),
            'response_deleted' => __('Response deleted successfully.', 'freelance-studio'),
            'error' => __('An error occurred. Please try again.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/list.php';
    }

    /**
     * Add new form
     */
    public function add() {
        $form = null;
        $clients = FS_Client::get_for_dropdown();
        $projects = FS_Project::get_all(array('status' => array('pending', 'active')));
        $statuses = FS_Form::get_statuses();
        $question_types = FS_Form::get_question_types();
        $is_new = true;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        // Pre-select client/project if passed in URL
        $selected_client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
        $selected_project_id = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/form.php';
    }

    /**
     * Edit form
     */
    public function edit($id) {
        $form = FS_Form::get($id);
        
        if (!$form) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=not_found'));
            exit;
        }
        
        $clients = FS_Client::get_for_dropdown();
        $projects = FS_Project::get_all(array('status' => array('pending', 'active')));
        $statuses = FS_Form::get_statuses();
        $question_types = FS_Form::get_question_types();
        $is_new = false;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        $response_count = FS_Form_Response::count(array('form_id' => $id));
        
        $messages = array(
            'created' => __('Form created successfully.', 'freelance-studio'),
            'updated' => __('Form updated successfully.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/form.php';
    }

    /**
     * View form responses
     */
    public function responses($id) {
        $form = FS_Form::get($id);
        
        if (!$form) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=not_found'));
            exit;
        }
        
        $responses = FS_Form_Response::get_by_form($id);
        $stats = FS_Form_Response::get_stats($id);
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/responses.php';
    }

    /**
     * View single response
     */
    public function view_response($id) {
        $response = FS_Form_Response::get($id);
        
        if (!$response) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=not_found'));
            exit;
        }
        
        $form = FS_Form::get($response->form_id);
        
        if (!$form) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=not_found'));
            exit;
        }
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/view-response.php';
    }

    /**
     * Duplicate form
     */
    public function duplicate($id) {
        $new_id = FS_Form::duplicate($id);
        
        if ($new_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit&id=' . $new_id . '&message=duplicated'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=error'));
        }
        exit;
    }

    /**
     * Export responses to CSV
     */
    public function export($id) {
        $form = FS_Form::get($id);
        
        if (!$form) {
            wp_die(esc_html__('Form not found', 'freelance-studio'));
        }
        
        $csv = FS_Form_Response::export_csv($id);
        
        if (empty($csv)) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=responses&id=' . $id . '&message=no_responses'));
            exit;
        }
        
        $filename = sanitize_file_name($form->name) . '-responses-' . gmdate('Y-m-d') . '.csv';
        
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Raw CSV data output with proper Content-Type header
        echo $csv;
        exit;
    }

    /**
     * List templates
     */
    public function templates() {
        $templates = FS_Form_Template::get_grouped_by_category();
        $categories = FS_Form_Template::get_categories();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Template created successfully.', 'freelance-studio'),
            'updated' => __('Template updated successfully.', 'freelance-studio'),
            'deleted' => __('Template deleted successfully.', 'freelance-studio'),
            'error' => __('An error occurred. Please try again.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/templates.php';
    }

    /**
     * Add new template
     */
    public function add_template() {
        $template = null;
        $categories = FS_Form_Template::get_categories();
        $is_new = true;
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/template-form.php';
    }

    /**
     * Edit template
     */
    public function edit_template($id) {
        $template = FS_Form_Template::get($id);
        
        if (!$template) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=templates&message=not_found'));
            exit;
        }
        
        $categories = FS_Form_Template::get_categories();
        $is_new = false;
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/template-form.php';
    }

    /**
     * Create form from template
     */
    public function use_template($id) {
        $template = FS_Form_Template::get($id);
        
        if (!$template) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=templates&message=not_found'));
            exit;
        }
        
        $form_id = FS_Form_Template::create_form_from_template($id);
        
        if ($form_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit&id=' . $form_id . '&message=created'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=templates&message=error'));
        }
        exit;
    }

    /**
     * Save form as template
     */
    public function save_as_template($id) {
        $form = FS_Form::get($id);
        
        if (!$form) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&message=not_found'));
            exit;
        }
        
        // Show the save as template form
        $categories = FS_Form_Template::get_categories();
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/forms/save-as-template.php';
    }

    /**
     * Handle template POST actions
     */
    private function handle_template_post() {
        if (!isset($_POST['fs_template_nonce']) || !wp_verify_nonce($_POST['fs_template_nonce'], 'fs_save_template')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $action = sanitize_text_field(wp_unslash($_POST['template_action']));
        $id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
        
        if ($action === 'save_as_template') {
            // Save form as template
            $form_id = intval($_POST['form_id']);
            $template_data = array(
                'name' => sanitize_text_field(wp_unslash($_POST['name'])),
                'description' => sanitize_textarea_field(wp_unslash($_POST['description'] ?? '')),
                'category' => sanitize_text_field(wp_unslash($_POST['category'] ?? 'other')),
            );
            
            $template_id = FS_Form_Template::save_form_as_template($form_id, $template_data);
            
            if ($template_id) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=templates&message=created'));
            } else {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=save-as-template&id=' . $form_id . '&message=error'));
            }
            exit;
        }
        
        if ($action === 'delete_template') {
            $result = FS_Form_Template::delete($id);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=templates&message=' . ($result ? 'deleted' : 'error')));
            exit;
        }
        
        // Parse template fields (same as form fields)
        $fields = array();
        if (isset($_POST['fields']) && is_array($_POST['fields'])) {
            foreach ($_POST['fields'] as $index => $field) {
                $field_data = array(
                    'id' => sanitize_text_field($field['id']),
                    'type' => sanitize_text_field($field['type']),
                    'label' => sanitize_text_field($field['label']),
                    'required' => isset($field['required']) ? 1 : 0,
                    'placeholder' => isset($field['placeholder']) ? sanitize_text_field($field['placeholder']) : '',
                    'help_text' => isset($field['help_text']) ? sanitize_text_field($field['help_text']) : '',
                    'order' => intval($index),
                );
                
                // Type-specific options
                if (in_array($field['type'], array('single_choice', 'multiple_choice', 'dropdown'))) {
                    $options = array();
                    if (isset($field['options']) && is_array($field['options'])) {
                        foreach ($field['options'] as $opt) {
                            if (!empty($opt)) {
                                $options[] = sanitize_text_field($opt);
                            }
                        }
                    }
                    $field_data['options'] = $options;
                }
                
                if ($field['type'] === 'scale') {
                    $field_data['min'] = isset($field['min']) ? intval($field['min']) : 1;
                    $field_data['max'] = isset($field['max']) ? intval($field['max']) : 10;
                    $field_data['min_label'] = isset($field['min_label']) ? sanitize_text_field($field['min_label']) : '';
                    $field_data['max_label'] = isset($field['max_label']) ? sanitize_text_field($field['max_label']) : '';
                }
                
                if ($field['type'] === 'file_upload') {
                    $field_data['allowed_types'] = isset($field['allowed_types']) ? sanitize_text_field($field['allowed_types']) : 'pdf,doc,docx,jpg,png';
                    $field_data['max_size'] = isset($field['max_size']) ? intval($field['max_size']) : 10;
                }
                
                if (in_array($field['type'], array('heading', 'paragraph'))) {
                    $field_data['content'] = isset($field['content']) ? wp_kses_post($field['content']) : '';
                }
                
                // Conditional logic
                if (!empty($field['conditional_logic']['enabled'])) {
                    $rules = array();
                    if (isset($field['conditional_logic']['rules']) && is_array($field['conditional_logic']['rules'])) {
                        foreach ($field['conditional_logic']['rules'] as $rule) {
                            if (!empty($rule['field_id'])) {
                                $rules[] = array(
                                    'field_id' => sanitize_text_field($rule['field_id']),
                                    'operator' => sanitize_text_field($rule['operator'] ?? 'equals'),
                                    'value' => sanitize_text_field($rule['value'] ?? ''),
                                );
                            }
                        }
                    }
                    
                    if (!empty($rules)) {
                        $field_data['conditional_logic'] = array(
                            'enabled' => 1,
                            'action' => sanitize_text_field($field['conditional_logic']['action'] ?? 'show'),
                            'logic' => sanitize_text_field($field['conditional_logic']['logic'] ?? 'all'),
                            'rules' => $rules,
                        );
                    }
                }
                
                $fields[] = $field_data;
            }
        }
        
        $settings = array(
            'submit_button_text' => isset($_POST['settings']['submit_button_text']) ? sanitize_text_field(wp_unslash($_POST['settings'])['submit_button_text']) : __('Submit', 'freelance-studio'),
            'success_message' => isset($_POST['settings']['success_message']) ? sanitize_textarea_field(wp_unslash($_POST['settings'])['success_message']) : __('Thank you!', 'freelance-studio'),
        );
        
        $data = array(
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'description' => sanitize_textarea_field(wp_unslash($_POST['description'] ?? '')),
            'category' => sanitize_text_field(wp_unslash($_POST['category'] ?? 'other')),
            'fields' => $fields,
            'settings' => $settings,
        );
        
        if ($action === 'update_template' && $id) {
            $result = FS_Form_Template::update($id, $data);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit-template&id=' . $id . '&message=' . ($result !== false ? 'updated' : 'error')));
        } else {
            $template_id = FS_Form_Template::create($data);
            if ($template_id) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=edit-template&id=' . $template_id . '&message=created'));
            } else {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-forms&action=add-template&message=error'));
            }
        }
        exit;
    }
}
