<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class BSPP_Paywall_Engine {
    private $settings;

    private $memberships;

    public function __construct() {
        $this->settings = new BSPP_Settings_Repository();
        $this->memberships = new BSPP_Membership_Repository();
    }

    public function is_post_unlocked( $post_id, $user_id = 0 ) {
        if ( empty( $post_id ) ) {
            return false;
        }
        // Onboarding launch checkpoint:
        // keep content unlocked only when setup has not been completed yet.
        // Support both flags for backward compatibility across earlier iterations.
        $onboarding_completed = (int) $this->settings->get( 'bspp_onboarding_completed', 0 );
        $paywall_launched = (int) $this->settings->get( 'bspp_paywall_launched', 0 );
        if ( $onboarding_completed !== 1 && $paywall_launched !== 1 ) {
            return true;
        }
        // Rule 1: post is still within free publish window
        if ( $this->is_within_free_publish_window( $post_id ) ) {
            return true;
        }
        // Anonymous users get no additional access yet
        if ( empty( $user_id ) ) {
            return false;
        }
        // Rule 2: active membership
        if ( $this->memberships->is_active( $user_id ) ) {
            return true;
        }
        // Rule 7: default locked
        return false;
    }

    private function is_within_free_publish_window( $post_id ) {
        $days = (int) $this->settings->get( 'posts_become_paid_after_days', 0 );
        if ( $days <= 0 ) {
            return false;
        }
        $post = get_post( $post_id );
        if ( !$post ) {
            return false;
        }
        $published_timestamp = strtotime( ( $post->post_date_gmt ?: $post->post_date ) );
        $days_in_seconds = $days * DAY_IN_SECONDS;
        return time() - $published_timestamp < $days_in_seconds;
    }

}
