<?php

class Edocman_Lite_Admin_Documents {

    private $per_page = 20;

    public function __construct() {
        add_action( 'admin_post_edocman_lite_save_document', array( $this, 'handle_form_submission' ) );
    }

    /**
     * Build a flat, hierarchically-indented list from all categories.
     */
    private function build_dropdown_tree( $categories, $parent_id = 0, $level = 0 ) {
        $tree = array();
        foreach ( $categories as $category ) {
            if ( (int) $category->parent_id === (int) $parent_id ) {
                $category->level         = $level;
                $prefix                  = $level > 0 ? str_repeat( '— ', $level ) : '';
                $category->title_display = $prefix . $category->title;
                $tree[]                  = $category;
                $children                = $this->build_dropdown_tree( $categories, $category->id, $level + 1 );
                $tree                    = array_merge( $tree, $children );
            }
        }
        return $tree;
    }

    public function display_documents_page() {
        $this->display_admin_notices();
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : 'list';

        switch ( $action ) {
            case 'add':
                $this->display_add_document_form();
                break;
            case 'edit':
                $this->display_edit_document_form();
                break;
            default:
                $this->display_documents_list();
                break;
        }
    }

    private function display_add_document_form() {
        $database   = new Edocman_Lite_Database();
        $categories = $database->get_all_categories( false );
        $categories = $this->build_dropdown_tree( $categories );

        include EDOCMAN_LITE_PLUGIN_PATH . 'admin/partials/documents-form.php';
    }

    private function display_edit_document_form() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $document_id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;

        if ( ! $document_id ) {
            echo '<div class="notice notice-error"><p>' . esc_html__( 'Invalid document ID.', 'edocman-lite' ) . '</p></div>';
            $this->display_documents_list();
            return;
        }

        $database = new Edocman_Lite_Database();
        $document = $database->get_document( $document_id );

        if ( ! $document ) {
            echo '<div class="notice notice-error"><p>' . esc_html__( 'Document not found.', 'edocman-lite' ) . '</p></div>';
            $this->display_documents_list();
            return;
        }

        $categories          = $database->get_all_categories( false );
        $categories          = $this->build_dropdown_tree( $categories );
        $document_categories = $database->get_document_categories( $document_id );

        $edocman_lite_main_category_id                  = 0;
        $edocman_lite_selected_additional_categories    = array();

        foreach ( $document_categories as $cat ) {
            if ( $cat->is_main_category ) {
                $edocman_lite_main_category_id = intval( $cat->category_id );
            } else {
                $edocman_lite_selected_additional_categories[] = intval( $cat->category_id );
            }
        }

        // Backward compat: if no main category marked, use first one.
        if ( $edocman_lite_main_category_id === 0 && ! empty( $document_categories ) ) {
            $edocman_lite_main_category_id = intval( $document_categories[0]->category_id );
        }

