<?php

namespace Unlockafe_addons\Admin;

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

/**
 * Email Records Admin Page Handler
 */
class EmailRecords {
    /**
     * Instance of this class
     *
     * @var object
     */
    private static $instance = null;

    /**
     * Get singleton instance
     *
     * @return EmailRecords
     */
    public static function get_instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Ensure this runs very late to avoid conflicts
        add_action('admin_menu', [$this, 'register_admin_menu'], 99);
    }

    /**
     * Register admin menu
     */
    public function register_admin_menu() {
        // Register as submenu only
        add_submenu_page(
            'unlock-addons', // Parent slug
            __('Email Records', 'unlock-addons-for-elementor'), // Page title
            __('Email Records', 'unlock-addons-for-elementor'), // Menu title
            'edit_posts', // Lower capability requirement
            'unlockafe-email-records', // Menu slug (changed to avoid conflicts)
            [$this, 'render_page'] // Callback
        );
    }

    /**
     * Render the Email Records admin page
     */
    public function render_page() {
        if (!current_user_can('edit_posts')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'unlock-addons-for-elementor'));
        }
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'unlockafe_email_capture';
        
        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name;
        
        // Get records if table exists
        $records = [];
        if ($table_exists) {
            $records = $wpdb->get_results(
                "SELECT id, name, email, page_url, form_id, submitted_at, status, ip_address 
                 FROM {$table_name} 
                 ORDER BY submitted_at DESC",
                ARRAY_A
            );
        }
        
        // Include the view file
        include_once UNLOCKAFE_INCLUDE_PATH . 'Admin/views/email-records.php';
    }

    // Duplicate get_instance method removed
}
