<?php
/**
* Kanews Insights
*
* @package Kanews
* @subpackage Framework
* @since 1.0.0
* @version 1.0.1
**/

class KANEWS_INSIGHTS {

    /**
     * Constructor
     * 
     * Initializes the Insights functionality by setting up filters and actions
     *
     * @since 1.0.0
     * @version 1.0.1
     */
    public function __construct() { 

        // User Column
        add_filter( 'manage_users_columns', array( $this, 'admin_subs_status_column' ), 1 );
        add_filter( 'manage_users_custom_column', array( $this, 'admin_subs_status_column_content'), 10, 3);

        // Metabox
        add_action( 'woocommerce_product_data_panels', array( $this, 'options' ) );
        add_action( 'woocommerce_process_product_meta', array( $this, 'update_options' ), 10, 2 );
        add_action( 'woocommerce_product_data_tabs', array( $this, 'tab' ) );
        add_action( 'admin_head', array( $this, 'tab_icon' ) );

        // Complated Order
        add_action( 'woocommerce_order_status_completed', array( $this, 'order_complate' ), 10, 1 );

        // Canceled Order
        add_action( 'woocommerce_order_status_changed', array( $this, 'order_cancel' ), 10, 3 );

        // Requires
        add_filter( 'the_content', array( $this, 'post_content' ), 1 );

        // User Fields
        add_action( 'show_user_profile', array( $this, 'create_profile_fields' ) );
        add_action( 'edit_user_profile', array( $this, 'create_profile_fields' ) );

        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

        add_action( 'pre_get_posts', array( $this, 'modify_search_query' ), 10, 1 );

    }


    /**
     * Enqueue scripts for countdown functionality
     *
     * @since 1.0.0
     * @version 1.0.1
     */
    public static function enqueue_scripts() {
        if( get_post_meta(get_the_ID(), 'post_insight', true) == '2' )
        wp_enqueue_script( 'jquery-countdown', KAN_TEMPLATE_URL . '/assets/js/jquery.countdown.min.js', array('kanews-theme'), KAN_THEME_VER, true );
    }

    /**
     * Display user badge for subscribers
     *
     * @param int $uid User ID
     * @return string|void HTML for user badge or void if not a subscriber
     * @since 1.0.0
     * @version 1.0.1
     */ 
    public static function user_badge($uid) {
    $sub = kanews_insights_control($uid);
    if($sub == false)
    return;

    return '<span class="kanews-user-badge"><span class="bg-success">'.esc_html__( 'Abone', 'kanews' ).'</span></span>';
    }

    /**
     * Filter post content based on subscription status
     *
     * @param string $content The post content
     * @return string Modified content
     * @since 1.0.0
     * @version 1.0.1
     */
    function post_content($content) {
		
	if( ! $system = kanews_get_option('kanews-insights') )
	return $content;
		
    $meta = get_post_meta( get_the_ID(), 'post_insight', true );

    $author = get_post_field ('post_author', get_the_ID());
    $user = get_current_user_id();

    if($author == $user)
    return $content;

    foreach(get_the_category(get_the_ID()) as $category) {
        $private_category = get_term_meta( $category->term_id, 'private-category', true );
        if( $private_category == 'yes' || $private_category ) {
			if( kanews_insights_control() == true ) {
                $private_category_pack = get_term_meta( $category->term_id, 'kanews-insights-cat', true );
                if( !empty($private_category_pack) && $private_category_pack !== 0 ) {
                    $expired  = get_user_meta($user, 'kanews_insights_purchase_expired', true);
                    if(is_array($private_category_pack)) {
											foreach($private_category_pack as $abc) {
												if(strpos( $abc, $expired) !== false ) {
													return $content;
												}
											} 
										}
                } else {
                    return $content;
                }
            }

			$out = kanews_private_content(null, $meta);

			return wp_trim_words( get_the_content(), apply_filters('kanews/insights/content_filter', 40), $out);
			exit();
        }
    }

    if( $meta == '0' || ! $meta )
    return $content;

    if( kanews_insights_control() == true )
    return $content;
    
    if( $meta == '2' && ( $countdown = get_post_meta(get_the_ID(), 'post_insight_countdown', true) ) != '' ) {
        $timediff = strtotime("now") - strtotime($countdown);
        if( $timediff > 0 ) {
            return $content;
        }
    }

    $out = kanews_private_content(null, $meta);

    return wp_trim_words( get_the_content(), apply_filters('kanews/insights/content_filter', 40), $out );
    }

