<?php 

// Hook to run when the theme or plugin is activated
function lcp_create_newsletter_tables() {
    global $wpdb;

    // Table names with prefix 'lcp'
    $table_name_contacts = $wpdb->prefix . 'lcp_newsletter_subscribers';
    $table_name_campaign_lists = $wpdb->prefix . 'lcp_newsletter_lists';
    $table_name_communications = $wpdb->prefix . 'lcp_communications'; 

    $charset_collate = $wpdb->get_charset_collate();

    // SQL to create the subscribers table
    $sql_contacts = "
    CREATE TABLE $table_name_contacts (
        id BIGINT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(255) NOT NULL,
        user_id BIGINT(20) UNSIGNED UNIQUE,
        first_name VARCHAR(255),
        last_name VARCHAR(255),
        subscription_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY email_unique (email)
    ) $charset_collate;
    ";

    // SQL to create the subscriptions table (if needed, for storing subscription data)
    $sql_subscriptions = "
    CREATE TABLE $table_name_campaign_lists (
        id BIGINT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        subscriber_id BIGINT(20) UNSIGNED NOT NULL,
        newsletter_name VARCHAR(255) NOT NULL,
        subscription_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (subscriber_id) REFERENCES $table_name_subscribers(id) ON DELETE CASCADE
    ) $charset_collate;
    ";

    $sql_communications = "
    CREATE TABLE $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        contact_id BIGINT(20) UNSIGNED NOT NULL,
        status ENUM('scheduled', 'sent', 'failed') NOT NULL DEFAULT 'scheduled',
        send_datetime DATETIME DEFAULT NULL,
        attempts INT(10) UNSIGNED NOT NULL DEFAULT 0,
        error_message TEXT DEFAULT NULL,
        PRIMARY KEY (id),
        KEY newsletter_id (newsletter_id)
        
        ) $charset_collate;
    ";

    // Run the SQL queries to create the tables
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql_contacts);
    dbDelta($sql_communications);
  ;
}
add_action('after_switch_theme', 'lcp_create_newsletter_tables');  // or use 'register_activation_hook()' for a plugin


// Register Custom Post Type for 'lcp_newsletters'
function lcp_register_newsletters_cpt() {
    $args = array(
        'label'               => 'Newsletters',
        'description'         => 'Custom post type for newsletters',
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_rest'        => true, // Enable for REST API
        'supports'            => array('title', 'editor', 'custom-fields'), // Supports custom fields
        'has_archive'         => true,
        'rewrite'             => array('slug' => 'newsletters'),
        'show_in_graphql'     => true,
        'hierarchical'        => false, // Set false as newsletters are usually single-level posts
    );

    register_post_type('lcp_newsletters', $args);
}
add_action('init', 'lcp_register_newsletters_cpt');

// Register Custom Taxonomy for 'newsletter_campaigns'
function lcp_register_newsletter_campaigns_taxonomy() {
    $args = array(
        'hierarchical' => true,
        'label' => 'Newsletter Campaigns',
        'show_ui' => true,
        'show_in_rest' => true,
        'show_admin_column' => true,
        'rewrite' => array('slug' => 'newsletter-campaigns'),
    );

    register_taxonomy('newsletter_campaigns', array('lcp_newsletters'), $args);
}
add_action('init', 'lcp_register_newsletter_campaigns_taxonomy');

// Add the 'send_datetime' meta field for the 'lcp_newsletters' CPT
function lcp_add_send_datetime_meta_box() {
    add_meta_box(
        'send_datetime_meta_box',    // Meta box ID
        'Send Date and Time',        // Title
        'lcp_render_send_datetime_meta_box', // Callback function to render content
        'lcp_newsletters',           // Post type to attach the meta box to
        'side',                      // Context (side bar)
        'high'                       // Priority
    );
}
add_action('add_meta_boxes', 'lcp_add_send_datetime_meta_box');

// Render the 'send_datetime' field
function lcp_render_send_datetime_meta_box($post) {
    wp_nonce_field(basename(__FILE__), 'send_datetime_nonce'); // Add nonce for security
    $send_datetime = get_post_meta($post->ID, '_send_datetime', true); // Get current value from post meta
    echo '<input type="datetime-local" id="send_datetime" name="send_datetime" value="' . esc_attr($send_datetime) . '" />';
}

// Save the 'send_datetime' field
function lcp_save_send_datetime_meta_box($post_id) {
    if (!isset($_POST['send_datetime_nonce']) || !wp_verify_nonce($_POST['send_datetime_nonce'], basename(__FILE__))) {
        return $post_id; // Nonce check failed, do not save
    }
    
    $send_datetime = isset($_POST['send_datetime']) ? sanitize_text_field($_POST['send_datetime']) : '';
    
    if (!empty($send_datetime)) {
        update_post_meta($post_id, '_send_datetime', $send_datetime); // Save send_datetime as post meta
    } else {
        delete_post_meta($post_id, '_send_datetime'); // Delete meta if empty
    }
}
add_action('save_post', 'lcp_save_send_datetime_meta_box');

function lcp_restrict_blocks_for_newsletters($allowed_blocks, $post) {
    // Check if the post type is 'lcp_newsletters'
    if ($post->post_type === 'lcp_newsletters') {
        // Define the allowed blocks for 'lcp_newsletters'
        $allowed_blocks = array(
            'core/paragraph',
            'core/heading',
            'core/list',
            'core/image',
            'core/quote',
            'core/button',
            // Add any other blocks you want to allow
        );
    }
    
    return $allowed_blocks;
}

add_filter('allowed_block_types', 'lcp_restrict_blocks_for_newsletters', 10, 2);


