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

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

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

    /**
     * Constructor
     */
    public function __construct()
    {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'cryzel_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_cryzel_contact_form_submit', [$this, 'handle_form_submission']);
        add_action('wp_ajax_nopriv_cryzel_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();

        $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id bigint(20) 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,
            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(
            'cryzel-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('cryzel-contact-form', 'cryzelContactForm', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('cryzel_contact_form'),
            'successMessage' => __('Thank you! Your message has been sent successfully.', 'cryzel'),
            'errorMessage' => __('Sorry, there was an error sending your message. Please try again.', 'cryzel'),
            'submittingText' => __('Sending...', 'cryzel'),
        ]);
    }

    /**
     * Handle form submission via AJAX
     */
    public function handle_form_submission()
    {
        // Verify nonce
        if (!check_ajax_referer('cryzel_contact_form', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', 'cryzel')]);
            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.', 'cryzel')]);
            return;
        }

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

        // Validate email
        if (!is_email($email)) {
            wp_send_json_error(['message' => __('Please enter a valid email address.', 'cryzel')]);
            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) {
            wp_send_json_error(['message' => __('Failed to save your message. Please try again.', 'cryzel')]);
            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', 'cryzel'), $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", 'cryzel'),
            $name,
            $email,
            $phone ?: __('Not provided', 'cryzel'),
            $subject ?: __('No subject', 'cryzel'),
            $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.', 'cryzel')
        ]);
    }

    /**
     * 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 viewing submissions
     */
    public function add_admin_menu()
    {
        add_theme_page(
            __('Contact Submissions', 'cryzel'),
            __('Contact Submissions', 'cryzel'),
            'manage_options',
            'cryzel-contact-submissions',
            [$this, 'display_submissions_page']
        );
    }

    /**
     * Display submissions page in admin
     */
    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.', 'cryzel') . '</p></div>';
        }

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

        $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', 'cryzel'); ?></h1>
            
            <?php if (empty($submissions)) : ?>
                <p><?php _e('No submissions yet.', 'cryzel'); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('ID', 'cryzel'); ?></th>
                            <th><?php _e('Name', 'cryzel'); ?></th>
                            <th><?php _e('Email', 'cryzel'); ?></th>
                            <th><?php _e('Phone', 'cryzel'); ?></th>
                            <th><?php _e('Subject', 'cryzel'); ?></th>
                            <th><?php _e('Message', 'cryzel'); ?></th>
                            <th><?php _e('Date', 'cryzel'); ?></th>
                            <th><?php _e('Actions', 'cryzel'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($submissions as $submission) : ?>
                            <tr>
                                <td><?php echo esc_html($submission->id); ?></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><?php echo esc_html(wp_trim_words($submission->message, 10)); ?></td>
                                <td><?php echo esc_html(date_i18n(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"><?php _e('View', 'cryzel'); ?></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" onclick="return confirm('<?php _e('Are you sure you want to delete this submission?', 'cryzel'); ?>')"><?php _e('Delete', 'cryzel'); ?></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;', 'cryzel'),
                                'next_text' => __('&raquo;', 'cryzel'),
                                '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><?php _e('Submission Details', 'cryzel'); ?></h2>
                        <table class="form-table">
                            <tr>
                                <th><?php _e('Name:', 'cryzel'); ?></th>
                                <td><?php echo esc_html($submission->name); ?></td>
                            </tr>
                            <tr>
                                <th><?php _e('Email:', 'cryzel'); ?></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><?php _e('Phone:', 'cryzel'); ?></th>
                                <td><?php echo esc_html($submission->phone); ?></td>
                            </tr>
                            <?php endif; ?>
                            <?php if ($submission->subject) : ?>
                            <tr>
                                <th><?php _e('Subject:', 'cryzel'); ?></th>
                                <td><?php echo esc_html($submission->subject); ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <th><?php _e('Message:', 'cryzel'); ?></th>
                                <td><?php echo nl2br(esc_html($submission->message)); ?></td>
                            </tr>
                            <tr>
                                <th><?php _e('IP Address:', 'cryzel'); ?></th>
                                <td><?php echo esc_html($submission->ip_address); ?></td>
                            </tr>
                            <tr>
                                <th><?php _e('Submitted:', 'cryzel'); ?></th>
                                <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($submission->submitted_at))); ?></td>
                            </tr>
                        </table>
                        <p><a href="<?php echo esc_url(remove_query_arg(['action', 'id'])); ?>" class="button"><?php _e('Back to List', 'cryzel'); ?></a></p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <?php
    }

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

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