<?php
/**
 * Contact Form Handler
 * 
 * Handles contact form submissions and admin display
 *
 * @package Eryndo
 */

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

class Eryndo_Contact_Form_Handler {
    
    /**
     * Constructor
     */
    public function __construct() {
        // AJAX handlers for logged in and non-logged in users
        add_action('wp_ajax_eryndo_contact_form_submit', array($this, 'handle_form_submission'));
        add_action('wp_ajax_nopriv_eryndo_contact_form_submit', array($this, 'handle_form_submission'));
        
        // Admin menu
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // Create database table on activation
        add_action('after_setup_theme', array($this, 'create_database_table'));
        
        // Enqueue frontend script
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_script'));
    }
    
    /**
     * Enqueue frontend script
     */
    public function enqueue_frontend_script() {
        $script_path = get_template_directory() . '/build/features/contact-form-widget/view.js';
        $script_url = get_template_directory_uri() . '/build/features/contact-form-widget/view.js';
        $asset_file = get_template_directory() . '/build/features/contact-form-widget/view.asset.php';
        
        // Get asset file data
        $asset_data = file_exists($asset_file) ? include $asset_file : array('dependencies' => array(), 'version' => '1.0.0');
        
        // Enqueue the script
        wp_enqueue_script(
            'eryndo-contact-form',
            $script_url,
            $asset_data['dependencies'],
            $asset_data['version'],
            true
        );
        
        // Localize script with AJAX URL and nonce
        wp_localize_script('eryndo-contact-form', 'eryndoContactForm', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('eryndo_contact_form_nonce')
        ));
    }
    
    /**
     * Create database table for storing contact form submissions
     */
    public function create_database_table() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'eryndo_contact_submissions';
        $charset_collate = $wpdb->get_charset_collate();
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            $sql = "CREATE TABLE $table_name (
                id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                name varchar(255) NOT NULL,
                email varchar(255) NOT NULL,
                phone varchar(50) DEFAULT NULL,
                subject varchar(500) DEFAULT NULL,
                message text NOT NULL,
                recipient_email varchar(255) DEFAULT NULL,
                ip_address varchar(45) DEFAULT NULL,
                user_agent text DEFAULT NULL,
                submitted_at datetime DEFAULT CURRENT_TIMESTAMP,
                status varchar(20) DEFAULT 'unread',
                PRIMARY KEY (id),
                KEY status (status),
                KEY submitted_at (submitted_at)
            ) $charset_collate;";
            
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
    
    /**
     * Handle form submission via AJAX
     */
    public function handle_form_submission() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'eryndo_contact_form_nonce')) {
            wp_send_json_error(array(
                'message' => __('Security check failed. Please refresh the page and try again.', 'eryndo')
            ));
        }
        
        // Honeypot check (spam protection)
        if (!empty($_POST['contact_website'])) {
            // This is likely spam, silently reject
            wp_send_json_success(array(
                'message' => __('Thank you! Your message has been sent successfully.', 'eryndo')
            ));
        }
        
        // Sanitize and validate input
        $name = isset($_POST['contact_name']) ? sanitize_text_field($_POST['contact_name']) : '';
        $email = isset($_POST['contact_email']) ? sanitize_email($_POST['contact_email']) : '';
        $phone = isset($_POST['contact_phone']) ? sanitize_text_field($_POST['contact_phone']) : '';
        $subject = isset($_POST['contact_subject']) ? sanitize_text_field($_POST['contact_subject']) : '';
        $message = isset($_POST['contact_message']) ? sanitize_textarea_field($_POST['contact_message']) : '';
        $recipient_email = isset($_POST['recipient_email']) ? sanitize_email($_POST['recipient_email']) : get_option('admin_email');
        
        // Validation
        $errors = array();
        
        if (empty($name)) {
            $errors[] = __('Name is required.', 'eryndo');
        }
        
        if (empty($email) || !is_email($email)) {
            $errors[] = __('Valid email is required.', 'eryndo');
        }
        
        if (empty($message)) {
            $errors[] = __('Message is required.', 'eryndo');
        }
        
        if (!empty($errors)) {
            wp_send_json_error(array(
                'message' => implode(' ', $errors)
            ));
        }
        
        // Save to database
        global $wpdb;
        $table_name = $wpdb->prefix . 'eryndo_contact_submissions';
        
        $inserted = $wpdb->insert(
            $table_name,
            array(
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'subject' => $subject,
                'message' => $message,
                'recipient_email' => $recipient_email,
                'ip_address' => $this->get_client_ip(),
                'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '',
                'submitted_at' => current_time('mysql'),
                'status' => 'unread'
            ),
            array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
        );
        
        if ($inserted === false) {
            wp_send_json_error(array(
                'message' => __('Failed to save your message. Please try again.', 'eryndo')
            ));
        }
        
        // Send email notification
        $this->send_email_notification($name, $email, $phone, $subject, $message, $recipient_email);
        
        // Return success response
        wp_send_json_success(array(
            'message' => __('Thank you! Your message has been sent successfully.', 'eryndo')
        ));
    }
    
    /**
     * Send email notification
     */
    private function send_email_notification($name, $email, $phone, $subject, $message, $recipient_email) {
        $email_subject = sprintf(__('[%s] New Contact Form Submission', 'eryndo'), get_bloginfo('name'));
        
        if (!empty($subject)) {
            $email_subject .= ' - ' . $subject;
        }
        
        $email_body = sprintf(
            __("You have received a new message from your website contact form.\n\n", 'eryndo') .
            __("Name: %s\n", 'eryndo') .
            __("Email: %s\n", 'eryndo') .
            ($phone ? __("Phone: %s\n", 'eryndo') : '') .
            ($subject ? __("Subject: %s\n", 'eryndo') : '') .
            __("\nMessage:\n%s\n\n", 'eryndo') .
            __("---\n", 'eryndo') .
            __("This message was sent from: %s", 'eryndo'),
            $name,
            $email,
            $phone,
            $subject,
            $message,
            home_url()
        );
        
        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'Reply-To: ' . $name . ' <' . $email . '>'
        );
        
        wp_mail($recipient_email, $email_subject, $email_body, $headers);
    }
    
    /**
     * Get client IP address
     */
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
        
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                        return $ip;
                    }
                }
            }
        }
        
        return '';
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_theme_page(
            __('Contact Submissions', 'eryndo'),
            __('Contact Forms', 'eryndo'),
            'manage_options',
            'eryndo-contact-submissions',
            array($this, 'render_admin_page')
        );
    }
    
    /**
     * Render admin page
     */
    public function render_admin_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'eryndo_contact_submissions';
        
        // Handle actions
        if (isset($_GET['action']) && isset($_GET['id']) && check_admin_referer('eryndo_contact_action')) {
            $id = intval($_GET['id']);
            
            if ($_GET['action'] === 'delete') {
                $wpdb->delete($table_name, array('id' => $id), array('%d'));
                echo '<div class="notice notice-success is-dismissible"><p>' . __('Submission deleted successfully.', 'eryndo') . '</p></div>';
            } elseif ($_GET['action'] === 'mark_read') {
                $wpdb->update($table_name, array('status' => 'read'), array('id' => $id), array('%s'), array('%d'));
                echo '<div class="notice notice-success is-dismissible"><p>' . __('Marked as read.', 'eryndo') . '</p></div>';
            } elseif ($_GET['action'] === 'mark_unread') {
                $wpdb->update($table_name, array('status' => 'unread'), array('id' => $id), array('%s'), array('%d'));
                echo '<div class="notice notice-success is-dismissible"><p>' . __('Marked as unread.', 'eryndo') . '</p></div>';
            }
        }
        
        // Get submissions
        $submissions = $wpdb->get_results("SELECT * FROM $table_name ORDER BY submitted_at DESC");
        
        ?>
        <div class="wrap">
            <h1><?php _e('Contact Form Submissions', 'eryndo'); ?></h1>
            
            <?php if (empty($submissions)): ?>
                <p><?php _e('No submissions yet.', 'eryndo'); ?></p>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th style="width: 5%;"><?php _e('ID', 'eryndo'); ?></th>
                            <th style="width: 15%;"><?php _e('Name', 'eryndo'); ?></th>
                            <th style="width: 15%;"><?php _e('Email', 'eryndo'); ?></th>
                            <th style="width: 15%;"><?php _e('Subject', 'eryndo'); ?></th>
                            <th style="width: 30%;"><?php _e('Message', 'eryndo'); ?></th>
                            <th style="width: 10%;"><?php _e('Date', 'eryndo'); ?></th>
                            <th style="width: 5%;"><?php _e('Status', 'eryndo'); ?></th>
                            <th style="width: 5%;"><?php _e('Actions', 'eryndo'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($submissions as $submission): ?>
                            <tr style="<?php echo $submission->status === 'unread' ? 'background-color: #f0f6fc;' : ''; ?>">
                                <td><?php echo esc_html($submission->id); ?></td>
                                <td><strong><?php echo esc_html($submission->name); ?></strong></td>
                                <td><a href="mailto:<?php echo esc_attr($submission->email); ?>"><?php echo esc_html($submission->email); ?></a></td>
                                <td><?php echo esc_html($submission->subject ?: '—'); ?></td>
                                <td><?php echo esc_html(wp_trim_words($submission->message, 15)); ?></td>
                                <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission->submitted_at))); ?></td>
                                <td>
                                    <span class="dashicons <?php echo $submission->status === 'unread' ? 'dashicons-marker' : 'dashicons-yes'; ?>" style="color: <?php echo $submission->status === 'unread' ? '#d63638' : '#00a32a'; ?>;"></span>
                                </td>
                                <td>
                                    <a href="#" onclick="event.preventDefault(); document.getElementById('detail-<?php echo $submission->id; ?>').style.display = document.getElementById('detail-<?php echo $submission->id; ?>').style.display === 'none' ? 'table-row' : 'none';" title="<?php _e('View Details', 'eryndo'); ?>">
                                        <span class="dashicons dashicons-visibility"></span>
                                    </a>
                                    <?php if ($submission->status === 'unread'): ?>
                                        <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=eryndo-contact-submissions&action=mark_read&id=' . $submission->id), 'eryndo_contact_action'); ?>" title="<?php _e('Mark as Read', 'eryndo'); ?>">
                                            <span class="dashicons dashicons-yes-alt"></span>
                                        </a>
                                    <?php else: ?>
                                        <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=eryndo-contact-submissions&action=mark_unread&id=' . $submission->id), 'eryndo_contact_action'); ?>" title="<?php _e('Mark as Unread', 'eryndo'); ?>">
                                            <span class="dashicons dashicons-marker"></span>
                                        </a>
                                    <?php endif; ?>
                                    <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=eryndo-contact-submissions&action=delete&id=' . $submission->id), 'eryndo_contact_action'); ?>" onclick="return confirm('<?php _e('Are you sure you want to delete this submission?', 'eryndo'); ?>');" title="<?php _e('Delete', 'eryndo'); ?>">
                                        <span class="dashicons dashicons-trash" style="color: #d63638;"></span>
                                    </a>
                                </td>
                            </tr>
                            <tr id="detail-<?php echo $submission->id; ?>" style="display: none; background-color: #f9f9f9;">
                                <td colspan="8" style="padding: 20px;">
                                    <h3><?php _e('Submission Details', 'eryndo'); ?></h3>
                                    <p><strong><?php _e('Name:', 'eryndo'); ?></strong> <?php echo esc_html($submission->name); ?></p>
                                    <p><strong><?php _e('Email:', 'eryndo'); ?></strong> <a href="mailto:<?php echo esc_attr($submission->email); ?>"><?php echo esc_html($submission->email); ?></a></p>
                                    <?php if ($submission->phone): ?>
                                        <p><strong><?php _e('Phone:', 'eryndo'); ?></strong> <a href="tel:<?php echo esc_attr($submission->phone); ?>"><?php echo esc_html($submission->phone); ?></a></p>
                                    <?php endif; ?>
                                    <?php if ($submission->subject): ?>
                                        <p><strong><?php _e('Subject:', 'eryndo'); ?></strong> <?php echo esc_html($submission->subject); ?></p>
                                    <?php endif; ?>
                                    <p><strong><?php _e('Message:', 'eryndo'); ?></strong></p>
                                    <div style="background: white; padding: 15px; border-left: 3px solid #2271b1;">
                                        <?php echo nl2br(esc_html($submission->message)); ?>
                                    </div>
                                    <hr>
                                    <p><strong><?php _e('Submitted:', 'eryndo'); ?></strong> <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission->submitted_at))); ?></p>
                                    <p><strong><?php _e('IP Address:', 'eryndo'); ?></strong> <?php echo esc_html($submission->ip_address); ?></p>
                                    <p><strong><?php _e('User Agent:', 'eryndo'); ?></strong> <?php echo esc_html($submission->user_agent); ?></p>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
}

// Initialize the handler
new Eryndo_Contact_Form_Handler();
