<?php
/**
 * Contact Form Handler
 * 
 * Handles contact form submissions, database storage, and admin panel display
 *
 * @package Blynex
 * @since 1.0.0
 */

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

class Blynex_Contact_Form_Handler
{
    /**
     * Database table name
     */
    private $table_name;

    /**
     * Constructor
     */
    public function __construct()
    {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'blynex_contact_submissions';

        // Register activation hook to create table
        register_activation_hook(get_template_directory() . '/functions.php', [$this, 'create_submissions_table']);

        // Create table on theme activation
        add_action('after_switch_theme', [$this, 'create_submissions_table']);

        // Handle AJAX form submission
        add_action('wp_ajax_blynex_contact_form_submit', [$this, 'handle_form_submission']);
        add_action('wp_ajax_nopriv_blynex_contact_form_submit', [$this, 'handle_form_submission']);

        // Add admin menu for viewing submissions
        add_action('admin_menu', [$this, 'add_admin_menu']);

        // Enqueue scripts for frontend
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_scripts']);
    }

    /**
     * Create submissions database table
     */
    public function create_submissions_table()
    {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();

        // Use more explicit SQL to ensure compatibility
        $sql = "CREATE TABLE {$this->table_name} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL DEFAULT '',
            email varchar(255) NOT NULL DEFAULT '',
            phone varchar(50) DEFAULT NULL,
            subject varchar(500) DEFAULT NULL,
            message text NOT NULL,
            ip_address varchar(100) DEFAULT NULL,
            user_agent text DEFAULT NULL,
            submitted_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY email (email),
            KEY submitted_at (submitted_at)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Enqueue frontend scripts
     */
    public function enqueue_frontend_scripts()
    {
        // Enqueue contact form script
        wp_enqueue_script(
            'blynex-contact-form',
            get_template_directory_uri() . '/assets/js/contact-form.js',
            [],
            wp_get_theme()->get('Version'),
            true
        );

        // Localize script with AJAX data
        wp_localize_script('blynex-contact-form', 'blynexContactForm', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('blynex_contact_form'),
            'successMessage' => __('Thank you! Your message has been sent successfully.', 'blynex'),
            'errorMessage' => __('Sorry, there was an error sending your message. Please try again.', 'blynex'),
            'submittingText' => __('Sending...', 'blynex'),
        ]);
    }

