<?php
namespace Unlockafe_addons\API;

use WP_REST_Server;
use WP_REST_Response;
use WP_Error;

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

/**
 * Email Records API class
 */
class EmailRecords_API {
    /**
     * Instance variable
     *
     * @var EmailRecords_API
     */
    private static $instance = null;

    /**
     * Constructor
     */
    private function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    /**
     * Get instance
     *
     * @return EmailRecords_API
     */
    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        register_rest_route('unlockafe-addons/v1', '/email-records', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_records'],
            'permission_callback' => function() {
                return current_user_can('edit_posts');
            }
        ]);
    }

    /**
     * Get email records
     *
     * @param \WP_REST_Request $request The request object
     * @return WP_REST_Response|WP_Error Response or error
     */
    public function get_records($request) {
        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;
        
        if (!$table_exists) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('Email records table does not exist.', 'unlock-addons-for-elementor'),
                'records' => []
            ]);
        }
        
        // Get records
        $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
        );
        
        if (empty($records)) {
            return new WP_REST_Response([
                'success' => true,
                'message' => __('No records found.', 'unlock-addons-for-elementor'),
                'records' => []
            ]);
        }
        
        return new WP_REST_Response([
            'success' => true,
            'message' => sprintf(
                __('Found %d records.', 'unlock-addons-for-elementor'),
                count($records)
            ),
            'records' => $records
        ]);
    }
}
