<?php
/**
 * Plugin Name: EventBookings
 * Description: A plugin to fetch and display data from a EventBookings.
 * Version: 1.2
 * Author: EventBookings
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

global $eventbookings_db_version;
$eventbookings_db_version = '1.2'; // bump this when you change schema

// Define Plugin Constants
define('EVENTBOOKINGS_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('EVENTBOOKINGS_PLUGIN_URL', plugin_dir_url(__FILE__));

// Configuration Management for API URLs
function eventbookings_get_config($key, $default = '')
{
    $environment = get_option('eventbookings_environment', 'production');

    $configs = [
        'development' => [
            'base_url' => 'https://api.diywebsite.net.au/v2',
            'app_url' => 'https://api.diywebsite.net.au',
            'identity_url' => 'https://identity.diywebsite.net.au',
            'remote_payment_url' => 'https://www.diywebsite.net.au/b/remote-payment/',
            'seatplan_url' => 'https://seat-plan.diywebsite.net.au',
        ],
        'staging' => [
            'base_url' => 'https://api.doyour.events/v3',
            'app_url' => 'https://api.doyour.events',
            'identity_url' => 'https://identity.doyour.events',
            'remote_payment_url' => 'https://www.doyour.events/b/remote-payment/',
            'seatplan_url' => 'https://seat-plan.doyour.events',
        ],
        'production' => [
            'base_url' => 'https://api-rto.eventbookings.com/v3',
            'app_url' => 'https://api-rto.eventbookings.com',
            'identity_url' => 'https://identity.eventbookings.com',
            'remote_payment_url' => 'https://www.eventbookings.com/b/remote-payment/',
            'seatplan_url' => 'https://seat-plan.eventbookings.com',
        ]
    ];

    return $configs[$environment][$key] ?? $default;
}

// Define constants using configuration management
define('EVENTBOOKINGS_BASE_URL', eventbookings_get_config('base_url'));
define('EVENTBOOKINGS_APP_URL', eventbookings_get_config('app_url'));
define('EVENTBOOKINGS_IDENTITY_URL', eventbookings_get_config('identity_url'));
define('EVENTBOOKINGS_REMOTE_PAYMENT_URL', eventbookings_get_config('remote_payment_url'));
define('EVENTBOOKINGS_SEATPLAN_URL', eventbookings_get_config('seatplan_url'));


// Include Necessary Files
require_once EVENTBOOKINGS_PLUGIN_PATH . 'includes/class-eventbookings.php';

function eventbookings_create_events_table()
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    // Table: eb_plugin_users
    $table_name = esc_sql($wpdb->prefix . 'eb_plugin_users');
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) != $table_name) {
        $sql = "CREATE TABLE $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            access_token TEXT NULL,
            refresh_token TEXT NULL,
            client_id VARCHAR(255) NULL UNIQUE,
            client_secret VARCHAR(255) NULL,
            user_data TEXT NULL,
            org_uuid TEXT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    // Table: customized_events
    $table_name = $wpdb->prefix . 'customized_events';
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) != $table_name) {
        $sql = "CREATE TABLE $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            organisation_uuid VARCHAR(100) NOT NULL,
            display_event_description TINYINT(1) NOT NULL DEFAULT 1,
            display_countdown TINYINT(1) NOT NULL DEFAULT 1,
            display_booking_start_countdown TINYINT(1) NOT NULL DEFAULT 1,
            display_discount_end_countdown TINYINT(1) NOT NULL DEFAULT 1,
            display_event_start_countdown TINYINT(1) NOT NULL DEFAULT 1,
            display_event_end_countdown TINYINT(1) NOT NULL DEFAULT 1,
            display_event_location_map TINYINT(1) NOT NULL DEFAULT 1,
            display_ticket_price_on_event_page TINYINT(1) NOT NULL DEFAULT 1,
            display_terms_and_condition TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE INDEX idx_organisation_uuid (organisation_uuid)
        ) $charset_collate;";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);

    }

    // Table: events
    $table_name = $wpdb->prefix . 'events';
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) != $table_name) {
        $sql = "CREATE TABLE $table_name (
            uuid VARCHAR(100) NOT NULL,
            organisation_uuid VARCHAR(100) NOT NULL,
            event_data TEXT NOT NULL,
            is_published TINYINT(1) NOT NULL DEFAULT 0,
            is_ended TINYINT(1) NOT NULL DEFAULT 0,
            event_name VARCHAR(200) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (uuid),
            INDEX idx_organisation_uuid (organisation_uuid),
            INDEX idx_published (is_published),
            INDEX idx_ended (is_ended),
            INDEX idx_created_at (created_at)
        ) $charset_collate;";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    $table_name = $wpdb->prefix . 'eb_feature_events';
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) != $table_name) {
        $sql = "CREATE TABLE $table_name (
            uuid VARCHAR(100) NOT NULL,
            organisation_uuid VARCHAR(100) NOT NULL,
            event_data TEXT NOT NULL,
            is_published TINYINT(1) NOT NULL DEFAULT 0,
            is_ended TINYINT(1) NOT NULL DEFAULT 0,
            event_name VARCHAR(200) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (uuid),
            INDEX idx_organisation_uuid (organisation_uuid),
            INDEX idx_published (is_published),
            INDEX idx_ended (is_ended),
            INDEX idx_created_at (created_at)
        ) $charset_collate;";
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    global $eventbookings_db_version;
    update_option('eventbookings_db_version', $eventbookings_db_version);
}

// Register the activation hook
register_activation_hook(__FILE__, 'eventbookings_create_events_table');

require_once plugin_dir_path(__FILE__) . 'includes/class-eventbookings-customized-events.php';

function eventbookings_test()
{
    global $wpdb;
    $table_name = esc_sql($wpdb->prefix . 'customized_events');

    // Ensure the table exists
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) != $table_name) {
        return; // Exit if the table is missing
    }
    $org_uuid = eventbookings_get_org_uuid() ?: 'default-org-uuid';
    // Check if there's already an entry
    $existing_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table_name} WHERE organisation_uuid = %s LIMIT 1", $org_uuid));


    if (!$existing_row) {
        // Insert new event settings if none exist
        $wpdb->insert($table_name, [
            'organisation_uuid' => $org_uuid,
            'display_event_description' => 1, // Default values
            'display_countdown' => 1,
            'display_booking_start_countdown' => 1,
            'display_discount_end_countdown' => 1,
            'display_event_start_countdown' => 1,
            'display_event_end_countdown' => 1,
            'display_event_location_map' => 1,
            'display_ticket_price_on_event_page' => 1,
            'display_terms_and_condition' => 1
        ]);
    } else {
        // Update settings instead
        $wpdb->update($table_name, ['display_event_description' => 1], ['organisation_uuid' => $org_uuid]);
    }
}

// Run on plugin activation
register_activation_hook(__FILE__, 'eventbookings_test');

function eventbookings_check_db_update()
{
    global $eventbookings_db_version;

    $installed_version = get_option('eventbookings_db_version');

    if ($installed_version != $eventbookings_db_version) {
        eventbookings_create_events_table();
        update_option('eventbookings_db_version', $eventbookings_db_version);
    }
}

add_action('plugins_loaded', 'eventbookings_check_db_update');

register_activation_hook(__FILE__, 'eventbookings_create_shortcode_page');

function eventbookings_create_shortcode_page()
{
    $page_title = 'Event Details';

    // Get stored slug or fallback
    $page_slug = get_option('eventbookings_details_page_slug', 'eb-event-details');

    // Check if page exists by slug
    $page_check = get_page_by_path($page_slug);

    if (!$page_check) {
        // Page not found — create a new one
        $page_data = array(
            'post_title' => $page_title,
            'post_name' => sanitize_title($page_slug), // ensure safe slug
            'post_content' => '[eventbookings_feature_event_details]',
            'post_status' => 'publish',
            'post_type' => 'page',
        );

        $new_page_id = wp_insert_post($page_data);

        if ($new_page_id && !is_wp_error($new_page_id)) {
            // Store the slug from the actual created page (in case WP adds -2, -3, etc.)
            $actual_slug = get_post_field('post_name', $new_page_id);
            update_option('eventbookings_details_page_slug', $actual_slug);
        }
    }
}


add_action('post_updated', 'eventbookings_check_slug_change', 10, 3);

function eventbookings_check_slug_change($post_ID, $post_after, $post_before)
{
    // Only check pages
    if ($post_after->post_type !== 'page') {
        return;
    }

    // Define your target page ID or slug
    $target_slug = 'my-plugin-page';

    // Get the original slug and the updated slug
    $old_slug = $post_before->post_name;
    $new_slug = $post_after->post_name;

    // Check if it's your page and slug has changed
    if ($old_slug === $target_slug && $old_slug !== $new_slug) {
        // 👇 Run your custom function
        eventbookings_slug_changed_action($post_ID, $old_slug, $new_slug);
    }
}

function eventbookings_slug_changed_action($post_ID, $old_slug, $new_slug)
{
    // Do whatever you need here

    update_option('eventbookings_details_page_slug', $new_slug);
}


/**
 * Get the organization UUID from the database
 *
 * @return string|null The organization UUID or null if not found
 */
function eventbookings_get_org_uuid()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'eb_plugin_users';
    $result = $wpdb->get_var($wpdb->prepare("SELECT org_uuid FROM %i LIMIT %d", $table_name, 1));
    return $result ?: null;
}

/**
 * Log EventBookings plugin messages
 *
 * @param string $level The log level (error, warning, info, debug)
 * @param string $message The message to log
 * @param array $context Additional context data
 */
function eventbookings_log($level, $message, $context = [])
{
    if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
        $log_entry = sprintf(
            '[EventBookings][%s] %s %s',
            strtoupper($level),
            $message,
            !empty($context) ? json_encode($context) : ''
        );
        error_log($log_entry);
    }
}

// Initialize Plugin
function eventbookings_plugin_init()
{
    new EVENTBOOKINGS_Plugin();
}

add_action('plugins_loaded', 'eventbookings_plugin_init');