<?php
/**
 * Plugin Name:       Plugin Compass Change log v2
 * Plugin URI:        https://plugincompass.com
 * Description:       Manage and display changelog entries with a custom post type, shortcode, widget and templates.
 * Version:           1.0.0
 * Author:            Plugin Compass
 * Author URI:        https://plugincompass.com
 * Update URI:        https://plugincompass.com
 * Text Domain:       pc-changelog-manager-abc123
 * Domain Path:       /languages
 * License:           GPLv2 or later
 */

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

// Plugin constants.
if ( ! defined( 'PC_CLM_VERSION' ) ) {
    define( 'PC_CLM_VERSION', '1.0.0' );
}

if ( ! defined( 'PC_CLM_PLUGIN_DIR' ) ) {
    define( 'PC_CLM_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}

if ( ! defined( 'PC_CLM_PLUGIN_URL' ) ) {
    define( 'PC_CLM_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}

// Include core classes.
require_once PC_CLM_PLUGIN_DIR . 'includes/class-changelog-post-type.php';
require_once PC_CLM_PLUGIN_DIR . 'includes/class-changelog-admin.php';
require_once PC_CLM_PLUGIN_DIR . 'includes/class-changelog-public.php';

/**
 * Initialize the plugin.
 */
function pc_clm_init() {
    // Register post type and initialize handlers.
    $post_type = new PC_CLM_Post_Type();
    $post_type->register();

    // Admin hooks.
    if ( is_admin() ) {
        new PC_CLM_Admin( $post_type );
    }

    // Public hooks.
    new PC_CLM_Public( $post_type );
}
add_action( 'init', 'pc_clm_init' );

/**
 * Create the changelog page if it doesn't exist.
 */
function pc_clm_create_changelog_page() {
    $slug = 'changelog';
    
    // Check if the page already exists by slug
    $page_check = get_posts(array(
        'name' => $slug,
        'post_type' => 'page',
        'post_status' => 'publish',
        'numberposts' => 1
    ));
    
    if(empty($page_check)){
        $new_page = array(
            'post_type' => 'page',
            'post_title' => 'Changelog',
            'post_name'  => $slug,
            'post_content' => '[changelog]',
            'post_status' => 'publish',
            'post_author' => 1,
        );
        wp_insert_post($new_page);
    }
}

/**
 * Activation callback.
 */
function pc_clm_activate() {
    $pt = new PC_CLM_Post_Type();
    $pt->register();
    pc_clm_create_changelog_page();
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'pc_clm_activate' );

/**
 * Deactivation callback.
 */
function pc_clm_deactivate() {
    flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pc_clm_deactivate' );