    /**
     * Add Kanews Insights tab to product data tabs
     *
     * @param array $tabs Existing tabs
     * @return array Modified tabs
     * @since 1.0.0
     * @version 1.0.1
     **/
    function tab( $tabs ){

    $tabs['kanews'] = array(
        'label'    => esc_html__( 'Kanews Insights', 'kanews' ),
        'target'   => 'kanews_product_data',
        'priority' => 21,
    );
    return $tabs;
    }

    /**
     * Display product options panel
     *
     * @since 1.0.0
     * @version 1.0.1
     **/
    function options () {
    echo '<div id="kanews_product_data" class="panel woocommerce_options_panel hidden">';
        woocommerce_wp_select( array(
        'id'      => 'kanews_insights',
        'label'   => __( 'Geçerlilik Süresi', 'kanews' ),
        'description'   => __( 'Bu paketi satın alan kişinin abonelik süresini belirleyin. Daha sonradan bu süreyi değiştirmeniz önerilmez değiştirmek yerine bunu çöpe atıp yeni bir ürün oluşturun.', 'kanews' ),
        'options' =>  array(
            '0' => esc_html__( 'Seçiminizi Yapın', 'kanews' ),
            'weekly' => esc_html__( '1 Hafta', 'kanews' ),
            'monthly' => esc_html__( '1 Ay', 'kanews' ),
            'three_months' => esc_html__( '3 Ay', 'kanews' ),
            'six_months' => esc_html__( '6 Ay', 'kanews' ),
            'yearly' => esc_html__( '1 Yıllık', 'kanews' ),
            'forever' => esc_html__( 'Ömür Boyu', 'kanews' ),
        ),
        'value'   => get_post_meta ( get_the_ID ( ) , 'kanews_insights' , true  ),
        ) );
        woocommerce_wp_select( array(
        'id'      => 'kanews_ilan_insights',
        'label'   => __( 'İlan Yukarı Taşıma Süresi', 'kanews' ),
        'description'   => __( 'Bu pakete sahip olan üyenin ilanlarını ne kadar sürede bir yukarı taşıyacağını belirleyin.', 'kanews' ),
        'options' =>  array(
            '0' => esc_html__( 'Seçiminizi Yapın', 'kanews' ),
            HOUR_IN_SECONDS => esc_html__( '1 Saat', 'kanews' ),
            4 * HOUR_IN_SECONDS => esc_html__( '4 Saat', 'kanews' ),
            8 * HOUR_IN_SECONDS  => esc_html__( '8 Saat', 'kanews' ),
            12 * HOUR_IN_SECONDS => esc_html__( '12 Saat', 'kanews' ),
            18 * HOUR_IN_SECONDS => esc_html__( '18 Saat', 'kanews' ),
            24 * HOUR_IN_SECONDS => esc_html__( '24 Saat', 'kanews' ),
        ),
        'value'   => get_post_meta ( get_the_ID ( ) , 'kanews_ilan_insights' , true  ),
        ) );
    echo  '</div>' ;
    }

    /**
     * Update product meta options
     *
     * @param int $id Product ID
     * @param object $post Post object
     * @since 1.0.0
     * @version 1.0.1
     **/
    function update_options ($id, $post) {
    update_post_meta( $id, 'kanews_insights', $_POST['kanews_insights'] );
    update_post_meta( $id, 'kanews_ilan_insights', $_POST['kanews_ilan_insights'] );
    }

