<?php
/**
 * Normalized Lead model. Every Source_Adapter produces one of these,
 * so storage / UI / export never need to know the original form plugin.
 *
 * @package Leadite
 */

namespace Leadite\Storage;

defined( 'ABSPATH' ) || exit;

class Lead {

	/** @var string Source slug: cf7, elementor, ... */
	public $source = '';

	/** @var string Form identifier within the source. */
	public $form_id = '';

	/** @var string Human-readable form name. */
	public $form_name = '';

	/**
	 * Fields list. Each item:
	 *  [ 'key'=>, 'label'=>, 'value'=>, 'type'=>, 'canonical'=> ]
	 *
	 * @var array
	 */
	public $fields = array();

	/** @var array Request metadata (ip, user_agent, referer, page_url, lang, utm...). */
	public $meta = array();

	/**
	 * Attachments list. Each item:
	 *  [ 'field_key'=>, 'name'=>, 'tmp_path'=>, 'copy'=> ]
	 *
	 * @var array
	 */
	public $attachments = array();

	/**
	 * Add a single field.
	 *
	 * @param string $key   Field machine key.
	 * @param mixed  $value Field value (array allowed -> joined).
	 * @param string $label Human label.
	 * @param string $type  Field type hint.
	 */
	public function add_field( $key, $value, $label = '', $type = 'text' ) {
		if ( is_array( $value ) ) {
			$value = implode( ', ', array_map( 'strval', $value ) );
		}

		$this->fields[] = array(
			'key'       => (string) $key,
			'label'     => $label ? (string) $label : (string) $key,
			'value'     => (string) $value,
			'type'      => (string) $type,
			'canonical' => '',
		);
	}

	/**
	 * Add an attachment field.
	 *
	 * @param string $field_key Field name/key.
	 * @param string $name      Original file name.
	 * @param string $tmp_path  Temporary path or URL to the file.
	 * @param bool   $copy      Whether repository should copy the file to uploads.
	 */
	public function add_attachment( $field_key, $name, $tmp_path, $copy = true ) {
		$this->attachments[] = array(
			'field_key' => (string) $field_key,
			'name'      => (string) $name,
			'tmp_path'  => (string) $tmp_path,
			'copy'      => (bool) $copy,
		);
	}

	/**
	 * Get a meta value with default.
	 *
	 * @param string $key     Meta key.
	 * @param mixed  $default Fallback.
	 * @return mixed
	 */
	public function meta( $key, $default = '' ) {
		return isset( $this->meta[ $key ] ) ? $this->meta[ $key ] : $default;
	}
}