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

/**
 * Plan helpers — Freemius is source of truth.
 * Free  = full manual workflow (real value for small sites).
 * Pro   = automation (bulk, background, WebP, backups).
 * Agency = Pro + unlimited sites + white-label.
 */

function aiio_default_settings() {
    return [
        'jpeg_quality' => 82,
        'png_compression' => 6,
        'size_threshold_kb' => 200,
        'webp_enabled' => 0,
        'webp_priority' => 'balanced',
        'avif_enabled' => 0,
        'avif_quality' => 50,
        'video_av1_enabled' => 0,
        'video_av1_crf' => 32,
        'auto_optimize_upload' => 0,
        'onboarding_done' => 0,
        'notify_email_enabled' => 0,
        'notify_email_failures' => 1,
        'notify_email_to' => get_option('admin_email'),
        'notify_include_csv' => 1,
        'whitelabel_enabled' => 0,
        'whitelabel_brand' => '',
        'whitelabel_logo' => '',
        'only_etch_images' => 0,
        'only_used_images' => 0,
        'exclude_filename_patterns' => "*-logo*\n*favicon*\n*icon-*",
        'lcp_budget_kb' => 200,
        'etch_native_ui' => 1,
    ];
}

function aiio_get_settings() {
    return wp_parse_args(get_option(AIIO_OPTION, []), aiio_default_settings());
}

function aiio_update_settings($settings) {
    update_option(AIIO_OPTION, wp_parse_args($settings, aiio_default_settings()));
}

function aiio_brand_name() {
    $s = aiio_get_settings();
    if (!empty($s['whitelabel_enabled']) && !empty($s['whitelabel_brand'])) {
        return $s['whitelabel_brand'];
    }
    return 'Pewit AI Image Optimizer';
}

function aiio_plan() {
    return 'free';
}

function aiio_is_pro_build() {
    return defined('AIIO_PRO') && AIIO_PRO;
}

function aiio_is_pro() {
    return true;
}

function aiio_is_agency() {
    return true;
}

function aiio_is_trial() {
    return false;
}

/**
 * Feature gate (no-op): every built-in feature is free and fully functional in this build.
 * Background jobs, bulk ops, WebP/AVIF sidecars, video AV1 and backups are all available to
 * everyone. Plan/badge helpers below stay truthful for display only and never block a feature.
 */
function aiio_can_automate() {
    return true;
}

function aiio_plan_label() {
    $map = ['free' => 'Free', 'pro' => 'Pro', 'agency' => 'Agency', 'trial' => 'Trial'];
    $plan = aiio_plan();
    if (aiio_is_trial() && $plan === 'free') {
        return 'Trial';
    }
    return $map[$plan] ?? 'Free';
}

function aiio_upgrade_url() {
    if (function_exists('aiio_freemius')) {
        $fs = aiio_freemius();
        if ($fs && method_exists($fs, 'get_upgrade_url')) {
            $url = $fs->get_upgrade_url();
            if ($url) {
                return $url;
            }
        }
    }
    return 'https://pewitlabs.com/product-ai-image-optimizer.html';
}

function aiio_account_url() {
    if (function_exists('aiio_freemius')) {
        $fs = aiio_freemius();
        if ($fs && method_exists($fs, 'get_account_url')) {
            $url = $fs->get_account_url();
            if ($url) {
                return $url;
            }
        }
    }
    return '';
}

function aiio_whitelabel() {
    $s = aiio_get_settings();
    $on = !empty($s['whitelabel_enabled']);
    return [
        'enabled' => $on,
        'brand'   => $on && !empty($s['whitelabel_brand']) ? (string) $s['whitelabel_brand'] : '',
        'logo'    => $on && !empty($s['whitelabel_logo']) ? (string) $s['whitelabel_logo'] : '',
    ];
}

function aiio_docs_url($path = '') {
    $base = 'https://pewitlabs.com/docs/pewit-ai-image-optimizer/';
    return $path ? $base . ltrim($path, '/') : $base;
}

function aiio_automation_upgrade_message() {
    return __('Bulk optimize, WebP/AVIF conversion, video AV1 sidecars and backups are all included for free. Optional managed support is available as a paid service.', 'pewit-ai-image-optimizer');
}

function aiio_verify_ajax() {
    check_ajax_referer('aiio_nonce', 'nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
    }
}

function aiio_current_page_slug() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin page slug; no state change.
    return isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : 'pewit-ai-image-optimizer';
}

function aiio_admin_page_url($slug = 'pewit-ai-image-optimizer') {
    return admin_url('admin.php?page=' . rawurlencode($slug));
}

/**
 * Backup root under uploads (filterable). Shares the same parent folder as the rest of the
 * PEWIT Labs suite (uploads/pewit-labs-backups) so snapshots live together.
 *
 * @param string $subdir Plugin folder, e.g. pewit-ai-image-optimizer.
 */
function aiio_backup_root($subdir = '') {
    $upload = wp_get_upload_dir();
    $base = trailingslashit($upload['basedir']) . 'pewit-labs-backups';
    $base = trailingslashit(apply_filters('aiio_backup_base_dir', $base));
    if ($subdir !== '') {
        $base = trailingslashit($base) . trim($subdir, '/');
    }
    if (!file_exists($base)) {
        wp_mkdir_p($base);
    }
    return trailingslashit($base);
}
