<?php

/**
 * Setup REST API
 */
function wpdav_setup_wp_rest(){

        
    /**
     * Add authentication to REST API
     */
    add_filter( 'rest_pre_dispatch', function( $result, WP_REST_Server $server, WP_REST_Request $request ) {

        if( $result instanceof WP_Error )
            return $result;

        $route = $request->get_route();
        $parts = explode('/', $route);

        $trimmed_prefix = trim(WPDAV_PLUGIN_REST_PREFIX, '/');

        if( in_array($trimmed_prefix, $parts) && !wpdav_is_user_authenticated() )
            return new WP_Error( 'rest_not_authenticated', 'You are not authenticated', array('status' => 401) );

        return $result;

    }, 10, 3 );

    /**
     * Register REST routes
     */
    add_action( 'rest_api_init', function () {

        register_rest_route( WPDAV_PLUGIN_REST_PREFIX , '/mysqldump', array(
            'methods' => 'GET',
            'callback' => 'wpdav_rest_database_dump',
        ) );


        register_rest_route( WPDAV_PLUGIN_REST_PREFIX , '/download/backup', array(
            'methods' => 'GET',
            'callback' => 'download_archive_backup',
        ) );
        
        register_rest_route( WPDAV_PLUGIN_REST_PREFIX , '/info', array(
            'methods' => 'GET',
            'callback' => 'wpdav_rest_plugin_info',
        ) );

    } );


}

/**
 * Route: /mysqldump
 * REST route to get database dump
 */
function wpdav_rest_database_dump(){

    $dump = wpdav_get_database_dump();

    // Set download headers 
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="database.sql"');
    header('Content-Length: ' . strlen($dump));
    // Echo, do not return WP_REST_Response, because of raw output
    echo $dump;
    exit;

}

/**
 * Route: /download/archive_www
 * REST route to get database dump
 */
function download_archive_backup(){

    $zip = new \PhpZip\ZipFile();
    $zip->addDirRecursive(ABSPATH, "/www/", \PhpZip\Constants\ZipCompressionMethod::STORED);
    $zip->addFromString("database.sql", wpdav_get_database_dump()); 
    $zip->outputAsAttachment("www.zip");

    exit;

}
/**
 * Retrives name of current theme
 */
function wpdav_rest_plugin_info(WP_REST_Request $request) {
   
    return new WP_REST_Response( array ('theme' => get_option( 'stylesheet' )) );

}
	