    /**
     * Add custom icon to product data tab
     *
     * @since 1.0.0
     * @version 1.0.1
     **/
    function tab_icon(){
    echo '<style>
    #woocommerce-product-data ul.wc-tabs li.kanews_options.kanews_tab a:before{
        content: "\f198";
    }
    </style>';
    }

    /**
     * Handle completed order actions
     *
     * @param int $order_id Order ID
     * @since 1.0.0
     * @version 1.0.1
     */
    function order_complate( $order_id ) {

    $order = wc_get_order( $order_id ); 
    $items = $order->get_items();

    foreach ( $items as $item )
    $product_id = $item->get_product_id();

    $product = wc_get_product( $product_id );
    $product_data = json_decode( $product, true );
    foreach($product_data['meta_data'] as $data ) {
        if($data['key'] == 'kanews_insights')
        $loop = $data['value'];
        if($data['key'] == 'kanews_ilan_insights')
        $loop2 = $data['value'];
    }

    $complate = $order->date_completed;
    $customer = $order->get_customer_id();

    update_user_meta( $customer, 'kanews_insights_purchase_date', $complate );
    update_user_meta( $customer, 'kanews_insights_purchase_expired', $loop );
    update_user_meta( $customer, 'kanews_insights_ilan_update_loop', $loop2 );
    }

    /**
     * Handle order cancellation
     *
     * @param int $order_id Order ID
     * @param string $old_status Previous order status
     * @param string $new_status New order status
     * @since 1.0.0
     * @version 1.0.1
     */
    function order_cancel( $order_id, $old_status, $new_status ) {
		if( $old_status == 'completed' && $new_status !== 'completed' ) {
			$order = wc_get_order( $order_id ); 
			$customer = $order->get_customer_id();

			update_user_meta( $customer, 'kanews_insights_purchase_date', 'Cancel' );
		}
    }

    /**
     * Add subscription status column to users table
     *
     * @param array $columns Existing columns
     * @return array Modified columns
     * @since 1.0.0
     * @version 1.0.1
     */
    function admin_subs_status_column($columns ) {
    $columns['subscription'] = 'Abonelik Durumu';
    return $columns;
    }		

    /**
     * Display subscription status in users table
     *
     * @param string $value Column value
     * @param string $column_name Column name
     * @param int $user_id User ID
     * @return string Modified column value
     * @since 1.0.0
     * @version 1.0.1
     */
    function admin_subs_status_column_content($value, $column_name, $user_id) {
    if ( 'subscription' == $column_name ) {
        if(kanews_insights_control($user_id) == true) 
        return '<button class="button" style="border-color:green;background:green;color:white;">'.esc_html__( 'Abone', 'kanews' ).'</button>';
        else
        return '<button class="button">'.esc_html__('Abone Değil', 'kanews').'</button>';
    }

    return $value;
    }

    /**
     * Add subscription history fields to user profile
     *
     * @param object $user User object
     * @since 1.0.0
     * @version 1.0.1
     */
    function create_profile_fields( $user ) { 
    if(kanews_get_option('kanews-insights') != true)
    return;
    $args = array('customer_id' => $user->ID, 'limit' => 5); $orders = wc_get_orders($args);
    if($orders && is_admin()): ?>
    <h3><?php esc_html_e('Abonelik Geçmişi', 'kanews'); ?></h3>
    <table class="widefat fixed">
        <thead>
        <tr>
            <th><span class="nobr"><?php esc_html_e('Id', 'kanews'); ?></span></th>
            <th><span class="nobr"><?php esc_html_e('Paket', 'kanews'); ?></span></th>
            <th><span class="nobr"><?php esc_html_e('Geçerlilik', 'kanews'); ?></span></th>
            <th><span class="nobr"><?php esc_html_e('Kalan Süre', 'kanews'); ?></span></th>
        </tr>
        </thead>
        <tbody>
        <?php kanews_order_lists($orders); ?>
        </tbody>
    </table>
    <?php endif;
    }

    /**
     * Exclude WooCommerce products from WordPress search results
     *
     * @param WP_Query $query Query object
     * @since 1.0.0
     * @version 1.0.1
     */
    function modify_search_query( $query ) {
        // Make sure this isn't the admin or is the main query
        if( is_admin() || ! $query->is_main_query() ) {
        return;
        }
    
        // Make sure this isn't the WooCommerce product search form
        if( isset($_GET['post_type']) && ($_GET['post_type'] == 'product') ) {
        return;
        }
    
        if( $query->is_search() ) {
        $in_search_post_types = get_post_types( array( 'exclude_from_search' => false ) );
    
        // The post types you're removing (example: 'product' and 'page')
        $post_types_to_remove = array( 'product', 'page', 'ilan', 'firma' );
    
        foreach( $post_types_to_remove as $post_type_to_remove ) {
            if( is_array( $in_search_post_types ) && in_array( $post_type_to_remove, $in_search_post_types ) ) {
            unset( $in_search_post_types[ $post_type_to_remove ] );
            $query->set( 'post_type', $in_search_post_types );
            }
        }
        }
    }
}

