<?php

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

class BSPP_Webhook_Event_Repository {
    private $table;

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

    public function has_processed($stripe_event_id) {
        global $wpdb;

        $stripe_event_id = sanitize_text_field($stripe_event_id);
        if (empty($stripe_event_id)) {
            return false;
        }

        $result = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM {$this->table} WHERE stripe_event_id = %s LIMIT 1",
                $stripe_event_id
            )
        );

        return !empty($result);
    }

    public function record_event($stripe_event_id, $stripe_event_type = null) {
        global $wpdb;

        $stripe_event_id = sanitize_text_field($stripe_event_id);
        $stripe_event_type = $stripe_event_type !== null ? sanitize_text_field($stripe_event_type) : null;

        if (empty($stripe_event_id)) {
            return false;
        }

        $inserted = $wpdb->insert(
            $this->table,
            [
                'stripe_event_id' => $stripe_event_id,
                'stripe_event_type' => $stripe_event_type,
            ]
        );

        return (bool) $inserted;
    }
}
