<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator;

defined('ABSPATH') || exit;

use CliqThemes\StoreLocator\Extensions\ExtensionLoader;
use CliqThemes\StoreLocator\Schema\SchemaInstaller;
use CliqThemes\StoreLocator\Privacy\Privacy;

/**
 * Cross-cutting platform concerns: capabilities, i18n and the
 * activation/deactivation lifecycle. Keeps the main plugin file thin.
 */
final class Platform
{
    public const CAPABILITY = 'manage_store_locator';

    /**
     * Runtime hooks registered on every load.
     */
    public function boot(): void
    {
        (new Privacy())->register();

        // Dev convenience: `wp cliq-sl reset` wipes all plugin data and rebuilds
        // the schema from scratch.
        if (defined('WP_CLI') && WP_CLI) {
            \WP_CLI::add_command('cliq-sl reset', static function (): void {
                SchemaInstaller::fresh();
                \WP_CLI::success('Store-locator data wiped and schema rebuilt from scratch.');
            });
        }
    }

    /**
     * Activation: install schema and reference data, then grant capability.
     */
    public static function activate(): void
    {
        // Extensions first: a feature's tables are created by the same installer
        // pass, so they have to be listening before it runs.
        ExtensionLoader::boot();

        SchemaInstaller::install();
        self::addCapabilities();
        // The retention job schedules itself once something is retaining data;
        // see Privacy::register().
    }

    /**
     * Deactivation: data and capabilities are preserved; scheduled work is not.
     *
     * Announced, not enumerated: whatever scheduled a job knows its hook.
     */
    public static function deactivate(): void
    {
        /**
         * Fired when the plugin is deactivated.
         */
        do_action('cliq_sl_deactivate');
    }

    /**
     * Grant the management capability to roles that can manage options.
     */
    public static function addCapabilities(): void
    {
        foreach (['administrator'] as $roleName) {
            $role = get_role($roleName);
            if ($role && ! $role->has_cap(self::CAPABILITY)) {
                $role->add_cap(self::CAPABILITY);
            }
        }
    }
}
