<?php
/**
 * Email Form AJAX Handler
 * 
 * @package Unlockafe_addons
 */

namespace Unlockafe_addons\Classes;

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

class Email_Form_Handler {
    
    /**
     * @var object Instance of this class
     */
    private static $instance = null;
    
    /**
     * Get instance of this class
     * 
     * @return object
     */
    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Register AJAX handlers
        add_action('wp_ajax_unlockafe_process_email_form', array($this, 'process_form_submission'));
        add_action('wp_ajax_nopriv_unlockafe_process_email_form', array($this, 'process_form_submission'));
        
        // Enqueue scripts
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }
    
    /**
     * Enqueue necessary scripts
     */
    public function enqueue_scripts() {
        // Admin URLs
        $admin_ajax = admin_url('admin-ajax.php');
        
        // Register and enqueue our email capture script
        wp_enqueue_script('unlockafe-email-capture', UNLOCKAFE_ASSETS . 'front-end/js/email-capture.js', array('jquery'), time(), true); // Using time() for cache busting
        
        // Create a nonce and localize the script
        $nonce = wp_create_nonce('unlockafe_email_form_nonce');
        error_log('Generated nonce: ' . $nonce);
        
        // Localize the script with our data
        wp_localize_script('unlockafe-email-capture', 'unlockafe_email_form', array(
            'ajax_url' => $admin_ajax,
            'nonce' => $nonce
        ));
    }
    
    /**
     * Process form submission
     */
    public function process_form_submission() {
        // Basic security check
        if (!check_ajax_referer('unlockafe_email_form_nonce', 'nonce', false)) {
            error_log('Nonce verification failed in Email Capture form');
        }

        if (empty($_POST['email'])) {
            wp_send_json_error(array(
                'message' => 'Email is required.'
            ));
            return;
        }

        $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
        $email = sanitize_email($_POST['email']);
        $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
        $form_id = isset($_POST['form_id']) ? sanitize_text_field($_POST['form_id']) : '';
        $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : null;

        if (!is_email($email)) {
            wp_send_json_error(array(
                'message' => 'Please enter a valid email address.'
            ));
            return;
        }

        // Duplicate check: email + page_url + category_id
        global $wpdb;
        $table_name = $wpdb->prefix . 'unlockafe_email_capture';
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE email = %s AND page_url = %s AND (category_id = %d OR (category_id IS NULL AND %d IS NULL))",
            $email, $page_url, $category_id, $category_id
        ));
        if ($exists > 0) {
            wp_send_json_error(array(
                'message' => 'This email is already added for this page and category.'
            ));
            return;
        }

        $result = $this->save_submission($name, $email, $page_url, $form_id, $category_id);

        if ($result) {
            wp_send_json_success(array(
                'message' => 'Thank you for subscribing!'
            ));
        } else {
            wp_send_json_error(array(
                'message' => 'Something went wrong. Please try again.'
            ));
        }
    }
    
    /**
     * Save submission to database
     * 
     * @param string $name Name
     * @param string $email Email
     * @param string $page_url Page URL
     * @param string $form_id Form ID
     * @param int $category_id Category ID
     * @return bool Success/failure
     */
    private function save_submission($name, $email, $page_url, $form_id, $category_id = null) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'unlockafe_email_capture';
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the table if it doesn't exist
            $db_setup = DB_Setup::getInstance();
            $db_setup->create_tables();
        }
        
        // Get user info
        $ip_address = $this->get_client_ip();
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        
        // Insert submission
        $data = array(
            'name' => $name,
            'email' => $email,
            'page_url' => $page_url,
            'form_id' => $form_id,
            'ip_address' => $ip_address,
            'user_agent' => $user_agent,
            'submitted_at' => current_time('mysql'),
            'status' => 'subscribed',
        );
        $format = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');
        if (!is_null($category_id)) {
            $data['category_id'] = $category_id;
            $format[] = '%d';
        }
        $result = $wpdb->insert($table_name, $data, $format);
        
        if ($result) {
            // Do something with the submission (e.g., send email, add to mailing list)
            do_action('unlockafe_after_email_submission', array(
                'name' => $name,
                'email' => $email,
                'page_url' => $page_url,
                'form_id' => $form_id,
                'category_id' => $category_id
            ));
            
            return true;
        }
        
        return false;
    }
    
    /**
     * Get client IP address
     * 
     * @return string 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);
    }
}

// Initialize the class
Email_Form_Handler::getInstance();
