<?php
/**
 * 247ChatMate — Agency Entitlement Helpers
 * Checkpoint: AGENCYFREEKEYREGISTRYLOCK1
 *
 * Purpose:
 * - Resolve whether the saved agency own-site access key is currently active.
 * - Provide a later hook point for the gated Agency Hub nav without creating the hub UI yet.
 *
 * Does not:
 * - Grant agency client seats.
 * - Replace LemonSqueezy paid subscription validation.
 * - Change frontend widget/chip/WhatsApp/lead email behaviour.
 */

defined('ABSPATH') || exit;

if (!function_exists('matewa_agency_entitlement_get_statuses_that_grant_own_site_access')) {
    function matewa_agency_entitlement_get_statuses_that_grant_own_site_access() {
        return array('approved', 'active');
    }
}

if (!function_exists('matewa_agency_entitlement_get_blocked_statuses')) {
    function matewa_agency_entitlement_get_blocked_statuses() {
        return array('pending', 'needs_review', 'rejected', 'revoked', 'blocked', 'expired', 'inactive');
    }
}

if (!function_exists('matewa_agency_entitlement_get_expiry_timestamp')) {
    function matewa_agency_entitlement_get_expiry_timestamp($expiry = '') {
        $expiry = trim((string) $expiry);

        if ('' === $expiry) {
            return 0;
        }

        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiry)) {
            $expiry .= ' 23:59:59 UTC';
        }

        $timestamp = strtotime($expiry);
        return $timestamp ? (int) $timestamp : 0;
    }
}

if (!function_exists('matewa_agency_own_site_access_is_active')) {
    function matewa_agency_own_site_access_is_active() {
        if (!function_exists('matewa_agency_registry_get_saved_access_code') || '' === matewa_agency_registry_get_saved_access_code()) {
            return false;
        }

        $stored = function_exists('matewa_agency_registry_get_last_result')
            ? matewa_agency_registry_get_last_result()
            : array();

        if (!is_array($stored) || empty($stored['success'])) {
            return false;
        }

        $status = isset($stored['status']) ? sanitize_key((string) $stored['status']) : '';

        if (!empty($stored['revoked']) || in_array($status, matewa_agency_entitlement_get_blocked_statuses(), true)) {
            return false;
        }

        if (!in_array($status, matewa_agency_entitlement_get_statuses_that_grant_own_site_access(), true)) {
            return false;
        }

        if (empty($stored['own_site_access'])) {
            return false;
        }

        $expiry_ts = matewa_agency_entitlement_get_expiry_timestamp($stored['access_expiry'] ?? '');
        if ($expiry_ts > 0 && time() > $expiry_ts) {
            return false;
        }

        return true;
    }
}

if (!function_exists('matewa_agency_hub_is_active')) {
    function matewa_agency_hub_is_active() {
        if (!matewa_agency_own_site_access_is_active()) {
            return false;
        }

        $stored = function_exists('matewa_agency_registry_get_last_result')
            ? matewa_agency_registry_get_last_result()
            : array();

        return is_array($stored) && !empty($stored['agency_hub']);
    }
}

if (!function_exists('matewa_agency_entitlement_get_summary')) {
    function matewa_agency_entitlement_get_summary() {
        $stored = function_exists('matewa_agency_registry_get_last_result')
            ? matewa_agency_registry_get_last_result()
            : array();
        $stored = is_array($stored) ? $stored : array();

        return array(
            'active'           => matewa_agency_own_site_access_is_active(),
            'agency_hub'       => matewa_agency_hub_is_active(),
            'status'           => sanitize_key((string) ($stored['status'] ?? '')),
            'code'             => sanitize_key((string) ($stored['code'] ?? 'not_checked')),
            'message'          => sanitize_text_field((string) ($stored['message'] ?? '')),
            'agency_id'        => sanitize_key((string) ($stored['agency_id'] ?? '')),
            'agency_name'      => sanitize_text_field((string) ($stored['agency_name'] ?? '')),
            'client_seats'     => isset($stored['client_seats']) ? absint($stored['client_seats']) : 0,
            'access_start'     => sanitize_text_field((string) ($stored['access_start'] ?? '')),
            'access_expiry'    => sanitize_text_field((string) ($stored['access_expiry'] ?? '')),
            'checked_at'       => isset($stored['checked_at']) ? (int) $stored['checked_at'] : 0,
            'masked_key'       => sanitize_text_field((string) ($stored['masked_key'] ?? '')),
            'configured'       => function_exists('matewa_agency_registry_is_configured') ? matewa_agency_registry_is_configured() : false,
        );
    }
}
