<?php
class KavehAPP
{

    public function __construct()
    {

        add_action('admin_footer', [$this, 'add_media_uploader_js']);
        add_action('admin_menu', [$this, 'kaveh_build_menu_page']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_media_uploader']);

    }

    public function kaveh_build_menu_page() {
        add_menu_page(
            __('Kaveh Android App Builder', 'kavehTheme'), // Page title
            __('Kaveh Android App', 'kavehTheme'), // Menu title
            'manage_options', // Capability
            'kaveh_build', // Menu slug
            [$this, 'kaveh_build_admin_page'], // Callback function
            '', // Icon URL (leave empty)
            100 // Position
        );
    
        // Hook to add custom CSS
        add_action('admin_head', [$this, 'custom_menu_icon']);
    }
    
    public function custom_menu_icon() {
        ?>
        <style>
            #toplevel_page_kaveh_build .wp-menu-image {
                background: url('<?php echo KAVEH_TEMPLATE_URI ?>/assets/images/android-svgrepo-com.svg') no-repeat center center !important;
                background-size: contain !important;
            }
            #toplevel_page_kaveh_build .wp-menu-image:before {
                content: '' !important;
            }
            #toplevel_page_kaveh_build div.wp-menu-image {
                width: 28px;
                height: 34px;
            }
        </style>
        <?php
    }
    
    // Enqueue WordPress media uploader scripts
    public function enqueue_media_uploader()
    {
        wp_enqueue_media(); // Enqueue the media uploader
    }

    // Admin page content
    public function kaveh_build_admin_page()
    {
        ?>

        <div class="wrap kaveh_build">
            <h1><?php esc_html_e('Kaveh Android App Builder (Publishable on Bazaar and Google Play)', 'kavehTheme'); ?></h1>
            <p><?php esc_html_e('This section is a new and fresh part of Kaveh, created with great effort by the Moein WordPress team over the past few months. For the first time in the world, it has been built, and naturally, we need your feedback to improve this section. We look forward to receiving your comments and initial feedback.', 'kavehTheme'); ?></p>
            <form method="post" action="">
                <input type="hidden" name="domain"
                    value="<?php echo str_replace(array('http://', 'https://'), '', home_url()); ?>" class="regular-text" />
                <input type="hidden" name="url" value="<?php echo home_url(); ?>" class="regular-text" />

                <table class="form-table">

                    <tr valign="top">
                        <th scope="row"><?php esc_html_e('English Name', 'kavehTheme'); ?></th>
                        <td><input type="text" name="name_en" value="Kaveh" class="regular-text" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php esc_html_e('Persian Name', 'kavehTheme'); ?></th>
                        <td><input type="text" name="name_fa" value="<?php esc_attr_e('Kaveh', 'kavehTheme'); ?>" class="regular-text" /></td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php esc_html_e('Logo', 'kavehTheme'); ?> (<span><?php esc_html_e('Logo size 1024*1024', 'kavehTheme'); ?></span>)</th>
                        <td>
                            <input type="hidden" name="logo_url" id="logo_url" value="" />
                            <button type="button" class="button" id="upload_logo_button"><?php esc_html_e('Select Logo', 'kavehTheme'); ?></button>
                            <div id="logo_preview" style="margin-top: 10px;"></div>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php esc_html_e('Splash Image', 'kavehTheme'); ?> (<span><?php esc_html_e('Splash size 2732*2732', 'kavehTheme'); ?></span>)</th>
                        <td>
                            <input type="hidden" name="splash_url" id="splash_url" value="" />
                            <button type="button" class="button" id="upload_splash_button"><?php esc_html_e('Select Image', 'kavehTheme'); ?></button>
                            <div id="splash_preview" style="margin-top: 10px;"></div>
                        </td>
                    </tr>
                </table>

                <?php submit_button(__('Start App Build', 'kavehTheme')); ?>
            </form>

            <?php
            // Handle form submission
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $this->handle_build_request();
            }
            ?>
        </div>
        <style>
            body.toplevel_page_kaveh_build {
                background: linear-gradient(90deg, #ff9966 0%, #ff5e62 100%) !important;
            }
            .kaveh_build input[type=text] {
                box-shadow: 0 0 0 transparent;
                border-radius: 44px;
                border: none;
                background-color: #eee;
                color: #000;
                padding: 5px 15px !important;
            }
            .kaveh_build {
                background-color: #ffffff;
                width: 60%;
                border-radius: 25px;
                margin: 25px;
                padding: 25px;
            }
            .kaveh_build h1 {
                color: #ff7664;
                font-variation-settings: "wght" 900, "DOTS" 1 !important;
            }
            .kaveh_build button {
                border-radius: 155px !important;
                padding: 3px 25px !important;
            }
            .kaveh_build .button-primary {
                border-radius: 155px !important;
                padding: 3px 25px !important;
                background: linear-gradient(90deg, #ff9966 0%, #ff5e62 100%) !important;
                border:none !important;
            }
        </style>
        <?php
    }

    // Handle the form submission and send the remote request
    public function handle_build_request()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Collect form data
        $domain = sanitize_text_field($_POST['domain']);
        $url = sanitize_text_field($_POST['url']);
        $name_en = sanitize_text_field($_POST['name_en']);
        $name_fa = sanitize_text_field($_POST['name_fa']);
        $logo_url = esc_url_raw($_POST['logo_url']);
        $splash_url = esc_url_raw($_POST['splash_url']);

        // Make sure URLs are provided
        if ($logo_url && $splash_url) {
            $response = $this->send_new_build_request($domain, $url, $name_en, $name_fa, $logo_url, $splash_url);
            echo '<div class="updated"><pre>' . esc_html($response) . '</pre></div>';
            $response = json_decode($response , true);
            $download_link = $response['dl'];
            ?>
            <a target="_blank" href="https://cli.appbin.ir<?php echo $download_link; ?>"><?php esc_html_e('Download Generated App', 'kavehTheme'); ?></a>
            <?php
        } else {
            echo '<div class="error"><p>' . esc_html(__('Please select both a logo and a splash image.', 'kavehTheme')) . '</p></div>';
        }
    }


    public function attachment_url_to_path($url) {
        $upload_dir = wp_upload_dir();
        if (strpos($url, $upload_dir['baseurl']) !== false) {
            $path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
            return $path;
        }
        return false;
    }


    public function send_new_build_request($domain, $url, $name_en, $name_fa, $logo_url, $splash_url)
    {

        $curl = curl_init();
        $authorization = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJsaWNlbnNlX2lkIjoxLCJpYXQiOjE3MTI1MTkxMjAsImV4cCI6MjAyNzg3OTEyMCwiYXVkIjoiU1JWIn0.MRfdw4u_S5YqnkqmwZ49AJ-Gi9qssDMqpkdkUzNFf0fEIQuAmIN2z0rh1uYR7q2QwI195SDEuZKZ2MDtTjehV54Eku3ngitoiQJceIvb-S88xi6-N86bftkEWYWEctZ8VdDZ5dEvFhlAjN2egvV4_dKbtQ4dnzRtrJ9KnaUVh40WRC6_pBhGe45mhBZ3BcNEApbvRz1Ppij5q-o9g7PSNa1xZs20WwqHRJstLMXP3fiva7Dbwxwn5ASzOxHxwxBXAwyadtw2pdpfm10_1_hlOg6ZeAfEDakyvbL50Z0pqVNEDtnrKyatpAy2J3gD8bdkbGlfMkMjyNyumfSbxvAUuw";
        $data = [
            'domain' => $domain,
            'url' => $url,
            'name_en' => $name_en,
            'name_fa' => $name_fa,
            "logo" => new CURLFile($this->attachment_url_to_path($logo_url)),
            "splash" => new CURLFile($this->attachment_url_to_path($splash_url)),
        ];
        // Set the Authorization header with "Token" prefix
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://cli.appbin.ir/api/v1/builds/start",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 30,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => [
                "Authorization: $authorization",
                "Content-Type: multipart/form-data"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return __('cURL Error #:', 'kavehTheme') . $err;
        } else {
            return $response;
        }

    }


    // Hook to add custom JavaScript for handling media uploader
    public function add_media_uploader_js()
    {
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function ($) {
                var logoUploader, splashUploader;

                // Logo upload button
                $('#upload_logo_button').on('click', function (e) {
                    e.preventDefault();

                    // If the uploader object has already been created, reopen the dialog
                    if (logoUploader) {
                        logoUploader.open();
                        return;
                    }

                    // Extend the wp.media object
                    logoUploader = wp.media.frames.file_frame = wp.media({
                        title: '<?php esc_html_e('Select Logo', 'kavehTheme'); ?>',
                        button: {
                            text: '<?php esc_html_e('Select Logo', 'kavehTheme'); ?>'
                        },
                        multiple: false
                    });

                    // When a file is selected, grab the URL and set it as the value of the input field
                    logoUploader.on('select', function () {
                        var attachment = logoUploader.state().get('selection').first().toJSON();
                        $('#logo_url').val(attachment.url);
                        $('#logo_preview').html('<img src="' + attachment.url + '" style="max-width:100px;" />');
                    });

                    // Open the uploader dialog
                    logoUploader.open();
                });

                // Splash upload button
                $('#upload_splash_button').on('click', function (e) {
                    e.preventDefault();

                    // If the uploader object has already been created, reopen the dialog
                    if (splashUploader) {
                        splashUploader.open();
                        return;
                    }

                    // Extend the wp.media object
                    splashUploader = wp.media.frames.file_frame = wp.media({
                        title: '<?php esc_html_e('Select Splash Image', 'kavehTheme'); ?>',
                        button: {
                            text: '<?php esc_html_e('Select Splash Image', 'kavehTheme'); ?>'
                        },
                        multiple: false
                    });

                    // When a file is selected, grab the URL and set it as the value of the input field
                    splashUploader.on('select', function () {
                        var attachment = splashUploader.state().get('selection').first().toJSON();
                        $('#splash_url').val(attachment.url);
                        $('#splash_preview').html('<img src="' + attachment.url + '" style="max-width:100px;" />');
                    });

                    // Open the uploader dialog
                    splashUploader.open();
                });
            });
        </script>
        <?php
    }


}