<?php
/**
 * Template: Legal Documents (native, full parity)
 *
 * Mirrors the Cloud Documents view: a "Generate new document" card, a table of
 * existing documents (type, language, version, status, working shortcode,
 * last updated) and per-row actions — Edit (inline editor → save-document-content),
 * Publish/Draft toggle (toggle-document) and Assign to a WordPress page
 * (biscotti_get_pages + biscotti_assign_page). Document data comes from the
 * get-documents proxy ({ documents:[{id,type,language,version,isPublished,updatedAt}] }).
 *
 * Document type values are the Prisma DocumentType enum (UPPERCASE). The
 * generate options use input keys that legal-service.js::prismaTypeMap maps to
 * valid enum values, so generation never produces an unsaveable type. The
 * displayed shortcode is the universal [biscotti-document type="<lowercase>"]
 * registered in class-shortcodes.php.
 *
 * @var array $data get-documents response.
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Legal Documents', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

if ( null === $data ) :
	include __DIR__ . '/partials/loading-state.php';
	return;
endif;

$documents = ( isset( $data['documents'] ) && is_array( $data['documents'] ) ) ? $data['documents'] : array();

/**
 * Human-readable label for a stored DocumentType enum value.
 *
 * @param string $type UPPERCASE enum value.
 * @return string
 */
if ( ! function_exists( 'biscotti_doc_type_label' ) ) {
	function biscotti_doc_type_label( $type ) {
		$labels = array(
		'IMPRESSUM'                     => __( 'Legal Notice (Impressum)', 'biscotti-cmp' ),
		'PRIVACY_POLICY'                => __( 'Privacy Policy', 'biscotti-cmp' ),
		'COOKIE_POLICY'                 => __( 'Cookie Policy', 'biscotti-cmp' ),
		'AVV'                           => __( 'Data Processing Agreement (AVV)', 'biscotti-cmp' ),
		'DSA_INFO'                      => __( 'DSA Information', 'biscotti-cmp' ),
		'TERMS'                         => __( 'Terms & Conditions (AGB)', 'biscotti-cmp' ),
		'WIDERRUF'                      => __( 'Cancellation Policy (Widerruf)', 'biscotti-cmp' ),
		'SOCIAL_MEDIA_PRIVACY'          => __( 'Social Media Privacy', 'biscotti-cmp' ),
		'TOS'                           => __( 'Terms of Service', 'biscotti-cmp' ),
		'AGB_B2B'                       => __( 'Terms & Conditions (B2B)', 'biscotti-cmp' ),
		'SHIPPING'                      => __( 'Shipping Policy', 'biscotti-cmp' ),
		'RETURNS'                       => __( 'Return Policy', 'biscotti-cmp' ),
		'AUP'                           => __( 'Acceptable Use Policy', 'biscotti-cmp' ),
		'SLA'                           => __( 'Service Level Agreement', 'biscotti-cmp' ),
		'COMMUNITY_GUIDELINES'          => __( 'Community Guidelines', 'biscotti-cmp' ),
		'COPYRIGHT'                     => __( 'Copyright Notice', 'biscotti-cmp' ),
		'NEWSLETTER'                    => __( 'Newsletter Consent Notice', 'biscotti-cmp' ),
		'PATIENT_CONSENT'               => __( 'Patient Consent', 'biscotti-cmp' ),
		'MEDICAL_DISCLAIMER'            => __( 'Medical Disclaimer', 'biscotti-cmp' ),
		'RISK_DISCLOSURE'               => __( 'Risk Disclosure', 'biscotti-cmp' ),
		'FINANCIAL_DISCLAIMER'          => __( 'Financial Disclaimer', 'biscotti-cmp' ),
		'KYC_POLICY'                    => __( 'KYC / AML Policy', 'biscotti-cmp' ),
		'COURSE_TERMS'                  => __( 'Course Terms', 'biscotti-cmp' ),
		'CERTIFICATION_POLICY'          => __( 'Certification Policy', 'biscotti-cmp' ),
		'BOOKING_TERMS'                 => __( 'Booking Terms', 'biscotti-cmp' ),
		'CANCELLATION_POLICY'           => __( 'Cancellation Policy', 'biscotti-cmp' ),
		'CONFIDENTIALITY'               => __( 'Confidentiality Agreement', 'biscotti-cmp' ),
		'ENGAGEMENT_LETTER'             => __( 'Engagement Letter', 'biscotti-cmp' ),
		'MEMBER_TERMS'                  => __( 'Membership Terms', 'biscotti-cmp' ),
		'DONATION_POLICY'               => __( 'Donation Policy', 'biscotti-cmp' ),
		'HOUSE_RULES'                   => __( 'House Rules', 'biscotti-cmp' ),
		'MARKETPLACE_USER_TERMS'        => __( 'Marketplace User Terms', 'biscotti-cmp' ),
		'MARKETPLACE_SELLER_CONDITIONS' => __( 'Marketplace Seller Conditions', 'biscotti-cmp' ),
	);
	return isset( $labels[ $type ] ) ? $labels[ $type ] : $type;
	}
}