if(class_exists( 'WooCommerce' ))
$KANEWS_INSIGHTS = new KANEWS_INSIGHTS();

/*-----------------------------------------------------------------------------------*/
# Check Subscription
/*-----------------------------------------------------------------------------------*/
/**
 * Check if a user has an active subscription
 *
 * @param int $user_id User ID (optional)
 * @return bool True if user has active subscription, false otherwise
 * @since 1.0.0
 * @version 1.0.1
 */
function kanews_insights_control($user_id = '') {
    $system = kanews_get_option('kanews-insights');

    if( ! $system )
    return false;

    if( !class_exists( 'WooCommerce' ))
    return false;

    if($user_id == '')
    $user_id = get_current_user_id();

    $purchase = get_user_meta($user_id, 'kanews_insights_purchase_date', true);
    $expired  = get_user_meta($user_id, 'kanews_insights_purchase_expired', true);
    $timediff = strtotime("now") - strtotime($purchase);

    if(!$purchase || $purchase == 'Cancel' )
    return false;

    $time = 0;

    switch($expired) {
    case 'weekly':
        $time = 86400*7;
        break;
    case 'six_months':
        $time = 86400*180;
    break;
    case 'three_months':
        $time = 86400*90;
    break;
    case 'monthly':
        $time = 86400*30;
    break;
    case 'weekly':
        $time = 86400*365;
        break;
    case 'forever':
        $time = 0;
        break;
    default:
        $time = 0;
        break;
    }

    if($timediff < $time || $time == 0)
    return true;
    else
    return false; 
}

/*-----------------------------------------------------------------------------------*/
# Kanews Insights Page URL
/*-----------------------------------------------------------------------------------*/
/**
 * Get the URL for the insights page
 *
 * @param bool $register Whether to include registration parameter
 * @return string URL for the insights page
 * @since 1.0.0
 * @version 1.0.1
 */
function kanews_insights_page_url($register = NULL) {
$page = kanews_get_option('kanews-insights-page') ? kanews_get_option('kanews-insights-page') : '';
$out = '#';

if($page != '')
$out = get_page_link($page);;

return $out;
}

/**
 * Custom redirect after adding to cart
 *
 * @param string $url Redirect URL
 * @return string Modified redirect URL
 * @since 1.0.0
 * @version 1.0.1
 */
function my_custom_add_to_cart_redirect( $url ) {

$url = wc_get_checkout_url();
return $url;

}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );


/**
 * Generate HTML for private content message
 *
 * @param string $read Read parameter
 * @param string $countdown Countdown parameter
 * @return string HTML for private content message
 * @since 1.0.0
 * @version 1.0.1
 */
