<?php
// Ensure the file is not accessed directly
if ( !defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Updater for version 2.1.2
 * Updates CV pages and user roles
 *
 * @package BWDCV
 * @version 2.1.2
 */
class BWDCV_Updater_2_1_2 extends BWDCV_Base_Updater {

    protected $target_version = '2.1.2';

    /**
     * Perform the actual update logic
     *
     * @throws Exception If update fails
     */
    protected function perform_update() {
        global $wpdb;

        // First, handle old folder cleanup
        $this->cleanup_old_plugin_folder();

        // Get all editor users
        $users = get_users( [
            'fields' => [ 'ID', 'user_login' ],
            'role'   => 'editor',
            'number' => -1
        ] );

        if ( empty( $users ) ) {
            error_log( 'BWDCV Update 2.1.2: No editor users found' );
            $this->set_success_notice( 'BWDCV Plugin updated successfully! No editor users found to update.' );
            return; // Not an error, just nothing to update
        }

        $updated_posts = 0;
        $updated_users = 0;
        $errors = [];

        foreach ( $users as $user ) {
            try {
                $result = $this->update_user_cv_pages( $user );
                $updated_posts += $result['posts'];

                if ( $result['posts'] > 0 ) {
                    $user_updated = $this->update_user_role( $user );
                    if ( $user_updated ) {
                        $updated_users++;
                    }
                }

            } catch ( Exception $e ) {
                $errors[] = "User {$user->user_login}: " . $e->getMessage();
                error_log( "Error updating user {$user->user_login}: " . $e->getMessage() );
            }
        }

        // Log results
        error_log( "BWDCV Update 2.1.2 completed: {$updated_posts} CV pages updated, {$updated_users} users updated" );

        if ( ! empty( $errors ) ) {
            error_log( 'BWDCV Update 2.1.2 errors: ' . implode( ', ', $errors ) );
        }

        // Set appropriate notice
        if ( $updated_posts > 0 || $updated_users > 0 ) {
            $this->set_success_notice( sprintf(
                'BWDCV Plugin updated successfully! Updated %d CV pages and %d users from editor to cv_editor role.',
                $updated_posts,
                $updated_users
            ) );
        } else {
            $this->set_success_notice( 'BWDCV Plugin updated successfully! No CV pages or users needed updating.' );
        }

        // If there were errors but some updates succeeded, don't fail completely
        if ( ! empty( $errors ) && ( $updated_posts === 0 && $updated_users === 0 ) ) {
            throw new Exception( 'All updates failed: ' . implode( ', ', array_slice( $errors, 0, 3 ) ) );
        }
    }

    /**
     * Add this new method to your existing BWDCV_Updater_2_1_2 class
     */
    private function cleanup_old_plugin_folder() {
        try {
            // Include the BWDCV_Delete_Old_Folder class
            $deleter_file = plugin_dir_path( __FILE__ ) . '../delete_old_folder.php';
            if ( file_exists( $deleter_file ) ) {
                require_once $deleter_file;
            } else {
                // Try alternative path
                $deleter_file = plugin_dir_path( BWDCV_FILE ) . 'includes/updater/updates/delete_old_folder.php';
                if ( file_exists( $deleter_file ) ) {
                    require_once $deleter_file;
                } else {
                    error_log( 'BWDCV: BWDCV_Delete_Old_Folder class file not found' );
                    return;
                }
            }

            // Create and run the folder deleter
            $folder_deleter = new BWDCV_Delete_Old_Folder( 'wp-cv-builder-saas' );
            $cleanup_success = $folder_deleter->delete_old_folder();

            if ( $cleanup_success ) {
                error_log( 'BWDCV: Old plugin folder cleanup completed successfully' );
            } else {
                $errors = $folder_deleter->get_error_message();
                error_log( 'BWDCV: Old plugin folder cleanup failed: ' . $errors );
                // Don't throw exception here as this shouldn't block the main update
            }

        } catch ( Exception $e ) {
            error_log( 'BWDCV: Exception during old folder cleanup: ' . $e->getMessage() );
            // Don't throw - this is cleanup and shouldn't block main update
        }
    }

    /**
     * Update CV pages for a specific user
     *
     * @param WP_User|stdClass $user User object
     * @return array Array with 'posts' count
     * @throws Exception If database update fails
     */
    private function update_user_cv_pages( $user ): array {
        global $wpdb;

        $cv_page_title = $user->user_login . "'s CV Page";
        $updated_posts = 0;

        // Find pages with this exact title
        $posts = $wpdb->get_results( $wpdb->prepare(
            "SELECT ID, post_title FROM {$wpdb->posts}
             WHERE post_type = 'page'
             AND post_title = %s
             AND post_status IN ('publish', 'draft', 'private')",
            $cv_page_title
        ) );

        if ( empty( $posts ) ) {
            return [ 'posts' => 0 ];
        }

        // Update posts to 'cv' post type
        foreach ( $posts as $post ) {
            $result = $wpdb->update(
                $wpdb->posts,
                [ 'post_type' => 'cv' ],
                [ 'ID' => $post->ID ],
                [ '%s' ],
                [ '%d' ]
            );

            if ( $result !== false ) {
                // Clear cache for this post
                clean_post_cache( $post->ID );
                $updated_posts++;
                error_log( "Updated post ID {$post->ID} to cv post type" );
            } else {
                throw new Exception( "Failed to update post ID {$post->ID} to cv post type" );
            }
        }

        return [ 'posts' => $updated_posts ];
    }

    /**
     * Update user role from editor to cv_editor
     *
     * @param WP_User|stdClass $user User object
     * @return bool Success status
     */
    private function update_user_role( $user ): bool {
        $user_obj = new WP_User( $user->ID );

        if ( ! in_array( 'editor', $user_obj->roles ) ) {
            return false; // User is no longer an editor
        }

        // Remove editor role and add cv_editor role
        $user_obj->remove_role( 'editor' );
        $user_obj->add_role( 'cv_editor' );

        // Verify the role was updated
        $updated_user = new WP_User( $user->ID );
        $success = in_array( 'cv_editor', $updated_user->roles ) &&
                   ! in_array( 'editor', $updated_user->roles );

        if ( $success ) {
            error_log( "Updated user {$user->user_login} (ID: {$user->ID}) from editor to cv_editor" );
        }

        return $success;
    }

    /**
     * Optional: Custom validation before running update
     * Override the parent method if needed
     */
    protected function should_update() {
        // Check if cv_editor role exists before trying to assign it
        if ( ! get_role( 'cv_editor' ) ) {
            error_log( 'BWDCV Update 2.1.2: cv_editor role does not exist. Please ensure it is created before running this update.' );
            $this->set_error_notice( 'Update failed: cv_editor role does not exist. Please contact support.' );
            return false;
        }

        return parent::should_update();
    }
}
