<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Edocman_Lite_Admin_Categories {

    private $per_page = 20;

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

    public function display_categories_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_category_form();
                break;
            case 'edit':
                $this->display_edit_category_form();
                break;
            default:
                $this->display_categories_list();
                break;
        }
    }

    private function display_add_category_form() {
        $parent_categories = $this->get_available_parent_categories( 0 );
        include EDOCMAN_LITE_PLUGIN_PATH . 'admin/partials/categories-form.php';
    }

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

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

        $database = new Edocman_Lite_Database();
        $category = $database->get_category( $category_id );

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

        $parent_categories = $this->get_available_parent_categories( $category_id );
        include EDOCMAN_LITE_PLUGIN_PATH . 'admin/partials/categories-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'] ) );
        $messages = array(
            'created' => __( 'Category created successfully.', 'edocman-lite' ),
            'updated' => __( 'Category updated successfully.', 'edocman-lite' ),
            'deleted' => __( 'Category deleted successfully.', 'edocman-lite' ),
            'error'   => __( 'Error saving category.', 'edocman-lite' ),
        );

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

    private function display_categories_list() {
        // 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'] ) ) : '';

        $database        = new Edocman_Lite_Database();
        $categories      = $database->get_all_categories( false );
        $categories_tree = $this->build_category_tree( $categories );

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

    private function build_category_tree( $categories, $parent_id = 0, $level = 0 ) {
        $tree = array();

        foreach ( $categories as $category ) {
            if ( (int) $category->parent_id === (int) $parent_id ) {
                $category->level = $level;
                $tree[]          = $category;
                $children        = $this->build_category_tree( $categories, $category->id, $level + 1 );
                $tree            = array_merge( $tree, $children );
            }
        }

        return $tree;
    }

    private function get_available_parent_categories( $exclude_id = 0 ) {
        $database       = new Edocman_Lite_Database();
        $all_categories = $database->get_all_categories( false );
        $available      = array();
        $exclude_ids    = array();

        if ( $exclude_id > 0 ) {
            $exclude_ids   = $this->get_descendant_ids( $exclude_id, $all_categories );
            $exclude_ids[] = $exclude_id;
        }

        foreach ( $all_categories as $category ) {
            if ( ! in_array( $category->id, $exclude_ids, true ) ) {
                $available[] = $category;
            }
        }

        return $this->build_dropdown_tree( $available );
    }

    private function get_descendant_ids( $parent_id, $all_categories ) {
        $ids = array();
        foreach ( $all_categories as $category ) {
            if ( (int) $category->parent_id === (int) $parent_id ) {
                $ids[] = $category->id;
                $ids   = array_merge( $ids, $this->get_descendant_ids( $category->id, $all_categories ) );
            }
        }
        return $ids;
    }

    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 handle_form_submission() {
        check_admin_referer( 'edocman_lite_category_action', 'edocman_lite_category_nonce' );

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

        $category_id = isset( $_POST['category_id'] ) ? absint( $_POST['category_id'] )                                  : 0;
        $title       = isset( $_POST['title'] )       ? sanitize_text_field( wp_unslash( $_POST['title'] ) )             : '';
        $parent_id   = isset( $_POST['parent_id'] )   ? intval( $_POST['parent_id'] )                                    : 0;
        $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;
        $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-categories&action=' . ( $category_id > 0 ? 'edit&id=' . $category_id : 'add' ) . '&message=error' ) );
            exit;
        }

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

        // Calculate path based on parent hierarchy.
        $hierarchical_folders = Edocman_Lite_Helper::get_config( 'hierarchical_folders', '0' );
        $folder_name          = isset( $_POST['folder_name'] ) ? sanitize_text_field( wp_unslash( $_POST['folder_name'] ) ) : '';

        if ( $hierarchical_folders === '1' && ! empty( trim( $folder_name ) ) ) {
            // Validate folder name: only alphanumerics, hyphens and underscores.
            if ( ! preg_match( '/^[a-zA-Z0-9_-]+$/', $folder_name ) ) {
                wp_safe_redirect( admin_url( 'admin.php?page=edocman-lite-categories&action=' . ( $category_id > 0 ? 'edit&id=' . $category_id : 'add' ) . '&message=error' ) );
                exit;
            }
        } else {
            $folder_name = $alias;
        }

        $path = $folder_name;
        if ( $parent_id > 0 ) {
            $db     = new Edocman_Lite_Database();
            $parent = $db->get_category( $parent_id );
            if ( $parent && ! empty( $parent->path ) ) {
                $path = trim( $parent->path, '/' ) . '/' . $folder_name;
            } elseif ( $parent ) {
                $parent_alias = ! empty( $parent->alias ) ? $parent->alias : Edocman_Lite_Helper::create_alias( $parent->title );
                $path         = $parent_alias . '/' . $folder_name;
            }
        }

        $data = array(
            'title'       => $title,
            'alias'       => $alias,
            'path'        => $path,
            'parent_id'   => $parent_id,
            'description' => $description,
            'published'   => $published,
            'image'       => $image,
            'ordering'    => $ordering,
        );

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

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

        if ( $result ) {
            $message  = $category_id > 0 ? 'updated' : 'created';
            $saved_id = $category_id > 0 ? $category_id : $result;

            // ✅ Create folder only when hierarchical folders is enabled AND
            // the resolved path is confirmed to be inside the uploads directory.
            if ( $hierarchical_folders === '1' && ! empty( $path ) ) {
                $documents_path  = Edocman_Lite_Helper::get_config( 'documents_path' );
                $upload_dir      = wp_upload_dir();
                $uploads_basedir = wp_normalize_path( $upload_dir['basedir'] );
                $category_folder = wp_normalize_path( rtrim( $documents_path, '/' ) . '/' . trim( $path, '/' ) );

                // Only create the folder if it resolves inside the uploads directory.
                if ( strpos( $category_folder, $uploads_basedir ) === 0 && ! file_exists( $category_folder ) ) {
                    wp_mkdir_p( $category_folder );
                }
            }

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