<?php

namespace Webien\Setup;
use StoutLogic\AcfBuilder\FieldsBuilder;

/*
 * Clean up some WP stuff and add ACF options for them
 */

class Updates
{

    static $acfGroup;

    public static function init()
    {

        // Handle access to plugin & theme upload/update pages
        add_action('admin_init', [__CLASS__, 'block_restricted_pages_for_users'], 99999);
        add_action('admin_head', [__CLASS__, 'hide_stuff_for_users'], 99999);




        // Option page
        // Start ACF section, (Optional stuff)
        self::$acfGroup = new FieldsBuilder(
            'webien_update_tools', ['title' => __('Uppdateringar', 'webien')]
        );

        self::addUpdateControls();

        // End ACF section
        self::$acfGroup
            ->setLocation('options_page', '==', 'acf-options-webien');
            acf_add_local_field_group(self::$acfGroup->build());



        // Handle Ajax calls
        add_action( 'wp_ajax_webien_update_create_db_dump', [__CLASS__, 'webien_update_create_db_dump'] );
        add_action( 'wp_ajax_webien_update_back_db_dump', [__CLASS__, 'webien_update_recover_db_dump'] );
        add_action( 'wp_ajax_webien_update_remove_db_dump', [__CLASS__, 'webien_update_remove_db_dump'] );


    }


    private static function addUpdateControls()
    {

        $buttonHtml = '<div class="loading"></div><div class="btns"><button id="webien_update_create_db_dump" type="button" class="button button-secondary">Skapa databasdump</button><button id="webien_update_back_db_dump" type="button" class="button button-secondary">Backa till skapad databasdump</button><button id="webien_update_remove_db_dump" type="button" class="button button-secondary">Ta bort skapad databasdump</button></div>';

        $available = get_option('webien_db_dump');
        $availableDbDumps = '';
        if($available) {
            $availableDbDumps = '<div id="webien_update_db_dumps">Tillgänglig backup finns fån <span>' . date('Y-m-d H:i:s', (int)$available) . '</span></div>';
        }


        self::$acfGroup
            ->addTab('webien_updates_db_tab', ['label' => 'Databasbackup']);

        self::$acfGroup
            ->addMessage('webien_update_buttons', 'Knappar', [
                'label' => 'Hjälpknappar för uppdateringar',
                'instructions' => '',
                'message' => 'Använd dessa funktioner när du gör upppdateringar på siten för att kunna backa om det skule behövas.' . $buttonHtml . $availableDbDumps,
                'new_lines' => 'wpautop',
                'esc_html' => 0,
            ]);

        self::$acfGroup
            ->addTab('webien_updates_users_tab', ['label' => 'Behöriga användare']);


        self::$acfGroup
            ->addTrueFalse('webien_use_updates_users', [
                'label' => __('', 'webien'),
                'required' => 0,
                'instructions' => __('Lås ut alla andra än specificerade användare från uppdateringar och pluginhantering. Om du inte har access nedan kommer du låsas ut efter att du sparar.', 'webien'),
                'conditional_logic' => [],
                'wrapper' => [
                ],
                'message' => __('Använd denna funktion', 'webien'),
                'default_value' => 1,
            ]);


        self::$acfGroup
            ->addUser('webien_updates_users', [
                'label' => __('Användare med access att uppdatera', 'webien'),
                'instructions' => __('Haus har alltid tillgång oavsett vad som väljs här.', 'webien'),
                'required' => 0,
                'role' => '',
                'allow_null' => 0,
                'multiple' => 1,
                'return_format' => 'id',
            ]);

    }


    public static function webien_update_create_db_dump()
    {

        $time = time();

        $fileName = sys_get_temp_dir() . '/webien_db_' . $time . '.sql';
        $command = "cd " . ABSPATH . " && wp db export " . $fileName;
        $output = shell_exec($command);


        if($output){
            update_option('webien_db_dump', $time);
            wp_send_json_success( 'Success' );
        } else {
            wp_send_json_error( 'Error' );
        }
    }


    public static function webien_update_recover_db_dump()
    {

        $db = get_option('webien_db_dump');
        if(!$db) {
            wp_send_json_error( 'No backup found' );
        }

        $fileName = sys_get_temp_dir() . '/webien_db_' . $db . '.sql';
        $command = "cd " . ABSPATH . " && wp db import " . $fileName;
        $output = shell_exec($command);


        if($output){
            delete_option('webien_db_dump');
            wp_send_json_success( 'Success' );
        } else {
            wp_send_json_error( 'Error' );
        }
    }



