<?php
/**
 * @package CleverOgre
 * @subpackage OgreAlert
 * @since OgreAlert 0.1.7
 */

namespace OgreAlert;

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

class Expiration {

    public static function load() {
        add_filter('ogrealert/valid_id', [__CLASS__, 'check'], 10, 2);
    }

    static function check($valid, $id) {
        if (!is_int($id)) return $valid;

        $exp_time = self::get_timestamp($id);
        if (!$exp_time) return $valid;

        $remaining = $exp_time - time();
        if ($remaining <= 0) {
            wp_trash_post($id);
            $valid = false;
        }

        return $valid;
    }

    public static function get_timestamp($id) {
        $meta_value = get_post_meta($id, '_ogrealert_expiration', true);
        if (empty($meta_value)) return false;

        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $meta_value) !== 1) return false;

        $exp_time = strtotime($meta_value);
        if (!$exp_time) return false;

        return $exp_time;
    }

}

\OgreAlert\Expiration::load();