// Curated generate options whose values legal-service.js::prismaTypeMap maps to a valid enum.
$generate_types = array(
	'PRIVACY_POLICY' => biscotti_doc_type_label( 'PRIVACY_POLICY' ),
	'IMPRESSUM'      => biscotti_doc_type_label( 'IMPRESSUM' ),
	'COOKIE_POLICY'  => biscotti_doc_type_label( 'COOKIE_POLICY' ),
	'TERMS'          => biscotti_doc_type_label( 'TERMS' ),
	'WIDERRUF'       => biscotti_doc_type_label( 'WIDERRUF' ),
	'AVV'            => biscotti_doc_type_label( 'AVV' ),
	'DSA_INFO'       => biscotti_doc_type_label( 'DSA_INFO' ),
	'SHIPPING'       => biscotti_doc_type_label( 'SHIPPING' ),
	'RETURNS'        => biscotti_doc_type_label( 'RETURNS' ),
	'TOS'            => biscotti_doc_type_label( 'TOS' ),
);
?>

<div class="biscotti-page biscotti-page-documents">

	<!-- Generate New Document -->
	<div class="biscotti-card">
		<h3>➕ <?php esc_html_e( 'Generate New Document', 'biscotti-cmp' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Generate a legally compliant document. Complete your company data in the Legal Wizard first.', 'biscotti-cmp' ); ?></p>
		<div class="biscotti-doc-gen-row">
			<select id="biscotti-doc-gen-type" class="biscotti-doc-select">
				<option value="">— <?php esc_html_e( 'Select Document Type', 'biscotti-cmp' ); ?> —</option>
				<?php foreach ( $generate_types as $value => $label ) : ?>
					<option value="<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></option>
				<?php endforeach; ?>
			</select>
			<button type="button" id="biscotti-doc-generate" class="button button-primary">⚡ <?php esc_html_e( 'Generate', 'biscotti-cmp' ); ?></button>
			<span id="biscotti-doc-gen-status" class="biscotti-save-status" role="status"></span>
		</div>
	</div>

	<!-- Documents Table -->
	<div class="biscotti-card">
		<h3>📄 <?php esc_html_e( 'Your Documents', 'biscotti-cmp' ); ?></h3>
		<?php if ( empty( $documents ) ) : ?>
			<div class="biscotti-empty-state">
				<span class="dashicons dashicons-media-document biscotti-empty-icon"></span>
				<h3><?php esc_html_e( 'No documents yet', 'biscotti-cmp' ); ?></h3>
				<p><?php esc_html_e( 'Generate your first document using the selector above.', 'biscotti-cmp' ); ?></p>
			</div>
		<?php else : ?>
			<table class="widefat biscotti-data-table biscotti-documents-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Type', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Language', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Version', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Status', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Shortcode', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Last Updated', 'biscotti-cmp' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Actions', 'biscotti-cmp' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php
					foreach ( $documents as $document ) :
						$doc_id       = isset( $document['id'] ) ? (string) $document['id'] : '';
						$doc_type     = isset( $document['type'] ) ? sanitize_text_field( (string) $document['type'] ) : '';
						$doc_language = isset( $document['language'] ) ? sanitize_text_field( (string) $document['language'] ) : '';
						$doc_version  = isset( $document['version'] ) ? absint( $document['version'] ) : 0;
						$is_published = ! empty( $document['isPublished'] );
						$updated_at   = isset( $document['updatedAt'] ) ? sanitize_text_field( (string) $document['updatedAt'] ) : '';

						$formatted_date = '';
						if ( ! empty( $updated_at ) ) {
							$ts             = strtotime( $updated_at );
							$formatted_date = $ts ? date_i18n( get_option( 'date_format' ), $ts ) : $updated_at;
						}

						$shortcode = sprintf( '[biscotti-document type="%s"]', strtolower( $doc_type ) );
						?>
						<tr data-document-id="<?php echo esc_attr( $doc_id ); ?>" data-document-type="<?php echo esc_attr( $doc_type ); ?>">
							<td><strong><?php echo esc_html( biscotti_doc_type_label( $doc_type ) ); ?></strong></td>
							<td><?php echo esc_html( strtoupper( $doc_language ) ); ?></td>
							<td>v<?php echo esc_html( $doc_version ); ?></td>
							<td>
								<?php if ( $is_published ) : ?>
									<span class="biscotti-pill biscotti-pill-green"><?php esc_html_e( 'Published', 'biscotti-cmp' ); ?></span>
								<?php else : ?>
									<span class="biscotti-pill biscotti-pill-amber"><?php esc_html_e( 'Draft', 'biscotti-cmp' ); ?></span>
								<?php endif; ?>
							</td>
							<td>
								<code class="biscotti-doc-sc"><?php echo esc_html( $shortcode ); ?></code>
								<button type="button" class="button-link biscotti-doc-copy" data-shortcode="<?php echo esc_attr( $shortcode ); ?>" title="<?php esc_attr_e( 'Copy', 'biscotti-cmp' ); ?>" aria-label="<?php esc_attr_e( 'Copy shortcode', 'biscotti-cmp' ); ?>">📋</button>
							</td>
							<td><?php echo esc_html( $formatted_date ); ?></td>
							<td class="biscotti-table-actions">
								<button type="button" class="button button-small biscotti-doc-edit" data-document-id="<?php echo esc_attr( $doc_id ); ?>" data-document-name="<?php echo esc_attr( biscotti_doc_type_label( $doc_type ) ); ?>"><?php esc_html_e( 'Edit', 'biscotti-cmp' ); ?></button>
								<button type="button" class="button button-small biscotti-doc-toggle<?php echo $is_published ? ' biscotti-doc-is-published' : ''; ?>" data-document-id="<?php echo esc_attr( $doc_id ); ?>"><?php echo $is_published ? esc_html__( 'Unpublish', 'biscotti-cmp' ) : esc_html__( 'Publish', 'biscotti-cmp' ); ?></button>
								<button type="button" class="button button-small biscotti-doc-assign" data-document-type="<?php echo esc_attr( $doc_type ); ?>"><?php esc_html_e( 'Assign to Page', 'biscotti-cmp' ); ?></button>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</div>

</div>

<!-- Edit Modal -->
<div id="biscotti-doc-editor" class="biscotti-doc-overlay" role="dialog" aria-modal="true" aria-labelledby="biscotti-doc-editor-title">
	<div class="biscotti-doc-modal">
		<div class="biscotti-doc-modal-header">
			<h3 id="biscotti-doc-editor-title">📝 <?php esc_html_e( 'Edit Document', 'biscotti-cmp' ); ?></h3>
			<button type="button" class="biscotti-doc-modal-close" id="biscotti-doc-editor-close" aria-label="<?php esc_attr_e( 'Close', 'biscotti-cmp' ); ?>">&times;</button>
		</div>
		<div id="biscotti-doc-editor-content" class="biscotti-doc-editor-content" contenteditable="true"></div>
		<div class="biscotti-doc-modal-footer">
			<button type="button" class="button button-primary" id="biscotti-doc-editor-save">💾 <?php esc_html_e( 'Save', 'biscotti-cmp' ); ?></button>
			<button type="button" class="button" id="biscotti-doc-editor-cancel"><?php esc_html_e( 'Cancel', 'biscotti-cmp' ); ?></button>
			<span id="biscotti-doc-editor-status" class="biscotti-save-status" role="status"></span>
		</div>
	</div>
</div>

<!-- Assign-to-Page Modal -->
<div id="biscotti-doc-assigner" class="biscotti-doc-overlay" role="dialog" aria-modal="true" aria-labelledby="biscotti-doc-assigner-title">
	<div class="biscotti-doc-modal biscotti-doc-modal-sm">
		<div class="biscotti-doc-modal-header">
			<h3 id="biscotti-doc-assigner-title"><?php esc_html_e( 'Assign to a Page', 'biscotti-cmp' ); ?></h3>
			<button type="button" class="biscotti-doc-modal-close" id="biscotti-doc-assigner-close" aria-label="<?php esc_attr_e( 'Close', 'biscotti-cmp' ); ?>">&times;</button>
		</div>
		<div class="biscotti-doc-modal-body">
			<p class="description"><?php esc_html_e( 'The document shortcode will be appended to the selected page. Existing content is preserved.', 'biscotti-cmp' ); ?></p>
			<select id="biscotti-doc-assign-page" class="biscotti-doc-select" style="width:100%;">
				<option value=""><?php esc_html_e( 'Loading pages…', 'biscotti-cmp' ); ?></option>
			</select>
		</div>
		<div class="biscotti-doc-modal-footer">
			<button type="button" class="button button-primary" id="biscotti-doc-assign-confirm"><?php esc_html_e( 'Assign', 'biscotti-cmp' ); ?></button>
			<button type="button" class="button" id="biscotti-doc-assigner-cancel"><?php esc_html_e( 'Cancel', 'biscotti-cmp' ); ?></button>
			<span id="biscotti-doc-assign-status" class="biscotti-save-status" role="status"></span>
		</div>
	</div>
</div>
