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

class EMPR_Deactivator {

    public static function run() {
        wp_clear_scheduled_hook( 'empr_job_sheet_cleanup' );
        wp_clear_scheduled_hook( 'empr_login_logs_cleanup' );
        flush_rewrite_rules();
    }

    /**
     * Fired when the plugin is uninstalled via WordPress.
     * Removes all plugin data: tables, options, roles, caps, and pages.
     * Does NOT touch Freemius-owned data (fs_* options).
     */
    public static function uninstall() {
        if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
            return;
        }

        global $wpdb;

        // Drop all seven custom tables.
        $tables = array(
            $wpdb->prefix . 'emr_shifts',
            $wpdb->prefix . 'emr_assignments',
            $wpdb->prefix . 'emr_leave',
            $wpdb->prefix . 'emr_attendance',
            $wpdb->prefix . 'emr_availability',
            $wpdb->prefix . 'emr_swap_requests',
            $wpdb->prefix . 'emr_leave_balances',
            $wpdb->prefix . 'emr_login_logs',
        );
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
        // Reason: DROP TABLE on internal plugin tables during
        // uninstall. Table names are hardcoded {$wpdb->prefix}emr_*
        // constants built from the $tables array above.
        // prepare() cannot be used for DDL statements.
        foreach ( $tables as $table ) {
            $wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
        }
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange

        // Delete all plugin-created WordPress pages.
        $page_options = array(
            'empr_page_dashboard',
            'empr_page_roster',
            'empr_page_leave',
            'empr_page_attendance',
            'empr_page_availability',
        );
        foreach ( $page_options as $opt ) {
            $page_id = (int) get_option( $opt );
            if ( $page_id ) {
                wp_delete_post( $page_id, true );
            }
        }

        // Delete all empr_* options.
        $options = array(
            'empr_version', 'empr_activated_at',
            'empr_company_name', 'empr_departments', 'empr_locations',
            'empr_week_start', 'empr_primary_color',
            'empr_allow_self_clock', 'empr_leave_enabled',
            'empr_hours_fulltime', 'empr_hours_parttime',
            'empr_leave_balance_enabled',
            'empr_annual_leave_ft', 'empr_annual_leave_pt',
            'empr_sick_leave_ft', 'empr_sick_leave_pt',
            'empr_supervisor_see_pay_rate',
            'empr_admin_include_self', 'empr_admin_include_all',
            'empr_public_roster_shortcode',
            'empr_payroll_enabled', 'empr_tax_enabled', 'empr_tax_rate',
            'empr_daily_budget_enabled', 'empr_daily_budget',
            'empr_daily_budget_per_day_enabled',
            'empr_daily_budget_mon', 'empr_daily_budget_tue', 'empr_daily_budget_wed',
            'empr_daily_budget_thu', 'empr_daily_budget_fri', 'empr_daily_budget_sat', 'empr_daily_budget_sun',
            'empr_notifications_enabled', 'empr_profile_mode_enabled',
            'empr_job_sheet_enabled', 'empr_job_sheet_auto_delete',
            'empr_page_dashboard', 'empr_page_roster', 'empr_page_leave',
            'empr_page_attendance', 'empr_page_availability',
            'empr_penalty_rate_enabled', 'empr_saturday_rate', 'empr_sunday_rate',
            'empr_manager_settings_access',
            'empr_wizard_completed',
            'empr_trial_expired_notice_dismissed',
            'empr_login_logs_enabled', 'empr_login_logs_retention',
            // Legacy state that may be left behind by an older install — no active
            // logic in this build reads it; deleted here only so uninstall leaves
            // nothing of it behind.
            'empr_last_known_plan', 'empr_plan_access_blocked',
            'empr_shortcode_migration_done',
            // Set by the legacy-page retirement migration. Listing them here is
            // harmless where they are never written.
            'empr_legacy_pages_migration_done', 'empr_legacy_pages_drafted',
        );
        foreach ( $options as $opt ) {
            delete_option( $opt );
        }

        // Remove per-admin self-inclusion user meta (stored since v2.4.8).
        $all_admins = get_users( array( 'role' => 'administrator', 'fields' => 'ID', 'number' => -1 ) );
        foreach ( $all_admins as $uid ) {
            delete_user_meta( (int) $uid, 'empr_admin_include_self' );
        }

        // Remove all three custom roles.
        remove_role( 'emr_manager' );
        remove_role( 'emr_supervisor' );
        remove_role( 'emr_employee' );

        // Strip all custom capabilities from the administrator role.
        $admin = get_role( 'administrator' );
        if ( $admin ) {
            $caps = array(
                'emr_manage_roster', 'emr_assign_shifts', 'emr_approve_leave',
                'emr_view_all_staff', 'emr_view_attendance', 'emr_edit_attendance',
                'emr_view_reports', 'emr_manage_settings', 'emr_view_own_shifts',
                'emr_clock_in_out', 'emr_submit_leave', 'emr_set_availability',
            );
            foreach ( $caps as $cap ) {
                $admin->remove_cap( $cap );
            }
        }
    }
}
