<?php

/**
 * Developer: Iaax Page (twitter.com/iaaxpage)
 * Date: 9/4/15, 11:18 PM
 * Generator: PhpStorm
 */

namespace OctopusSignatureClient\WordPress;
// TODO: Add dependencies USE statemens here


class ResourcesManager
{

    public function __construct()
    {

    }

    public static function saveFileToUploads($fileName, $fileContents, $directory = null)
    {
        // Get WordPress Upload Directory
        $upload_dir = wp_upload_dir(); // Set upload folder

        if ( $directory ){
            $subDirectory = (empty($directory) ? '' : trailingslashit($directory));
            // Base dir is the path to the uploads directory
            $file = "{$upload_dir['basedir']}/{$subDirectory}{$fileName}";
            $fileURL = "{$upload_dir['baseurl']}/{$subDirectory}{$fileName}";
            // Make the directories recusr
            wp_mkdir_p( "{$upload_dir['basedir']}/{$subDirectory}" );

        } else {
            if (wp_mkdir_p($upload_dir['path'])) {
                $file = "{$upload_dir['path']}/{$fileName}";
                $fileURL = "{$upload_dir['url']}/{$fileName}";
            } else {
                $file = "{$upload_dir['basedir']}/{$fileName}";
                $fileURL = "{$upload_dir['baseurl']}/{$fileName}";
            }
        }

        file_put_contents( $file, $fileContents );

        return array( 'filePath' => $file, 'fileURL' => $fileURL );
    }

    public static function addFileToPost($postID, $filePath)
    {
        $file = file_get_contents( $filePath );
        $wp_filetype = wp_check_filetype( $filePath, null );

        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name( $filePath ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        $attachmentID = wp_insert_attachment( $attachment, $file, $postID );
        // Require Image Class
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        // Generate Attachment Metadata
        $attach_data = wp_generate_attachment_metadata( $attachmentID, $file );
        wp_update_attachment_metadata( $attachmentID, $attach_data );

        return $attachmentID;
    }

    public static function setAsPostThumbnail($postID, $attachmentID)
    {

    }

}