function kanews_private_content($read = '', $countdown = '') {
$login_link = kanews_account_page_url();
$disable_before = 'bcontent-none';
$out = '';
if($read != 'a') {
    $out .= '... <div class="kanews-private-read-more"></div>';
    $disable_before = '';
}

if( $countdown == '2' ) {
    $h2_text = esc_html__( 'Bu içerik abonelerimiz için erken erişimdedir.', 'kanews' );
    $p_text = esc_html__( 'İlgili içeriği görebilmek için hemen bir abonelik başlatın veya sürenin dolmasını bekleyin.', 'kanews' );
    $countdown_html = '<div id="kanews_insights_countdown" data-countdown="'.get_post_meta(get_the_ID(), 'post_insight_countdown', true).'"></div>';
} else{
    $h2_text = kanews_translate('subscribe-post-title', esc_html__( 'Bu içerik abonelirimize özel olarak hazırlanmıştır.', 'kanews' ));
    $p_text  = kanews_translate('subscribe-post-desc', esc_html__( 'İlgili içeriği görebilmek için hemen bir abonelik başlatın veya zaten aboneyseniz giriş yapın.', 'kanews' ));
    $countdown_html = '';
}

$out .= '
<div class="kanews-private-post '.$disable_before.'">
    <div class="kanews-private-post-inner">
    <i class="icon-unlock"></i>
    <h2>'. $h2_text .'</h2>
    <p>'. $p_text .'</p>
    '.$countdown_html.'
    <div class="kanews-btn-group justify-content-center">';
        if(kanews_get_option('login-system') && !is_user_logged_in())
        $out .= '<a href="'.esc_url($login_link).'" class="kanews-btn bg-dark">'.esc_html__( 'Giriş Yap', 'kanews' ).'</a>';
        $out .= '<a href="'.kanews_insights_page_url().'" class="kanews-btn">'.esc_html__( 'Hemen Bir Abonelik Başlat', 'kanews' ).'</a>
    </div>
    </div>
</div>
';
return $out;
}

/**
 * Display order lists in user profile
 *
 * @param array $orders Orders to display
 * @since 1.0.0
 * @version 1.0.1
 */
function kanews_order_lists( $orders ) {
foreach($orders as $order) { ?>
<tr>
    <?php 
    $order = wc_get_order( $order->get_id() ); $items = $order->get_items();
    foreach ( $items as $item ) {
    $purchase = $order->get_date_completed();
    $expired  = get_post_meta($item->get_product_id(),'kanews_insights', true);
    if( $expired )
    $timediff = strtotime("now") - strtotime( $purchase);
    else
    $timediff = 0;
    echo '<td>'.$order->get_id().'</td>';
    echo '<td>'.$item->get_name().'</td>';
    
    if($order->get_status() == 'completed') {
        kanews_display_subscription_period($expired, $timediff);
    } elseif($order->get_status() == 'cancel') {
        echo '<td>'.$expired.'</td>';
        echo '<td>'.esc_html__('Aboneliğiniz iptal edildi','kanews' ).'</td>';
    } else {
        echo '<td>'.$expired.'</td>';
        echo '<td>'.esc_html__('Aboneliğiniz henüz onaylanmadı','kanews' ).'</td>';
    }
    }
    ?>
</tr>
<?php } 
}

/**
 * Display subscription period information
 *
 * @param string $expired The subscription period type
 * @param int $timediff The time difference in seconds
 * @return void
 * @since 1.0.0
 * @version 1.0.1
 */
function kanews_display_subscription_period($expired, $timediff) {
    $periods = [
        'weekly' => [
            'seconds' => 86400 * 7,
            'label' => esc_html__('1 Hafta', 'kanews')
        ],
        'six_months' => [
            'seconds' => 86400 * 180,
            'label' => esc_html__('6 Ay', 'kanews')
        ],
        'three_months' => [
            'seconds' => 86400 * 90,
            'label' => esc_html__('3 Ay', 'kanews')
        ],
        'monthly' => [
            'seconds' => 86400 * 30,
            'label' => esc_html__('1 Ay', 'kanews')
        ],
        'yearly' => [
            'seconds' => 86400 * 365,
            'label' => esc_html__('1 Yıl', 'kanews')
        ],
        'forever' => [
            'seconds' => 0,
            'label' => esc_html__('Ömür boyu', 'kanews')
        ]
    ];
    
    if (isset($periods[$expired])) {
        $period = $periods[$expired];
        echo '<td>'.$period['label'].'</td>';
        
        if ($period['seconds'] > 0) {
            if ($timediff < $period['seconds']) {
                echo '<td>'. secondsToTime($period['seconds'] - $timediff).'</td>';
            } else {
                echo '<td>'.esc_html__('Süre Doldu', 'kanews').'</td>';
            }
        } else {
            echo '<td>'.esc_html__('Ömür boyu', 'kanews').'</td>';
        }
    } else {
        echo '<td>'.esc_html__('Ömür boyu', 'kanews').'</td>';
        echo '<td>'.esc_html__('Ömür boyu', 'kanews').'</td>';
    }
}
