<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function pc_membership_format_price( $price, $currency = null ) {
    if ( is_null( $currency ) ) {
        $options = get_option( 'pc_membership_options' );
        $currency = isset( $options['currency'] ) ? $options['currency'] : 'usd';
    }

    $symbols = array(
        'usd' => '$',
        'eur' => '€',
        'gbp' => '£',
    );

    $symbol = isset( $symbols[ $currency ] ) ? $symbols[ $currency ] : $currency;

    return $symbol . number_format( (float) $price, 2 );
}

function pc_membership_get_plan( $plan_id ) {
    global $wpdb;
    return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pc_membership_plans WHERE id = %d", $plan_id ) );
}

function pc_membership_get_all_plans() {
    global $wpdb;
    return $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}pc_membership_plans ORDER BY price ASC" );
}

function pc_membership_get_user_subscription( $user_id ) {
    global $wpdb;
    return $wpdb->get_row( $wpdb->prepare(
        "SELECT s.*, p.name as plan_name, p.role, p.is_subscription, p.billing_interval
         FROM {$wpdb->prefix}pc_membership_subscriptions s
         LEFT JOIN {$wpdb->prefix}pc_membership_plans p ON s.plan_id = p.id
         WHERE s.user_id = %d AND s.status = 'active'
         ORDER BY s.id DESC LIMIT 1",
        $user_id
    ) );
}

function pc_membership_is_user_on_plan( $user_id, $plan_id ) {
    $subscription = pc_membership_get_user_subscription( $user_id );
    return $subscription && $subscription->plan_id == $plan_id;
}

function pc_membership_has_active_subscription( $user_id ) {
    return (bool) pc_membership_get_user_subscription( $user_id );
}

function pc_membership_get_page_url( $page_type ) {
    $options = get_option( 'pc_membership_options' );
    $page_id = isset( $options[ $page_type . '_page_id' ] ) ? absint( $options[ $page_type . '_page_id' ] ) : 0;
    return $page_id ? get_permalink( $page_id ) : home_url();
}

function pc_membership_redirect_to_checkout() {
    $checkout_url = pc_membership_get_page_url( 'checkout' );
    if ( $checkout_url ) {
        wp_redirect( $checkout_url );
        exit;
    }
}

function pc_membership_redirect_to_login() {
    $login_url = pc_membership_get_page_url( 'login' );
    if ( $login_url ) {
        wp_redirect( $login_url );
        exit;
    }
    wp_redirect( wp_login_url() );
    exit;
}

function pc_membership_register_user( $user_login, $user_email, $user_password ) {
    $errors = new WP_Error();

    if ( username_exists( $user_login ) ) {
        $errors->add( 'username_exists', __( 'Username already exists.', 'pc-membership-abc123' ) );
    }

    if ( email_exists( $user_email ) ) {
        $errors->add( 'email_exists', __( 'Email already registered.', 'pc-membership-abc123' ) );
    }

    if ( ! is_email( $user_email ) ) {
        $errors->add( 'invalid_email', __( 'Invalid email address.', 'pc-membership-abc123' ) );
    }

    if ( ! validate_username( $user_login ) ) {
        $errors->add( 'invalid_username', __( 'Invalid username.', 'pc-membership-abc123' ) );
    }

    if ( strlen( $user_password ) < 8 ) {
        $errors->add( 'weak_password', __( 'Password must be at least 8 characters.', 'pc-membership-abc123' ) );
    }

    if ( $errors->has_errors() ) {
        return $errors;
    }

    $user_id = wp_create_user( $user_login, $user_password, $user_email );

    if ( is_wp_error( $user_id ) ) {
        return $user_id;
    }

    wp_update_user( array(
        'ID' => $user_id,
        'display_name' => $user_login,
    ) );

    $user = get_userdata( $user_id );
    $user->set_role( 'subscriber' );

    do_action( 'pc_membership_user_registered', $user_id, $user_login, $user_email );

    return $user_id;
}

function pc_membership_authenticate_user( $user_login, $user_password ) {
    $user = wp_authenticate_username_password( null, $user_login, $user_password );

    if ( is_wp_error( $user ) ) {
        return $user;
    }

    wp_set_auth_cookie( $user->ID, true );
    do_action( 'wp_login', $user_login, $user );

    return $user;
}

function pc_membership_create_checkout_session( $plan_id, $user_id = null ) {
    if ( ! class_exists( 'PC_Membership_Stripe' ) ) {
        require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/stripe-handler.php';
    }

    return PC_Membership_Stripe::create_checkout_session( $plan_id, $user_id );
}

function pc_membership_restrict_content( $content_id, $plan_ids, $redirect = 'checkout' ) {
    if ( ! class_exists( 'PC_Membership_Access_Control' ) ) {
        require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/access-control.php';
    }

    return PC_Membership_Access_Control::restrict_post( $content_id, $plan_ids, $redirect );
}

function pc_membership_unrestrict_content( $content_id ) {
    if ( ! class_exists( 'PC_Membership_Access_Control' ) ) {
        require_once PC_MEMBERSHIP_PLUGIN_DIR . 'includes/access-control.php';
    }

    return PC_Membership_Access_Control::unrestrict_post( $content_id );
}

function pc_membership_get_stats() {
    global $wpdb;

    $stats = array(
        'active_members' => 0,
        'active_subscriptions' => 0,
        'total_plans' => 0,
        'revenue_this_month' => 0,
        'revenue_last_month' => 0,
    );

    $stats['active_members'] = $wpdb->get_var( "SELECT COUNT(DISTINCT user_id) FROM {$wpdb->prefix}pc_membership_subscriptions WHERE status = 'active'" );
    $stats['active_subscriptions'] = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pc_membership_subscriptions WHERE status = 'active'" );
    $stats['total_plans'] = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}pc_membership_plans" );

    $current_month = date( 'Y-m-01' );
    $last_month = date( 'Y-m-01', strtotime( '-1 month' ) );

    $stats['revenue_this_month'] = $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount), 0) FROM {$wpdb->prefix}pc_membership_payments WHERE status = 'succeeded' AND created_at >= %s",
        $current_month
    ) );

    $stats['revenue_last_month'] = $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount), 0) FROM {$wpdb->prefix}pc_membership_payments WHERE status = 'succeeded' AND created_at >= %s AND created_at < %s",
        $last_month,
        $current_month
    ) );

    return $stats;
}