    public static function webien_update_remove_db_dump()
    {

        $db = get_option('webien_db_dump');
        if(!$db) {
            wp_send_json_success( 'Success' );
        }

        $fileName = sys_get_temp_dir() . '/webien_db_' . $db . '.sql';
        $command = "rm " . $fileName;
        shell_exec($command);

        delete_option('webien_db_dump');
        wp_send_json_success( 'Success' );

    }



    static function block_restricted_pages_for_users() {

        // Make sure we handle cases where ACF has not been saved
        $useRestriction = get_field('webien_use_updates_users', 'option');
        if(!$useRestriction && $useRestriction !== NULL) {
            return;
        }

        $allowed_users = [1]; // Should be Haus user

        $haus_user = get_user_by('login', 'haus');
        $haus_email = get_user_by('email', 'service@haus.se');
        if($haus_user) {
            $allowed_users[] = $haus_user->ID;
            $allowed_users[] = $haus_email->ID;
        }

        // Add any user with a haus email set as the user email
        $users_with_haus_email = get_users( array(
            'search'         => '*@haus.se',
            'search_columns' => array( 'user_email' ),
        ) );
        foreach($users_with_haus_email as $user) {
            $allowed_users[] = $user->ID;
        }


        // Also include the users specified in ACF
        $users = get_field('webien_updates_users', 'option');
        if($users) {
            $allowed_users = array_merge($allowed_users, $users);
        }


        if (!in_array(get_current_user_id(), $allowed_users)) {
            global $pagenow;

            if(isset($_GET['page']) && $_GET['page'] == 'acf-options-webien') {
                $pagenow = 'webien-settings';
            }

            // Block access to the plugin & theme upload/update pages
            if (in_array($pagenow, ['plugins.php', 'plugin-install.php', 'plugin-editor.php', 'update-core.php', 'webien-settings'], true)) {
                wp_die(
                    __('<div style="text-align: center; padding: 50px; font-family: Arial, sans-serif;">
        <img src="' . WEBIEN_PLUGIN_URL . '/assets/images/lock.svg" alt="Access Denied" style="max-width: 300px; margin-bottom: 20px;">
        <h1 style="color: #000; font-size: 36px; margin-bottom: 10px;">Behörighet saknas</h1>
        <p style="font-size: 16px; color: #555;">Du saknar behörighet för att hantera detta.<br>Vänligen kontakta <a href="mailto:support@haus.se">supporten</a> om det skulle behövas.</p>
        <a class="button button-primary" href="'.home_url().'/wp-admin" style=" margin-top: 20px;background: #2271b1;border-color:#2271b1;color:#fff;text-decoration: none;text-shadow: none;height: 36px;display: inline-flex;padding: 0 20px;align-items: center;">&larr; Tillbaka</a>
    </div>', 'your-text-domain'),
                    __('Access Denied', 'your-text-domain'),
                    ['response' => 403]
                );
            }
        }

    }


    static function hide_stuff_for_users()
    {

        // Make sure we handle cases where ACF has not been saved
        $useRestriction = get_field('webien_use_updates_users', 'option');
        if(!$useRestriction && $useRestriction !== NULL) {
            return;
        }

        $allowed_users = [1]; // Should be Haus user

        $haus_user = get_user_by('login', 'haus');
        $haus_email = get_user_by('email', 'service@haus.se');
        if($haus_user) {
            $allowed_users[] = $haus_user->ID;
            $allowed_users[] = $haus_email->ID;
        }

        // Add any user with a haus email set as the user email
        $users_with_haus_email = get_users( array(
            'search'         => '*@haus.se',
            'search_columns' => array( 'user_email' ),
        ) );
        foreach($users_with_haus_email as $user) {
            $allowed_users[] = $user->ID;
        }

        // Also include the users specified in ACF
        $users = get_field('webien_updates_users', 'option');
        if ($users) {
            $allowed_users = array_merge($allowed_users, $users);
        }


        if (!in_array(get_current_user_id(), $allowed_users)) {

            // Hide the update button
            echo '<style>
                #menu-plugins {
                    display: none !important;
                }
                #toplevel_page_acf-options-webien {
                    display: none !important;
                }
                a[href="update-core.php"] {
                    display: none !important;
                }
            </style>';
        }

    }


}