<?php

namespace Flyerimage\Core\Init;

use Flyerimage\App\Services\FlyerImageService;

/**
 * Plugin Installer class
 */
class Installer
{

    /**
     * Run the installer
     * 
     * @return void
     */
    public function run()
    {
        $this->add_version();
        $this->create_tables();
    }

    /**
     * Add plugin version
     * 
     * @return void
     */
    public function add_version()
    {
        $installed = get_option('flyer_image_installed_V002596854');
        if (!$installed) {
            update_option('flyer_image_installed_V002596854', time());
        }
    }

    /**
     * Create plugin required tables by schema
     * 
     * @return void
     */
    public function create_tables()
    {
        $version = get_option("flyer_image_version_V002596854");
        //if ($version != FLYER_IMAGE_VERSION) {
            update_option('flyer_image_version_V002596854', FLYER_IMAGE_VERSION);
            (new FlyerImageService())->doMigration();

            // Store API URL in WordPress database instead of file
            $api_url = get_site_url() . '/index.php/wp-json/' . FLYER_IMAGE_WP_PLUGIN_API_BASE_V252202251;
            update_option('flyeri_api_url', $api_url);
            
            // Migrate existing images from plugin directory to uploads directory
            $this->migrate_images_to_uploads();
        //}
    }

    /**
     * Migrate existing images from plugin directory to uploads directory
     * @return void
     */
    private function migrate_images_to_uploads() {
        $old_images_dir = FLYER_IMAGE_PUBLIC_PATH . '/images';
        $upload_dir = wp_upload_dir();
        $new_images_dir = $upload_dir['basedir'] . '/flyerimage';
        
        // Create flyerimage directory in uploads if it doesn't exist
        if (!file_exists($new_images_dir)) {
            wp_mkdir_p($new_images_dir);
        }
        
        // Check if old images directory exists
        if (file_exists($old_images_dir) && is_dir($old_images_dir)) {
            $files = glob($old_images_dir . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
            
            foreach ($files as $file) {
                $filename = basename($file);
                $new_path = $new_images_dir . '/' . $filename;
                
                // Only move if file doesn't already exist in uploads
                if (!file_exists($new_path)) {
                    copy($file, $new_path);
                }
            }
        }
    }

    /**
     * @return void
     */
    public function uninstall() {
        global $wpdb;

        $wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}fi_flyerimage_images`" );
        $wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}fi_flyerimages`" );
    }

    /**
     * @return void
     */
    public function deactivation() {

    }
}