<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class WP_OJS_SSO_File_Upload {

    private static $instance = null;

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_post_ojs_download_document', [ $this, 'admin_download' ] );
    }

    public static function get_upload_dir( $user_id ) {
        $upload_dir = wp_upload_dir();
        return $upload_dir['basedir'] . '/ojs-sso-bridge/' . (int) $user_id;
    }

    /**
     * Student certificate: saved as Media attachment under file-utenti/.../certificato
     */
    public static function handle_upload( $user_id, $file_key = 'ojs_student_document' ) {
        if ( ! class_exists( 'WP_OJS_SSO_Subscription_Media' ) ) {
            return new WP_Error( 'missing', __( 'Storage handler is not available.', 'wp-ojs-sso-bridge' ) );
        }
        return WP_OJS_SSO_Subscription_Media::handle_upload( (int) $user_id, $file_key, WP_OJS_SSO_Subscription_Media::KIND_CERTIFICATO );
    }

    public function admin_download() {
        if ( ! current_user_can( 'edit_users' ) ) {
            wp_die( esc_html__( 'Unauthorized', 'wp-ojs-sso-bridge' ), 403 );
        }

        $user_id = (int) ( $_GET['user_id'] ?? 0 );
        if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'ojs_download_doc_' . $user_id ) ) {
            wp_die( esc_html__( 'Invalid nonce', 'wp-ojs-sso-bridge' ), 403 );
        }

        $val = get_user_meta( $user_id, 'ojs_student_document', true );
        $path = '';

        if ( $val && is_numeric( $val ) && (int) $val > 0 ) {
            $p = get_attached_file( (int) $val );
            if ( $p && is_readable( $p ) ) {
                $path = $p;
            }
        } elseif ( $val && is_string( $val ) && is_file( $val ) && is_readable( $val ) ) {
            $path = $val;
        }

        if ( ! $path ) {
            wp_die( esc_html__( 'File not found', 'wp-ojs-sso-bridge' ), 404 );
        }

        $finfo = finfo_open( FILEINFO_MIME_TYPE );
        $mime  = finfo_file( $finfo, $path );
        finfo_close( $finfo );

        header( 'Content-Type: ' . $mime );
        header( 'Content-Disposition: attachment; filename="' . rawurlencode( basename( $path ) ) . '"' );
        header( 'Content-Length: ' . filesize( $path ) );
        readfile( $path );
        exit;
    }

    public static function get_admin_download_url( $user_id ) {
        return wp_nonce_url(
            admin_url( 'admin-post.php?action=ojs_download_document&user_id=' . (int) $user_id ),
            'ojs_download_doc_' . (int) $user_id
        );
    }

    public static function delete_user_files( $user_id ) {
        if ( class_exists( 'WP_OJS_SSO_Subscription_Media' ) ) {
            WP_OJS_SSO_Subscription_Media::on_delete_user( $user_id );
            return;
        }
        $dir = self::get_upload_dir( $user_id );
        if ( is_dir( $dir ) ) {
            $files = glob( $dir . '/*' );
            if ( $files ) {
                array_map( 'unlink', $files );
            }
            @rmdir( $dir );
        }
    }
}
