<?php
/**
 * Contacter
 * Voice feedback form for your website for saving and transcribing user voice messages to text.
 * Exclusively on https://1.envato.market/contacter
 *
 * @encoding        UTF-8
 * @version         1.7.8
 * @copyright       (C) 2018 - 2023 Merkulove ( https://merkulov.design/ ). All rights reserved.
 * @license         Envato License https://1.envato.market/KYbje
 * @contributors    Dmitry Merkulov (dmitry@merkulov.design)
 * @support         help@merkulov.design
 **/

namespace Merkulove\Contacter;

use Merkulove\Contacter\Unity\Plugin;

/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

final class Attachment {

	/**
	 * The one true Attachment.
	 *
	 * @var Attachment
	 * @since 1.0.0
	 **/
	private static $instance;

	/**
	 * Create media library record and attach it to the post
	 *
	 * @param $upload_dir
	 * @param $record_name
	 * @param $cForm_id
	 *
	 * @return void
	 */
    public function create_attachment( $record_name, $cForm_id ) {

        /** Get uploads directory info */
	    $upload_dir = wp_get_upload_dir();
	    if ( ! is_array( $upload_dir ) ) { return; }

		/** Combine file name, url and path */
	    $file_name = Caster::get_instance()->build_file_name( $cForm_id, 0, $record_name );
        $audio_file = $upload_dir[ 'basedir' ] . '/' . Plugin::get_slug() . '/' . $file_name;
        $audio_url = $upload_dir[ 'baseurl' ] . '/' . Plugin::get_slug() . '/' . $file_name;

        /** Store file meta to the post meta */
        $audio_meta = wp_read_audio_metadata( $audio_file );
        if ( ! is_array( $audio_meta ) ) { return; }

        /** Prepare post variables */
	    $cForm = get_post( $cForm_id );

        /** Prepare attachments options */
        $attachment = array(
            'guid'           => $audio_url,
            'post_mime_type' => $audio_meta['mime_type'],
            'post_title'     => esc_html__( 'Record', 'contacter' ) . ': ' . $cForm->post_title,
            'post_author'    => 1,
            'post_status'    => 'inherit'
        );

        /** Create a new attachment record */
        $attachment_id = wp_insert_attachment( $attachment, $audio_file );

		/** Mark attachment as plugin attachment for future removing */
		if ( $attachment_id ) {
			add_post_meta( $attachment_id, 'contacter-attachment', 'wav' );
		}

    }

	/**
	 * Main Attachment Instance.
	 *
	 * Insures that only one instance of Attachment exists in memory at any one time.
	 *
	 * @static
	 * @return Attachment
	 * @since 2.0.0
	 **/
	public static function get_instance() {

        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {

			self::$instance = new self;

		}

		return self::$instance;

	}

}
