<?php

if (!defined('ABSPATH')) {
    exit;
}

class BSPP_Membership_Repository {

    private $table;

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'bobasoftware_pp_memberships';
    }

    public function create($user_id, $plan, $status = 'active', $current_period_end = null) {
        global $wpdb;

        $inserted = $wpdb->insert(
            $this->table,
            [
                'user_id' => $user_id,
                'plan' => $plan,
                'status' => $status,
                'current_period_end' => $current_period_end,
            ]
        );

        if (!$inserted) {
            return false;
        }

        return (int) $wpdb->insert_id;
    }

    public function get_by_id($membership_id) {
        global $wpdb;
        $membership_id = (int) $membership_id;
        if ($membership_id <= 0) {
            return null;
        }

        return $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$this->table} WHERE id = %d LIMIT 1", $membership_id)
        );
    }

    public function get_by_stripe_subscription_id($stripe_subscription_id) {
        global $wpdb;
        $stripe_subscription_id = sanitize_text_field((string) $stripe_subscription_id);
        if ($stripe_subscription_id === '' || strpos($stripe_subscription_id, 'sub_') !== 0) {
            return null;
        }

        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table} WHERE stripe_subscription_id = %s ORDER BY id DESC LIMIT 1",
                $stripe_subscription_id
            )
        );
    }

    /**
     * Attach Stripe customer + subscription to the member's active row (subscription checkouts).
     */
    public function update_stripe_ids_for_active_user($user_id, $stripe_customer_id, $stripe_subscription_id) {
        global $wpdb;
        $user_id = (int) $user_id;
        $stripe_customer_id = sanitize_text_field((string) $stripe_customer_id);
        $stripe_subscription_id = sanitize_text_field((string) $stripe_subscription_id);
        if ($user_id <= 0) {
            return false;
        }

        $data = [];
        if ($stripe_customer_id !== '' && strpos($stripe_customer_id, 'cus_') === 0) {
            $data['stripe_customer_id'] = $stripe_customer_id;
        }
        if ($stripe_subscription_id !== '' && strpos($stripe_subscription_id, 'sub_') === 0) {
            $data['stripe_subscription_id'] = $stripe_subscription_id;
        }
        if (empty($data)) {
            return false;
        }

        return (bool) $wpdb->update(
            $this->table,
            $data,
            [
                'user_id' => $user_id,
                'status' => 'active',
            ]
        );
    }

    /**
     * Publisher-initiated cancel: Stripe keeps access until period end; local flag for admin display.
     */
    public function mark_cancel_at_period_end($membership_id) {
        global $wpdb;
        $membership_id = (int) $membership_id;
        if ($membership_id <= 0) {
            return false;
        }

        return (bool) $wpdb->update(
            $this->table,
            ['cancel_at_period_end' => 1],
            ['id' => $membership_id]
        );
    }

    public function update_status_and_period($membership_id, $status, $current_period_end = null, $cancel_at_period_end = null) {
        global $wpdb;
        $membership_id = (int) $membership_id;
        $status = sanitize_key((string) $status);
        if ($membership_id <= 0 || $status === '') {
            return false;
        }

        $data = ['status' => $status];
        if ($current_period_end !== null) {
            $data['current_period_end'] = $current_period_end;
        }
        if ($cancel_at_period_end !== null) {
            $data['cancel_at_period_end'] = (int) (bool) $cancel_at_period_end;
        }

        return (bool) $wpdb->update($this->table, $data, ['id' => $membership_id]);
    }

    public function get_active($user_id) {
        global $wpdb;

        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table}
                 WHERE user_id = %d
                 AND status = 'active'
                 LIMIT 1",
                $user_id
            )
        );
    }

    public function is_active($user_id) {
        return !empty($this->get_active($user_id));
    }
}