<?php
/**
 * Form Template Model
 *
 * @package Freelance_Studio
 */

class FS_Form_Template {

    /**
     * Template category constants
     */
    const CATEGORY_CLIENT = 'client';
    const CATEGORY_PROJECT = 'project';
    const CATEGORY_FEEDBACK = 'feedback';
    const CATEGORY_INTAKE = 'intake';
    const CATEGORY_OTHER = 'other';

    /**
     * Create a new form template
     *
     * @param array $data Template data
     * @return int|false Insert ID or false on failure
     */
    public static function create($data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        $result = $wpdb->insert(
            $table,
            array(
                'name' => sanitize_text_field($data['name']),
                'description' => isset($data['description']) ? sanitize_textarea_field($data['description']) : '',
                'category' => isset($data['category']) ? sanitize_text_field($data['category']) : self::CATEGORY_OTHER,
                'fields' => isset($data['fields']) ? wp_json_encode($data['fields']) : '[]',
                'settings' => isset($data['settings']) ? wp_json_encode($data['settings']) : '{}',
                'is_default' => isset($data['is_default']) ? intval($data['is_default']) : 0,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql'),
            ),
            array('%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s')
        );
        
        if ($result === false) {
            error_log('FS_Form_Template::create failed: ' . $wpdb->last_error);
            return false;
        }
        
        return $wpdb->insert_id;
    }