        include EDOCMAN_LITE_PLUGIN_PATH . 'admin/partials/documents-form.php';
    }

    private function display_admin_notices() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! isset( $_GET['message'] ) ) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $message = sanitize_key( wp_unslash( $_GET['message'] ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $count = isset( $_GET['count'] ) ? intval( $_GET['count'] ) : 0;

        $messages = array(
            'created'          => __( 'Document created successfully.', 'edocman-lite' ),
            'updated'          => __( 'Document updated successfully.', 'edocman-lite' ),
            'deleted'          => __( 'Document deleted successfully.', 'edocman-lite' ),
            /* translators: %s: number of documents deleted */
            'bulk_deleted'     => sprintf( _n( '%s document deleted successfully.', '%s documents deleted successfully.', $count, 'edocman-lite' ), $count ),
            /* translators: %s: number of documents published */
            'bulk_published'   => sprintf( _n( '%s document published successfully.', '%s documents published successfully.', $count, 'edocman-lite' ), $count ),
            /* translators: %s: number of documents unpublished */
            'bulk_unpublished' => sprintf( _n( '%s document unpublished successfully.', '%s documents unpublished successfully.', $count, 'edocman-lite' ), $count ),
            'bulk_error'            => __( 'No documents were affected by the bulk action.', 'edocman-lite' ),
            'error'                 => __( 'Error saving document.', 'edocman-lite' ),
            'file_error'            => __( 'Error uploading file.', 'edocman-lite' ),
            'file_type_not_allowed' => __( 'File type is not allowed.', 'edocman-lite' ),
            'file_too_large'        => __( 'File exceeds the maximum allowed size.', 'edocman-lite' ),
        );

        if ( isset( $messages[ $message ] ) ) {
            $is_error = ( strpos( $message, 'error' ) !== false || strpos( $message, 'not_allowed' ) !== false || strpos( $message, 'too_large' ) !== false );
            $class    = $is_error ? 'notice-error' : 'notice-success';
            echo '<div class="notice ' . esc_attr( $class ) . ' is-dismissible"><p>' . esc_html( $messages[ $message ] ) . '</p></div>';
        }
    }

    private function display_documents_list() {
        // Handle bulk actions first.
        $this->handle_bulk_actions();

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $current_page    = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $search          = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $category_filter = isset( $_GET['category_filter'] ) ? intval( $_GET['category_filter'] ) : 0;

        $database   = new Edocman_Lite_Database();
        $documents  = $database->get_documents( $category_filter, false );
        $categories = $database->get_categories( 0, false );

        include EDOCMAN_LITE_PLUGIN_PATH . 'admin/partials/documents-list.php';
    }

    public function handle_form_submission() {
        check_admin_referer( 'edocman_lite_document_action', 'edocman_lite_document_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied', 'edocman-lite' ) );
        }

        $document_id       = isset( $_POST['document_id'] )       ? intval( $_POST['document_id'] )                                    : 0;
        $title             = isset( $_POST['title'] )             ? sanitize_text_field( wp_unslash( $_POST['title'] ) )               : '';
        $short_description = isset( $_POST['short_description'] ) ? wp_kses_post( wp_unslash( $_POST['short_description'] ) )          : '';
        $description       = isset( $_POST['description'] )       ? wp_kses_post( wp_unslash( $_POST['description'] ) )                : '';
        $published         = isset( $_POST['published'] )         ? 1                                                                  : 0;
        $image             = isset( $_POST['image'] )             ? sanitize_text_field( wp_unslash( $_POST['image'] ) )               : '';
        $ordering          = isset( $_POST['ordering'] )          ? intval( $_POST['ordering'] )                                       : 0;
        $main_category_id  = isset( $_POST['main_category_id'] )  ? absint( $_POST['main_category_id'] )                              : 0;

        $additional_category_ids = isset( $_POST['additional_category_ids'] )
            ? array_map( 'absint', (array) $_POST['additional_category_ids'] )
            : array();

        $task = isset( $_POST['task'] ) ? sanitize_text_field( wp_unslash( $_POST['task'] ) ) : 'save';

        if ( empty( $title ) ) {
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&action=' . ( $document_id > 0 ? 'edit&id=' . $document_id : 'add' ) . '&message=error' ) );
            exit;
        }

        $alias = Edocman_Lite_Helper::create_alias( $title );

        // Default file info.
        $filename          = '';
        $original_filename = '';
        $file_size         = '';

        if ( $document_id > 0 ) {
            $database          = new Edocman_Lite_Database();
            $existing_document = $database->get_document( $document_id );
            $filename          = $existing_document->filename;
            $original_filename = $existing_document->original_filename;
            $file_size         = $existing_document->file_size;
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        if ( isset( $_FILES['document_file'] ) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $upload_result = $this->handle_file_upload( $_FILES['document_file'], $main_category_id );

            if ( $upload_result['success'] ) {
                $filename          = $upload_result['filename'];
                $original_filename = $upload_result['original_filename'];
                $file_size         = $upload_result['file_size'];
            } else {
                $message_code = isset( $upload_result['error'] ) ? $upload_result['error'] : 'file_error';
                wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&action=' . ( $document_id > 0 ? 'edit&id=' . $document_id : 'add' ) . '&message=' . urlencode( $message_code ) ) );
                exit;
            }
        }

        $data = array(
            'title'             => $title,
            'alias'             => $alias,
            'filename'          => $filename,
            'original_filename' => $original_filename,
            'short_description' => $short_description,
            'description'       => $description,
            'published'         => $published,
            'image'             => $image,
            'ordering'          => $ordering,
            'file_size'         => $file_size,
        );

        if ( $document_id > 0 ) {
            $data['id'] = $document_id;
        }

        $database = new Edocman_Lite_Database();
        $result   = $database->save_document( $data );

        if ( $result ) {
            $saved_id = $document_id > 0 ? $document_id : $result;
            $database->update_document_categories( $saved_id, $main_category_id, $additional_category_ids );

            $message = $document_id > 0 ? 'updated' : 'created';

            if ( $task === 'apply' ) {
                wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&action=edit&id=' . $saved_id . '&message=' . $message ) );
            } else {
                wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&message=' . $message ) );
            }
        } else {
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&action=' . ( $document_id > 0 ? 'edit&id=' . $document_id : 'add' ) . '&message=error' ) );
        }
        exit;
    }

    private function handle_file_upload( $file, $main_category_id = 0 ) {
        $documents_path = Edocman_Lite_Helper::get_config( 'documents_path' );

        // Validate file extension.
        $allowed_raw   = Edocman_Lite_Helper::get_config( 'allowed_file_types', 'pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar' );
        $allowed_types = ! empty( $allowed_raw ) ? array_map( 'trim', explode( ',', $allowed_raw ) ) : array();
        $ext           = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );

        if ( ! empty( $allowed_types ) && ! in_array( $ext, $allowed_types, true ) ) {
            return array( 'success' => false, 'error' => 'file_type_not_allowed' );
        }

        // Validate file size.
        $max_size_mb    = intval( Edocman_Lite_Helper::get_config( 'max_file_size', 10 ) );
        $max_size_bytes = $max_size_mb * 1024 * 1024;

        if ( $file['size'] > $max_size_bytes ) {
            return array( 'success' => false, 'error' => 'file_too_large' );
        }

        // Determine upload sub-directory, respecting hierarchical folders.
        $hierarchical_folders = Edocman_Lite_Helper::get_config( 'hierarchical_folders', '0' );
        $relative_dir         = 'documents';

        if ( $hierarchical_folders === '1' && $main_category_id > 0 ) {
            $database = new Edocman_Lite_Database();
            $category = $database->get_category( intval( $main_category_id ) );
            if ( $category && ! empty( $category->path ) ) {
                $relative_dir = trim( $category->path, '/' );
            }
        }

        $upload_dir = rtrim( $documents_path, '/' ) . '/' . $relative_dir . '/';

        if ( ! file_exists( $upload_dir ) ) {
            wp_mkdir_p( $upload_dir );
        }

        $original_filename = basename( $file['name'] );
        $safe_filename     = Edocman_Lite_Helper::sanitize_filename( $original_filename );
        $file_size         = $file['size'];

        if ( ! function_exists( 'wp_handle_upload' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        $target_dir  = untrailingslashit( $upload_dir );
        $target_name = $safe_filename;
        $dir_filter  = static function( $uploads ) use ( $target_dir ) {
            $uploads['path']   = $target_dir;
            $uploads['url']    = '';
            $uploads['subdir'] = '';
            $uploads['error']  = false;
            return $uploads;
        };

        add_filter( 'upload_dir', $dir_filter );

        $upload_result = wp_handle_upload(
            $file,
            array(
                'test_form'                => false,
                'unique_filename_callback' => static function( $dir, $name, $ext ) use ( $target_name ) {
                    return $target_name;
                },
            )
        );

        remove_filter( 'upload_dir', $dir_filter );

        if ( isset( $upload_result['error'] ) || ! isset( $upload_result['file'] ) ) {
            return array( 'success' => false, 'error' => 'upload_failed' );
        }

        $stored_filename = $relative_dir . '/' . $safe_filename;

        return array(
            'success'           => true,
            'filename'          => $stored_filename,
            'original_filename' => $original_filename,
            'file_size'         => Edocman_Lite_Helper::format_file_size( $file_size ),
        );
    }

    /**
     * Handle bulk actions.
     */
    private function handle_bulk_actions() {
        if ( ! isset( $_POST['action'] ) && ! isset( $_POST['action2'] ) ) {
            return;
        }

        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'bulk-documents' ) ) {
            wp_die( esc_html__( 'Security check failed', 'edocman-lite' ) );
        }

        $action_top    = isset( $_POST['action'] )  ? sanitize_key( wp_unslash( $_POST['action'] ) )  : '-1';
        $action_bottom = isset( $_POST['action2'] ) ? sanitize_key( wp_unslash( $_POST['action2'] ) ) : '-1';
        $action        = $action_top !== '-1' ? $action_top : $action_bottom;

        if ( $action === '-1' ) {
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied', 'edocman-lite' ) );
        }

        if ( ! isset( $_POST['document_ids'] ) || ! is_array( $_POST['document_ids'] ) ) {
            return;
        }

        $document_ids = array_filter( array_map( 'intval', $_POST['document_ids'] ) );

        if ( empty( $document_ids ) ) {
            return;
        }

        switch ( $action ) {
            case 'delete':
                $this->bulk_delete_documents( $document_ids );
                break;
            case 'publish':
                $this->bulk_update_status( $document_ids, 1 );
                break;
            case 'unpublish':
                $this->bulk_update_status( $document_ids, 0 );
                break;
        }
    }

    /**
     * Bulk delete documents.
     *
     * @param int[] $document_ids List of document IDs to delete.
     */
    private function bulk_delete_documents( $document_ids ) {
        $deleted_count  = 0;
        $database       = new Edocman_Lite_Database();
        $documents_path = Edocman_Lite_Helper::get_config( 'documents_path' );

        foreach ( $document_ids as $document_id ) {
            $document = $database->get_document( $document_id );

            if ( $document && ! empty( $document->filename ) ) {
                $file_path = rtrim( $documents_path, '/' ) . '/' . ltrim( $document->filename, '/' );
                if ( file_exists( $file_path ) ) {
                    wp_delete_file( $file_path );
                }
            }

            if ( $database->delete_document( $document_id ) !== false ) {
                $deleted_count++;
            }
        }

        if ( $deleted_count > 0 ) {
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&paged=1&message=bulk_deleted&count=' . $deleted_count ) );
        } else {
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&message=bulk_error' ) );
        }
        exit;
    }

    /**
     * Bulk update published status.
     *
     * @param int[] $document_ids List of document IDs.
     * @param int   $status       1 = published, 0 = unpublished.
     */
    private function bulk_update_status( $document_ids, $status ) {
        global $wpdb;

        $updated_count = 0;
        $table         = $wpdb->prefix . 'edocman_documents';

        foreach ( $document_ids as $document_id ) {
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $result = $wpdb->update(
                $table,
                array( 'published' => $status ),
                array( 'id'        => $document_id ),
                array( '%d' ),
                array( '%d' )
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

            if ( $result !== false ) {
                $updated_count++;
            }
        }

        if ( $updated_count > 0 ) {
            $message = $status ? 'bulk_published' : 'bulk_unpublished';
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&message=' . $message . '&count=' . $updated_count ) );
        } else {
            wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-documents&message=bulk_error' ) );
        }
        exit;
    }
}
