<?php

$postType = 'page';
$postStatus = 'publish';  
$leadTitle = 'Card';



$new_post = array(
'post_title' => $leadTitle,
'post_status' => $postStatus,
'post_author' => '',
'post_type' => $postType
);
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = %s AND post_type = %s',$leadTitle,$postType);
$wpdb->query( $query );
if ( $wpdb->num_rows == 0 ) {
    $post_id = wp_insert_post($new_post);
}

$getss=$wpdb->query("SHOW TABLES LIKE 'ow_card_2022'");
if($getss==0){
	$check_old_db=$wpdb->query("SHOW TABLES LIKE 'ow_card'");
	if($check_old_db==0){$wpdb->query("DROP TABLE `ow_card`");}
$wpdb->query("CREATE TABLE `ow_card_2022` ( 
`id` int(4) NOT NULL, 
`border_color` varchar(7) NULL, 
`swish_color` varchar(7) NULL, 
`sgreet_color` varchar(7) NULL, 
`logo_bgcolor` varchar(7) NULL, 
`cedit_color` varchar(7) NULL, 
`footbg_color` varchar(7) NULL, 
`cardbg_color` varchar(7) NULL, 
`season` text NULL, 
`season_wish` longtext NULL, 
`greetings` longtext NULL, 
`card_image_name` varchar(100) DEFAULT NULL, 
`card_content` longtext NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ");
    
    $wpdb->query("ALTER TABLE `ow_card_2022` ADD PRIMARY KEY(`id`)");
    $wpdb->query("ALTER TABLE `ow_card_2022` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;");    
}

// **** template assignment for url '/card'
remove_action("template_redirect", 'my_theme_redirect');
 add_action("template_redirect", 'my_theme_redirect');

    function my_theme_redirect() {
        global $wp;
        global $post;
        $plugindir = dirname( __FILE__ );

        if ($post->post_name == 'card') {
            $templatefilename = 'seasonalcard.php';
            if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
                $return_template = TEMPLATEPATH . '/' . $templatefilename;
            } else {
                $return_template = $plugindir . '/template/' . $templatefilename;
            }
            do_theme_redirect($return_template);
        }
    }

function seasoncardmenu() { 
	global $iris_db;
	$row=$iris_db->get_row( "SELECT * FROM seasoncards where active='1'" );
        $sdate = strtotime($row->start_date);
        $edate = strtotime($row->end_date);
        $currtime = strtotime("now");
	if ( has_card() ) {
        if( $currtime >= $sdate && $currtime <= $edate ){
            add_submenu_page( 'iris-dashboard', 'IRIS-Card settings', 'Card Settings', 'edit_posts', 'iris-card-settings', 'card_page' );
        } 
	}
	
    
	}
add_action('admin_menu', 'seasoncardmenu');
function card_page() {
	require_once plugin_dir_path( __DIR__ ) . 'admin/page-card-settings.php'; 
}

function do_theme_redirect( $url ) {

    global $post, $wp_query;
    if( have_posts() )  {
        include($url);
        die();
    }   else    {
        $wp_query->is_404   =   true;
    }
}