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

class BLM_Connection {

    public static function is_connected() {
        $status = get_option( 'blm_connection_status', array() );
        return ! empty( $status['connected'] );
    }

    public static function connect( $api_key ) {
        if ( empty( $api_key ) ) {
            return false;
        }

        $hash = wp_hash( $api_key );

        update_option( 'blm_connection_status', array(
            'connected' => true,
            'key_hash'  => $hash,
        ) );

        return true;
    }

    public static function disconnect() {
        update_option( 'blm_connection_status', array(
            'connected' => false,
            'key_hash'  => '',
        ) );
    }

    public static function validate_key( $provided_key ) {
        $status = get_option( 'blm_connection_status', array() );

        if ( empty( $status['key_hash'] ) ) {
            return false;
        }

        $provided_hash = wp_hash( $provided_key );

        return hash_equals( $status['key_hash'], $provided_hash );
    }

    public static function get_last_updated() {
        $timestamp = get_option( 'blm_last_updated', '' );

        if ( empty( $timestamp ) ) {
            return 'Never';
        }

        return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $timestamp ) );
    }
}