    /**
     * Handle form submission via AJAX
     */
    public function handle_form_submission()
    {
        // Verify nonce
        if (!check_ajax_referer('blynex_contact_form', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', 'blynex')]);
            return;
        }

        // Sanitize and validate input
        $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
        $subject = isset($_POST['subject']) ? sanitize_text_field($_POST['subject']) : '';
        $message = isset($_POST['message']) ? sanitize_textarea_field($_POST['message']) : '';
        $honeypot = isset($_POST['website']) ? sanitize_text_field($_POST['website']) : '';

        // Honeypot check - if filled, it's likely spam
        if (!empty($honeypot)) {
            wp_send_json_error(['message' => __('Spam detected.', 'blynex')]);
            return;
        }

        // Validate required fields
        if (empty($name) || empty($email) || empty($message)) {
            wp_send_json_error(['message' => __('Please fill in all required fields.', 'blynex')]);
            return;
        }

        // Validate email
        if (!is_email($email)) {
            wp_send_json_error(['message' => __('Please enter a valid email address.', 'blynex')]);
            return;
        }

        // Get IP address and user agent
        $ip_address = $this->get_client_ip();
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';

        // Save to database
        global $wpdb;

        $inserted = $wpdb->insert(
            $this->table_name,
            [
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'subject' => $subject,
                'message' => $message,
                'ip_address' => $ip_address,
                'user_agent' => $user_agent,
            ],
            ['%s', '%s', '%s', '%s', '%s', '%s', '%s']
        );

        if ($inserted === false) {
            wp_send_json_error(['message' => __('Failed to save your message. Please try again.', 'blynex')]);
            return;
        }

        // Send email notification
        $recipient_email = isset($_POST['recipientEmail']) ? sanitize_email($_POST['recipientEmail']) : get_option('admin_email');
        
        $email_subject = sprintf(__('New Contact Form Submission from %s', 'blynex'), $name);
        $email_message = sprintf(
            __("You have received a new contact form submission:\n\nName: %s\nEmail: %s\nPhone: %s\nSubject: %s\n\nMessage:\n%s\n\n---\nIP Address: %s\nSubmitted: %s", 'blynex'),
            $name,
            $email,
            $phone ?: __('Not provided', 'blynex'),
            $subject ?: __('No subject', 'blynex'),
            $message,
            $ip_address,
            current_time('mysql')
        );

        $headers = [
            'Content-Type: text/plain; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
            'Reply-To: ' . $name . ' <' . $email . '>',
        ];

        wp_mail($recipient_email, $email_subject, $email_message, $headers);

        wp_send_json_success([
            'message' => __('Thank you! Your message has been sent successfully.', 'blynex')
        ]);
    }



    /**
     * Get client IP address
     */
    private function get_client_ip()
    {
        $ip = '';
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return sanitize_text_field($ip);
    }

    /**
     * Add admin menu for contact form submissions
     */
    public function add_admin_menu()
    {
        add_theme_page(
            __('Contact Submissions', 'blynex'),
            __('Contact Submissions', 'blynex'),
            'manage_options',
            'blynex-contact-submissions',
            [$this, 'display_submissions_page']
        );
    }

    /**
     * Delete a submission
     */
    private function delete_submission($id)
    {
        global $wpdb;
        return $wpdb->delete(
            $this->table_name,
            ['id' => (int)$id],
            ['%d']
        );
    }

    /**
     * Display submissions page in admin (Cryzel style)
     */
    public function display_submissions_page()
    {
        // Handle deletion
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
            check_admin_referer('delete_submission_' . $_GET['id']);
            $this->delete_submission((int)$_GET['id']);
            echo '<div class="notice notice-success"><p>' . __('Submission deleted successfully.', 'blynex') . '</p></div>';
        }

        // Get submissions
        global $wpdb;
        $page = isset($_GET['paged']) ? max(1, (int)$_GET['paged']) : 1;
        $per_page = 20;
        $offset = ($page - 1) * $per_page;

        // Ensure table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$this->table_name}'");
        if (!$table_exists) {
            $this->create_submissions_table();
        }

        $total = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}");
        $submissions = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} ORDER BY submitted_at DESC LIMIT %d OFFSET %d",
            $per_page,
            $offset
        ));

        $total_pages = ceil($total / $per_page);

        ?>
        <div class="wrap">
            <h1><?php _e('Contact Form Submissions', 'blynex'); ?></h1>
            
            <?php if (empty($submissions)) : ?>
                <div class="notice notice-info">
                    <p><?php _e('No submissions yet.', 'blynex'); ?></p>
                </div>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('ID', 'blynex'); ?></th>
                            <th><?php _e('Name', 'blynex'); ?></th>
                            <th><?php _e('Email', 'blynex'); ?></th>
                            <th><?php _e('Phone', 'blynex'); ?></th>
                            <th><?php _e('Subject', 'blynex'); ?></th>
                            <th><?php _e('Message', 'blynex'); ?></th>
                            <th><?php _e('Date', 'blynex'); ?></th>
                            <th><?php _e('Actions', 'blynex'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($submissions as $submission) : ?>
                            <tr>
                                <td><strong>#<?php echo esc_html($submission->id); ?></strong></td>
                                <td><?php echo esc_html($submission->name); ?></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->phone ?: '—'); ?></td>
                                <td><?php echo esc_html($submission->subject ?: '—'); ?></td>
                                <td>
                                    <div style="max-width: 200px; overflow: hidden;">
                                        <?php echo esc_html(wp_trim_words($submission->message, 8)); ?>
                                    </div>
                                </td>
                                <td><?php echo esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission->submitted_at))); ?></td>
                                <td>
                                    <a href="<?php echo esc_url(add_query_arg([
                                        'action' => 'view',
                                        'id' => $submission->id
                                    ])); ?>" class="button button-small">
                                        <span class="dashicons dashicons-visibility" style="vertical-align: middle;"></span>
                                        <?php _e('View', 'blynex'); ?>
                                    </a>
                                    <a href="<?php echo esc_url(wp_nonce_url(add_query_arg([
                                        'action' => 'delete',
                                        'id' => $submission->id
                                    ]), 'delete_submission_' . $submission->id)); ?>" 
                                       class="button button-small button-link-delete" 
                                       onclick="return confirm('<?php _e('Are you sure you want to delete this submission?', 'blynex'); ?>')">
                                        <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                                        <?php _e('Delete', 'blynex'); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if ($total_pages > 1) : ?>
                    <div class="tablenav">
                        <div class="tablenav-pages">
                            <?php
                            echo paginate_links([
                                'base' => add_query_arg('paged', '%#%'),
                                'format' => '',
                                'prev_text' => __('&laquo;', 'blynex'),
                                'next_text' => __('&raquo;', 'blynex'),
                                'total' => $total_pages,
                                'current' => $page
                            ]);
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <?php if (isset($_GET['action']) && $_GET['action'] === 'view' && isset($_GET['id'])) : ?>
                <?php
                $submission = $wpdb->get_row($wpdb->prepare(
                    "SELECT * FROM {$this->table_name} WHERE id = %d",
                    (int)$_GET['id']
                ));
                if ($submission) :
                ?>
                    <div class="card" style="margin-top: 20px; max-width: 800px;">
                        <h2>
                            <span class="dashicons dashicons-email-alt" style="vertical-align: middle;"></span>
                            <?php _e('Submission Details', 'blynex'); ?> - #<?php echo esc_html($submission->id); ?>
                        </h2>
                        <table class="form-table" role="presentation">
                            <tbody>
                                <tr>
                                    <th scope="row"><?php _e('Name:', 'blynex'); ?></th>
                                    <td><?php echo esc_html($submission->name); ?></td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php _e('Email:', 'blynex'); ?></th>
                                    <td><a href="mailto:<?php echo esc_attr($submission->email); ?>"><?php echo esc_html($submission->email); ?></a></td>
                                </tr>
                                <?php if ($submission->phone) : ?>
                                <tr>
                                    <th scope="row"><?php _e('Phone:', 'blynex'); ?></th>
                                    <td><a href="tel:<?php echo esc_attr($submission->phone); ?>"><?php echo esc_html($submission->phone); ?></a></td>
                                </tr>
                                <?php endif; ?>
                                <?php if ($submission->subject) : ?>
                                <tr>
                                    <th scope="row"><?php _e('Subject:', 'blynex'); ?></th>
                                    <td><strong><?php echo esc_html($submission->subject); ?></strong></td>
                                </tr>
                                <?php endif; ?>
                                <tr>
                                    <th scope="row"><?php _e('Message:', 'blynex'); ?></th>
                                    <td>
                                        <div style="background: #f9f9f9; padding: 15px; border-radius: 4px; border-left: 4px solid #0073aa; max-width: 600px; line-height: 1.6;">
                                            <?php echo nl2br(esc_html($submission->message)); ?>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php _e('IP Address:', 'blynex'); ?></th>
                                    <td><code><?php echo esc_html($submission->ip_address); ?></code></td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php _e('Submitted:', 'blynex'); ?></th>
                                    <td><?php echo esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission->submitted_at))); ?></td>
                                </tr>
                                <?php if ($submission->user_agent) : ?>
                                <tr>
                                    <th scope="row"><?php _e('Browser:', 'blynex'); ?></th>
                                    <td><small><code><?php echo esc_html($submission->user_agent); ?></code></small></td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                        <p class="submit">
                            <a href="<?php echo esc_url(remove_query_arg(['action', 'id'])); ?>" class="button button-primary">
                                <span class="dashicons dashicons-arrow-left-alt" style="vertical-align: middle;"></span>
                                <?php _e('Back to List', 'blynex'); ?>
                            </a>
                            <a href="mailto:<?php echo esc_attr($submission->email); ?>?subject=Re: <?php echo esc_attr($submission->subject ?: 'Your Message'); ?>" class="button">
                                <span class="dashicons dashicons-email" style="vertical-align: middle;"></span>
                                <?php _e('Reply via Email', 'blynex'); ?>
                            </a>
                            <a href="<?php echo esc_url(wp_nonce_url(add_query_arg([
                                'action' => 'delete',
                                'id' => $submission->id
                            ], remove_query_arg(['action', 'id'])), 'delete_submission_' . $submission->id)); ?>" 
                               class="button button-link-delete" 
                               onclick="return confirm('<?php _e('Are you sure you want to delete this submission?', 'blynex'); ?>')">
                                <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                                <?php _e('Delete', 'blynex'); ?>
                            </a>
                        </p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <style>
        .card h2 .dashicons {
            color: #0073aa;
        }
        .wp-list-table .button .dashicons {
            font-size: 16px;
            width: 16px;
            height: 16px;
        }
        .wp-list-table td {
            vertical-align: middle;
        }
        .button-link-delete:hover {
            color: #d63638;
        }
        </style>
        <?php
    }
}

// Initialize the contact form handler
new Blynex_Contact_Form_Handler();