    /**
     * Get a template by ID
     *
     * @param int $id Template ID
     * @return object|null
     */
    public static function get($id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        $template = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d",
            $id
        ));
        
        if ($template) {
            $template->fields = json_decode($template->fields ?? '', true) ?: array();
            $template->settings = json_decode($template->settings ?? '', true) ?: array();
        }
        
        return $template;
    }

    /**
     * Get all templates
     *
     * @param array $args Query arguments
     * @return array
     */
    public static function get_all($args = array()) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        $defaults = array(
            'category' => '',
            'is_default' => null,
            'orderby' => 'name',
            'order' => 'ASC',
            'limit' => 100,
            'offset' => 0,
        );
        
        $args = wp_parse_args($args, $defaults);
        
        $where = array('1=1');
        $values = array();
        
        if (!empty($args['category'])) {
            $where[] = 'category = %s';
            $values[] = $args['category'];
        }
        
        if ($args['is_default'] !== null) {
            $where[] = 'is_default = %d';
            $values[] = intval($args['is_default']);
        }
        
        $where_clause = implode(' AND ', $where);
        $orderby = sanitize_sql_orderby($args['orderby'] . ' ' . $args['order']) ?: 'name ASC';
        
        $sql = "SELECT * FROM {$table} WHERE {$where_clause} ORDER BY {$orderby} LIMIT %d OFFSET %d";
        
        $values[] = $args['limit'];
        $values[] = $args['offset'];
        
        if (!empty($values)) {
            $sql = $wpdb->prepare($sql, $values); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
        }
        
        $results = $wpdb->get_results($sql); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
        
        foreach ($results as &$template) {
            $template->fields = json_decode($template->fields ?? '', true) ?: array();
            $template->settings = json_decode($template->settings ?? '', true) ?: array();
        }
        
        return $results;
    }

    /**
     * Get templates for dropdown
     *
     * @return array
     */
    public static function get_for_dropdown() {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        return $wpdb->get_results(
            "SELECT id, name, category, description FROM {$table} ORDER BY category ASC, name ASC"
        );
    }

    /**
     * Get templates grouped by category
     *
     * @return array
     */
    public static function get_grouped_by_category() {
        $templates = self::get_all();
        $grouped = array();
        
        foreach ($templates as $template) {
            $category = $template->category ?: self::CATEGORY_OTHER;
            if (!isset($grouped[$category])) {
                $grouped[$category] = array();
            }
            $grouped[$category][] = $template;
        }
        
        return $grouped;
    }

    /**
     * Update a template
     *
     * @param int   $id   Template ID
     * @param array $data Template data
     * @return int|false
     */
    public static function update($id, $data) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        $update_data = array(
            'updated_at' => current_time('mysql'),
        );
        
        if (isset($data['name'])) {
            $update_data['name'] = sanitize_text_field($data['name']);
        }
        
        if (isset($data['description'])) {
            $update_data['description'] = sanitize_textarea_field($data['description']);
        }
        
        if (isset($data['category'])) {
            $update_data['category'] = sanitize_text_field($data['category']);
        }
        
        if (isset($data['fields'])) {
            $update_data['fields'] = wp_json_encode($data['fields']);
        }
        
        if (isset($data['settings'])) {
            $update_data['settings'] = wp_json_encode($data['settings']);
        }
        
        if (isset($data['is_default'])) {
            $update_data['is_default'] = intval($data['is_default']);
        }
        
        return $wpdb->update(
            $table,
            $update_data,
            array('id' => $id),
            null,
            array('%d')
        );
    }

    /**
     * Delete a template
     *
     * @param int $id Template ID
     * @return int|false
     */
    public static function delete($id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        return $wpdb->delete($table, array('id' => $id), array('%d'));
    }

    /**
     * Create form from template
     *
     * @param int   $template_id Template ID
     * @param array $form_data   Additional form data
     * @return int|false Form ID or false on failure
     */
    public static function create_form_from_template($template_id, $form_data = array()) {
        $template = self::get($template_id);
        
        if (!$template) {
            return false;
        }
        
        // Regenerate field IDs to ensure uniqueness
        $fields = self::regenerate_field_ids($template->fields);
        
        $data = array(
            'name' => isset($form_data['name']) ? $form_data['name'] : $template->name,
            'description' => isset($form_data['description']) ? $form_data['description'] : $template->description,
            'fields' => $fields,
            'settings' => $template->settings,
            'status' => FS_Form::STATUS_DRAFT,
            'client_id' => isset($form_data['client_id']) ? $form_data['client_id'] : null,
            'project_id' => isset($form_data['project_id']) ? $form_data['project_id'] : null,
        );
        
        return FS_Form::create($data);
    }

    /**
     * Save form as template
     *
     * @param int   $form_id Form ID
     * @param array $template_data Template metadata
     * @return int|false Template ID or false on failure
     */
    public static function save_form_as_template($form_id, $template_data = array()) {
        $form = FS_Form::get($form_id);
        
        if (!$form) {
            return false;
        }
        
        $data = array(
            'name' => isset($template_data['name']) ? $template_data['name'] : $form->name . ' (Template)',
            'description' => isset($template_data['description']) ? $template_data['description'] : $form->description,
            'category' => isset($template_data['category']) ? $template_data['category'] : self::CATEGORY_OTHER,
            'fields' => $form->fields,
            'settings' => $form->settings,
            'is_default' => isset($template_data['is_default']) ? $template_data['is_default'] : 0,
        );
        
        return self::create($data);
    }

    /**
     * Regenerate field IDs to ensure uniqueness
     *
     * @param array $fields Field array
     * @return array Fields with new IDs
     */
    private static function regenerate_field_ids($fields) {
        $id_map = array();
        
        // First pass: generate new IDs and build mapping
        foreach ($fields as &$field) {
            $old_id = $field['id'];
            $new_id = 'field_' . uniqid();
            $id_map[$old_id] = $new_id;
            $field['id'] = $new_id;
        }
        
        // Second pass: update conditional logic references
        foreach ($fields as &$field) {
            if (!empty($field['conditional_logic']['rules'])) {
                foreach ($field['conditional_logic']['rules'] as &$rule) {
                    if (isset($rule['field_id']) && isset($id_map[$rule['field_id']])) {
                        $rule['field_id'] = $id_map[$rule['field_id']];
                    }
                }
            }
        }
        
        return $fields;
    }

    /**
     * Get available categories
     *
     * @return array
     */
    public static function get_categories() {
        return array(
            self::CATEGORY_CLIENT => __('Client Onboarding', 'freelance-studio'),
            self::CATEGORY_PROJECT => __('Project Intake', 'freelance-studio'),
            self::CATEGORY_FEEDBACK => __('Feedback & Reviews', 'freelance-studio'),
            self::CATEGORY_INTAKE => __('General Intake', 'freelance-studio'),
            self::CATEGORY_OTHER => __('Other', 'freelance-studio'),
        );
    }

    /**
     * Install default templates
     *
     * @return void
     */
    public static function install_defaults() {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_form_templates';
        
        // Check if defaults already installed
        $existing = $wpdb->get_var("SELECT COUNT(*) FROM {$table} WHERE is_default = 1");
        if ($existing > 0) {
            return;
        }
        
        $defaults = self::get_default_templates();
        
        foreach ($defaults as $template) {
            self::create($template);
        }
    }

    /**
     * Get default template definitions
     *
     * @return array
     */
    private static function get_default_templates() {
        return array(
            array(
                'name' => __('Client Onboarding Questionnaire', 'freelance-studio'),
                'description' => __('Gather essential information from new clients to kickstart your project.', 'freelance-studio'),
                'category' => self::CATEGORY_CLIENT,
                'is_default' => 1,
                'fields' => array(
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('About Your Business', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'short_text',
                        'label' => __('Company/Organization Name', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('Describe your business in a few sentences', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'url',
                        'label' => __('Current Website (if any)', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'single_choice',
                        'label' => __('What industry are you in?', 'freelance-studio'),
                        'options' => array('Technology', 'Healthcare', 'Finance', 'Retail', 'Education', 'Non-profit', 'Other'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('Project Goals', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('What are your main goals for this project?', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('Who is your target audience?', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'multiple_choice',
                        'label' => __('What services are you interested in?', 'freelance-studio'),
                        'options' => array('Logo Design', 'Website Design', 'Website Development', 'Branding', 'Print Design', 'Marketing Materials'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('Timeline & Budget', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'dropdown',
                        'label' => __('What is your timeline?', 'freelance-studio'),
                        'options' => array('ASAP', '1-2 weeks', '1 month', '2-3 months', 'Flexible'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'dropdown',
                        'label' => __('What is your approximate budget?', 'freelance-studio'),
                        'options' => array('Under $1,000', '$1,000 - $5,000', '$5,000 - $10,000', '$10,000 - $25,000', '$25,000+'),
                        'required' => true,
                    ),
                ),
                'settings' => array(
                    'submit_button_text' => __('Submit', 'freelance-studio'),
                    'success_message' => __('Thank you for your submission! We\'ll be in touch soon.', 'freelance-studio'),
                ),
            ),
            array(
                'name' => __('Project Feedback Form', 'freelance-studio'),
                'description' => __('Collect client feedback after project completion.', 'freelance-studio'),
                'category' => self::CATEGORY_FEEDBACK,
                'is_default' => 1,
                'fields' => array(
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'paragraph',
                        'label' => __('Thank you for working with us! Please take a moment to share your feedback.', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'scale',
                        'label' => __('Overall, how satisfied are you with the project outcome?', 'freelance-studio'),
                        'scale_min' => 1,
                        'scale_max' => 10,
                        'scale_min_label' => __('Not satisfied', 'freelance-studio'),
                        'scale_max_label' => __('Extremely satisfied', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'scale',
                        'label' => __('How would you rate our communication throughout the project?', 'freelance-studio'),
                        'scale_min' => 1,
                        'scale_max' => 10,
                        'scale_min_label' => __('Poor', 'freelance-studio'),
                        'scale_max_label' => __('Excellent', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'scale',
                        'label' => __('How likely are you to recommend our services to others?', 'freelance-studio'),
                        'scale_min' => 1,
                        'scale_max' => 10,
                        'scale_min_label' => __('Not likely', 'freelance-studio'),
                        'scale_max_label' => __('Very likely', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('What did you like most about working with us?', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('What could we improve for future projects?', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'yes_no',
                        'label' => __('Would you be willing to provide a testimonial we can use on our website?', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('Any additional comments?', 'freelance-studio'),
                        'required' => false,
                    ),
                ),
                'settings' => array(
                    'submit_button_text' => __('Submit Feedback', 'freelance-studio'),
                    'success_message' => __('Thank you for your feedback! We truly appreciate it.', 'freelance-studio'),
                ),
            ),
            array(
                'name' => __('Website Design Brief', 'freelance-studio'),
                'description' => __('Detailed questionnaire for website design projects.', 'freelance-studio'),
                'category' => self::CATEGORY_PROJECT,
                'is_default' => 1,
                'fields' => array(
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('Current Website', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'yes_no',
                        'label' => __('Do you have an existing website?', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'url',
                        'label' => __('Current website URL', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('What do you like and dislike about your current site?', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('Design Preferences', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('List 3-5 websites you like and explain what you like about them', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'multiple_choice',
                        'label' => __('What style best describes your brand?', 'freelance-studio'),
                        'options' => array('Modern/Minimal', 'Bold/Colorful', 'Classic/Traditional', 'Playful/Fun', 'Professional/Corporate', 'Artistic/Creative'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'short_text',
                        'label' => __('Brand colors (if you have them)', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'heading',
                        'label' => __('Content & Features', 'freelance-studio'),
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('List all the pages you need on your website', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'multiple_choice',
                        'label' => __('What features do you need?', 'freelance-studio'),
                        'options' => array('Contact Form', 'Blog', 'E-commerce/Shop', 'Portfolio/Gallery', 'Booking/Scheduling', 'Member Login', 'Newsletter Signup', 'Social Media Integration'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'yes_no',
                        'label' => __('Do you have content (text, images) ready?', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'file_upload',
                        'label' => __('Upload your logo and any brand assets', 'freelance-studio'),
                        'required' => false,
                        'allowed_types' => array('image/*', '.pdf', '.ai', '.eps'),
                        'max_size' => 10,
                    ),
                ),
                'settings' => array(
                    'submit_button_text' => __('Submit Brief', 'freelance-studio'),
                    'success_message' => __('Thank you! We\'ve received your design brief and will review it shortly.', 'freelance-studio'),
                ),
            ),
            array(
                'name' => __('Contact Request Form', 'freelance-studio'),
                'description' => __('Simple contact form for inquiries.', 'freelance-studio'),
                'category' => self::CATEGORY_INTAKE,
                'is_default' => 1,
                'fields' => array(
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'short_text',
                        'label' => __('Your Name', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'email',
                        'label' => __('Email Address', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'phone',
                        'label' => __('Phone Number', 'freelance-studio'),
                        'required' => false,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'dropdown',
                        'label' => __('How can we help you?', 'freelance-studio'),
                        'options' => array('New Project Inquiry', 'Existing Project Question', 'Support Request', 'Partnership Opportunity', 'Other'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'long_text',
                        'label' => __('Your Message', 'freelance-studio'),
                        'required' => true,
                    ),
                    array(
                        'id' => 'field_' . uniqid(),
                        'type' => 'dropdown',
                        'label' => __('How did you hear about us?', 'freelance-studio'),
                        'options' => array('Search Engine', 'Social Media', 'Referral', 'Previous Client', 'Other'),
                        'required' => false,
                    ),
                ),
                'settings' => array(
                    'submit_button_text' => __('Send Message', 'freelance-studio'),
                    'success_message' => __('Thank you for reaching out! We\'ll get back to you within 1-2 business days.', 'freelance-studio'),
                ),
            ),
        );
    }
}
