<?php

namespace UltraguardPro\modules\uptime_monitor\db;

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

use UltraguardPro\db\BaseTable;

class SslChecksTable extends BaseTable {

    protected $table_name  = 'ultraguard_ssl_checks';
    protected $cache_group = 'ultraguard_ssl_checks';

    public function get_defaults(): array {
        return [
            'id'             => 0,
            'domain'         => '',
            'is_valid'       => 0,
            'expiry_date'    => '',
            'days_remaining' => 0,
            'issuer'         => '',
            'subject'        => '',
            'fingerprint'    => '',
            'error_message'  => '',
            'checked_at'     => '',
        ];
    }

    protected function validate_data( $data ) {
        return $this->validate_required( (array) $data, [ 'domain' ] ) ? $data : false;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $key => $value ) {
            if ( in_array( $key, [ 'is_valid', 'days_remaining' ], true ) ) {
                $out[ $key ] = (int) $value;
            } elseif ( 'error_message' === $key ) {
                $out[ $key ] = sanitize_textarea_field( (string) $value );
            } else {
                $out[ $key ] = is_string( $value ) ? sanitize_text_field( $value ) : $value;
            }
        }
        return $out;
    }

    public function get_latest_for_domain( string $domain ): ?array {
        $rows = $this->get_by( [ 'domain' => $domain ], 1, 'checked_at', 'DESC' );
        return ! empty( $rows[0] ) ? $rows[0] : null;
    }
}
