<?php
/**
 * Prevents Flavor plugin from being deactivated or deleted via WP admin.
 */

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

class Flavor_Plugin_Guard {

    private $our_plugin = 'flavor/flavor.php';

    public function __construct() {
        if ( is_admin() ) {
            add_filter( 'plugin_action_links', [ $this, 'hide_action_links' ], 99, 2 );
            add_action( 'admin_init', [ $this, 'intercept_deactivation' ] );
        }
        // Runs before active_plugins option is written — keeps plugin in the list
        add_filter( 'pre_update_option_active_plugins', [ $this, 'ensure_active' ], 99, 2 );
    }

    public function hide_action_links( $actions, $plugin_file ) {
        if ( $plugin_file === $this->our_plugin ) {
            unset( $actions['deactivate'] );
            unset( $actions['delete'] );
            unset( $actions['edit'] );
        }
        return $actions;
    }

    public function intercept_deactivation() {
        $action     = isset( $_GET['action'] ) ? $_GET['action'] : '';
        $plugin     = isset( $_GET['plugin'] ) ? urldecode( $_GET['plugin'] ) : '';

        // Single-plugin deactivation or deletion URL
        if ( in_array( $action, [ 'deactivate', 'delete-plugin' ], true ) && $plugin === $this->our_plugin ) {
            wp_redirect( admin_url( 'plugins.php' ) );
            exit;
        }

        // Bulk deactivation — remove our plugin from the checked list before it is processed
        $bulk_action = isset( $_POST['action'] ) ? $_POST['action'] :
                       ( isset( $_POST['action2'] ) ? $_POST['action2'] : '' );
        if ( in_array( $bulk_action, [ 'deactivate-selected' ], true ) && ! empty( $_POST['checked'] ) ) {
            $_POST['checked'] = array_values( array_filter(
                (array) $_POST['checked'],
                function ( $p ) { return $p !== $this->our_plugin; }
            ) );
        }
    }

    public function ensure_active( $new_value, $old_value ) {
        // If the plugin was active and is being removed from the list — put it back
        if ( in_array( $this->our_plugin, (array) $old_value, true ) &&
             ! in_array( $this->our_plugin, (array) $new_value, true ) ) {
            $new_value[] = $this->our_plugin;
        }
        return $new_value;
    }
}
