<?php
/**
 * Payout Drawer — Details Card
 *
 * Collapsible card containing secondary metadata (batch, generated by, dates,
 * account, invoice link). Fires the classic `affwp_edit_payout_*` hooks so
 * integrators continue to work without a migration — context change for `_end`
 * is documented in the changelog (block context, not table rows).
 *
 * Expects the parent `x-data="{ drawer: $store.payoutDrawer }"` scope
 * (see drawer.php content_callback).
 *
 * @package     AffiliateWP
 * @subpackage  Admin/Payouts
 * @since       2.33.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

?>

<template x-if="drawer.payout">
	<!--
		$persist keeps the Details open/closed state across drawer opens,
		payout-to-payout keyboard navigation, and page reloads (localStorage).
		Key is namespaced so sibling drawers don't clobber each other.
	-->
	<div x-data="{ expanded: $persist(true).as('affwp-payout-drawer-details-open') }" class="affwp-card rounded-lg border border-gray-200 bg-white overflow-hidden">

		<!--
			Tinted eyebrow strip used as the collapse toggle button.
			Visual treatment matches the other drawer cards (Supersession,
			Next Steps, Summary) — same bg-gray-50 strip + uppercase
			eyebrow typography — while preserving the button affordance
			that drives the expand/collapse. Hover lifts the strip a
			shade so the interactivity is telegraphed (other cards'
			eyebrow strips are non-interactive and stay flat).

			chevron-right collapsed, -rotate-90 (quarter turn ccw → up)
			when expanded. Matches the convention used by
			affwp_render_configure_button() in Settings.
		-->
		<!--
			focus-visible uses an inset ring so the focus indicator stays
			INSIDE the button's bounds. Without `focus:outline-none` the
			default browser focus outline escapes the card's rounded
			corners and looks like a bug. Same recipe as the Switch
			payout method footer trigger.

			Note the eyebrow strip does NOT carry a `border-b`. That
			separator now lives on the body's inner wrapper as a
			`border-t`, so it animates in and out with the collapse
			(see the body wrapper below). Earlier we tried conditioning
			`border-b` on `expanded` via `:class` — but the class flips
			synchronously while x-collapse animates the body height
			asynchronously, so for one frame the border sat doubled
			against the card's outer bottom border (open) or vanished
			while the body was still animating closed.
		-->
		<button type="button"
			@click="expanded = ! expanded"
			:aria-expanded="expanded.toString()"
			class="w-full cursor-pointer flex items-center justify-between gap-3 px-4 py-2 bg-gray-50 hover:bg-gray-100 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-affwp-brand-500 transition-colors">
			<span class="text-[11px] font-semibold uppercase tracking-wide text-gray-600"><?php esc_html_e( 'Details', 'affiliate-wp' ); ?></span>
			<span class="text-gray-400 transition-transform duration-200"
				:class="{ '-rotate-90': expanded }"
				aria-hidden="true">
				<?php \AffiliateWP\Utils\Icons::render( 'chevron-right', '', [ 'class' => 'h-4 w-4' ] ); ?>
			</span>
		</button>

		<!--
			x-collapse animates the element's height 0 → auto. Any padding on the
			collapsing element itself snaps in at t=0, which is the chunky first
			frame. Keep the collapsing element padding-free; move padding/border
			to the inner wrapper so the content eases in along with the height.
		-->
		<div x-show="expanded" x-collapse>
			<!--
				`border-t` lives on this inner wrapper so it grows
				and shrinks WITH the body height animation. Earlier
				attempts (border-b on the eyebrow, conditional via
				:class) had a frame-0 timing flash because the class
				flipped synchronously while x-collapse animated
				asynchronously. With the border owned by the body,
				the separator animates in/out cleanly with the rest
				of the content. Collapsed state has no separator at
				all (the card's outer bottom border does the work).
			-->
			<div class="flex flex-col gap-3 p-4 text-sm border-t border-gray-200">

			<template x-if="drawer.payout.batch_id && drawer.payout.batch_id > 0">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Batch', 'affiliate-wp' ); ?></span>
					<!--
						Click swaps drawers (payout closes, batch opens) when
						the batch drawer is registered on this page. On pages
						without the batch drawer, the link navigates normally
						to the batches tab with ?batch_id=X — the batch
						drawer auto-opens there from the URL param. Either
						path lands the admin on the same state; the drawer
						swap is just the smoother variant.
					-->
					<a :href="drawer.payout.batch_url"
						@click="if ( drawer.openBatch( drawer.payout.batch_id ) ) $event.preventDefault()"
						class="text-affwp-link hover:text-affwp-link-hover"
						x-text="'#' + drawer.payout.batch_id"></a>
				</div>
			</template>

			<template x-if="! drawer.payout.batch_id || drawer.payout.batch_id == 0">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Batch', 'affiliate-wp' ); ?></span>
					<span class="text-gray-500 italic text-xs"><?php echo esc_html_x( '(not batched)', 'payout batch', 'affiliate-wp' ); ?></span>
				</div>
			</template>

			<!--
				Retry-chain lineage. When this payout replaced an earlier attempt
				(hidden from the list because chains collapse to their current
				tail), surface the link back here as provenance — alongside Batch,
				where the other relational facts live. Clicking swaps the drawer
				to the previous attempt, with returnTo so the back-breadcrumb works.
			-->
			<template x-if="drawer.payout.previous_payout_id && drawer.payout.previous_payout_id > 0">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Previous attempt', 'affiliate-wp' ); ?></span>
					<a href="#"
						@click.prevent="drawer.openFor( drawer.payout.previous_payout_id, { returnTo: { type: 'payout', id: drawer.payoutId } } )"
						class="text-affwp-link hover:text-affwp-link-hover"
						x-text="'#' + drawer.payout.previous_payout_id"></a>
				</div>
			</template>

			<div class="flex items-baseline justify-between gap-3">
				<span class="text-gray-500"><?php esc_html_e( 'Affiliate', 'affiliate-wp' ); ?></span>
				<a :href="drawer.payout.affiliate_url"
					class="text-affwp-link hover:text-affwp-link-hover"
					x-text="drawer.payout.affiliate_name + ' (ID: ' + drawer.payout.affiliate_id + ')'"></a>
			</div>

			<template x-if="drawer.payout.payout_email || drawer.payout.affiliate_email">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Payout email', 'affiliate-wp' ); ?></span>
					<a :href="'mailto:' + (drawer.payout.payout_email || drawer.payout.affiliate_email)"
						class="text-affwp-link hover:text-affwp-link-hover truncate max-w-60"
						x-text="drawer.payout.payout_email || drawer.payout.affiliate_email"></a>
				</div>
			</template>

			<!--
				Generated-by row hidden when owner_label is empty (system-
				created payout, no human attribution). Matches the batch
				drawer's "drop the by-X suffix when created_by=0" rule.
			-->
			<template x-if="drawer.payout.owner_label">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Generated by', 'affiliate-wp' ); ?></span>
					<span class="text-gray-900" x-text="drawer.payout.owner_label"></span>
				</div>
			</template>

			<div class="flex items-baseline justify-between gap-3">
				<span class="text-gray-500"><?php esc_html_e( 'Payout method', 'affiliate-wp' ); ?></span>
				<!--
					Uses payout_method_label (properly-cased "PayPal" etc.)
					rather than the slug + CSS capitalize hack, same reason
					as the drawer header sub-line.
				-->
				<span class="text-gray-900" x-text="drawer.payout.payout_method_label || '—'"></span>
			</div>

			<div class="flex items-baseline justify-between gap-3">
				<span class="text-gray-500"><?php esc_html_e( 'Payout date', 'affiliate-wp' ); ?></span>
				<span class="text-gray-900" x-text="drawer.payout.date_formatted"></span>
			</div>

			<!--
				Provider fees row. Label is method-named ("PayPal fees" /
				"Stripe fees") so the provider is explicit — "Total fees"
				on its own didn't say WHO charged or WHO paid. The fees
				are deducted from the site owner's provider balance when
				the payout is sent (affiliate's payout amount is gross,
				not net of fees), but that's implicit in the admin-panel
				context. Title attribute spells it out for hover.

				Hidden when no fee data is recorded (manual / store-
				credit / Stripe-before-transfer cases) so the row doesn't
				render "—" needlessly.
			-->
			<template x-if="drawer.payout.total_fees_formatted">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"
						:title="'Charged to your ' + ( drawer.payout.payout_method_label || 'provider' ) + ' account when this payout was sent.'">
						<span x-text="( drawer.payout.payout_method_label || '' ) + ' '"></span><?php esc_html_e( 'fees', 'affiliate-wp' ); ?>
					</span>
					<span class="text-gray-900" x-text="drawer.payout.total_fees_formatted"></span>
				</div>
			</template>

			<!--
				PayPal bookkeeping — Batch ID + last-checked stamp. Moved
				here from the top "PayPal — Pending" summary card when the
				summary card is suppressed by the Next Steps card. The data
				is still useful for support tickets and for confirming the
				system is actively polling, but its scope is batch-level
				(shared across every payout in the same AffiliateWP batch),
				which is misleading when surfaced at the top of a single-
				payout drawer. Living in Details puts it where other
				system-side metadata lives.

				ID renders as plain monospace text — PayPal doesn't expose
				a stable per-batch UI URL (only a generic Activity / Reports
				list page that's unhelpful), so a clickable affordance
				would lie about what the link does. Admins can copy the ID
				to paste into PayPal's search.
			-->
			<!--
				Both PayPal rows are gated on `! drawer.showSummaryCard`: the top
				summary card owns Batch ID + Last verified when visible, so Details
				only carries them as the fallback when the summary card is
				suppressed (Next Steps active, superseded). Without the gate a
				processing PayPal payout printed both values twice.
			-->
			<template x-if="! drawer.showSummaryCard && drawer.paypalData && drawer.paypalData.paypal_batch_id">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'PayPal batch ID', 'affiliate-wp' ); ?></span>
					<span class="text-gray-900 font-mono text-xs select-all" x-text="drawer.paypalData.paypal_batch_id"></span>
				</div>
			</template>

			<template x-if="! drawer.showSummaryCard && drawer.paypalData && drawer.paypalData.last_checked_human">
				<div class="flex items-baseline justify-between gap-3">
					<!--
						"Last checked" alone is ambiguous: admin reads it as
						"we last checked the affiliate's PayPal email." It's
						actually "our system last polled PayPal's API to ask
						for the batch's current status." Disambiguated label:
						"PayPal status checked" puts the object of the check
						(PayPal's API status response) in the label itself.
					-->
					<span class="text-gray-500"><?php esc_html_e( 'PayPal status checked', 'affiliate-wp' ); ?></span>
					<span class="text-gray-900 text-xs"
						x-text="drawer.paypalData.last_checked_human + ' (' + (drawer.paypalData.poll_count || 0) + ' check' + ((drawer.paypalData.poll_count || 0) === 1 ? '' : 's') + ')'"></span>
				</div>
			</template>

			<!--
				Raw failure reason for power users. Lives in the Details
				panel so it's behind the standard "collapsed by default"
				disclosure: most admins read the Next Steps card and never
				need this string. The minority debugging an unfamiliar
				failure mode (or filing a support ticket) can expand
				Details and copy the verbatim error.

				D20: the row used to render the raw PayPal JSON blob
				verbatim, which broke the layout (long unbroken strings)
				and read as hostile to admins. Now mirrors the Summary
				card: a parsed headline (paypalData.error_headline /
				payout.error_message) on the row, and the structured
				payload tucked into a sibling `<details>` block for
				support investigations. `wrap-anywhere` + `break-words`
				are required because JSON has no natural break points.
			-->
			<template x-if="drawer.isFailed && ( ( drawer.paypalData && ( drawer.paypalData.error_headline || drawer.paypalData.error ) ) || drawer.payout.error_message )">
				<div class="flex flex-col gap-1">
					<div class="flex items-baseline justify-between gap-3">
						<span class="text-gray-500"><?php esc_html_e( 'Error', 'affiliate-wp' ); ?></span>
						<span class="text-gray-900 text-right max-w-[60%] break-words"
							style="overflow-wrap: anywhere; word-break: break-word;"
							x-text="( drawer.paypalData && ( drawer.paypalData.error_headline || drawer.paypalData.error ) ) || drawer.payout.error_message"></span>
					</div>
					<template x-if="drawer.paypalData && drawer.paypalData.error_raw">
						<details class="self-end" style="max-width: 100%;">
							<summary class="cursor-pointer text-gray-500 hover:text-gray-700 select-none text-right"
								style="font-size: 11px;">
								<?php esc_html_e( 'Show raw provider response', 'affiliate-wp' ); ?>
							</summary>
							<pre class="mt-1 p-2 bg-gray-50 border border-gray-200 rounded text-gray-800 break-words select-all m-0"
								style="font-size: 11px; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; max-width: 100%;"
								x-text="drawer.paypalData.error_raw"></pre>
						</details>
					</template>
				</div>
			</template>

			<template x-if="drawer.payout.service_account">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Payout account', 'affiliate-wp' ); ?></span>
					<span class="text-gray-900" x-text="drawer.payout.service_account"></span>
				</div>
			</template>

			<template x-if="drawer.payout.service_invoice_link">
				<div class="flex items-baseline justify-between gap-3">
					<span class="text-gray-500"><?php esc_html_e( 'Invoice link', 'affiliate-wp' ); ?></span>
					<a :href="drawer.payout.service_invoice_link"
						target="_blank"
						rel="noopener noreferrer"
						class="text-affwp-link hover:text-affwp-link-hover truncate max-w-xs"
						x-text="drawer.payout.service_invoice_link"></a>
				</div>
			</template>

			</div>
		</div>

	</div>
</template>

<!--
	Integrator-hook output (`affwp_edit_payout_top/end/bottom`) plus any
	future core "extras" are captured server-side by the AJAX handler and
	shipped in drawer.payout.details_extras_html. Rendered as a bare
	vertical stack so the contributor chooses its own framing — emit
	affwp_card() for a framed card, affwp_property_list() to add label/value
	rows in the drawer's native style, or affwp_data_table() for tabular
	content. Legacy <tr>-only output from _end is auto-wrapped server-side
	(see affwp_wrap_legacy_payout_end_rows) so unupdated addons still render.
-->
<template x-if="drawer.payout && drawer.payout.details_extras_html">
	<div class="space-y-3" x-html="drawer.payout.details_extras_html"></div>
</template>
