<?php
/**
 * مشتریان — جزئیات یک مشتری (بارگذاری جزئی در همان تب).
 *
 * Expects $user (WP_User) set by zerti_render_customer_detail().
 */
if (!defined('ABSPATH')) {
    exit;
}

if (!isset($user) || !($user instanceof WP_User)) {
    return;
}

$uid = (int) $user->ID;
$uid_label = zerti_to_persian_digits((string) $uid);

$first_name = trim((string) get_user_meta($uid, 'billing_first_name', true));
$last_name = trim((string) get_user_meta($uid, 'billing_last_name', true));
$display_name = trim((string) $user->display_name);
if ($display_name === '') {
    $display_name = trim($first_name . ' ' . $last_name);
}
if ($display_name === '') {
    $display_name = trim((string) $user->user_login);
}
if ($display_name === '') {
    $display_name = __('Untitled', 'zerti');
}
$name_display = zerti_to_persian_digits($display_name);

$email = trim((string) $user->user_email);
$username = trim((string) $user->user_login);

$phone = trim((string) get_user_meta($uid, 'billing_phone', true));
if ($phone === '') {
    $phone = trim((string) get_user_meta($uid, 'shipping_phone', true));
}

$registered_ts = strtotime((string) $user->user_registered);
if ($registered_ts === false) {
    $registered_ts = 0;
}
$registered_label = $registered_ts > 0 ? zerti_format_datetime($registered_ts) : '—';

$order_count = 0;
$money_spent = 0.0;

$role_labels = [];
if (!empty($user->roles)) {
    $wp_roles = wp_roles();
    foreach ($user->roles as $slug) {
        if (isset($wp_roles->roles[$slug]['name'])) {
            $role_labels[] = translate_user_role($wp_roles->roles[$slug]['name']);
        }
    }
}
$role_display = $role_labels !== [] ? implode('، ', $role_labels) : '—';

$customer_orders = [];
if (function_exists('wc_get_orders')) {
    $orders_page = 1;
    $orders_per_page = 100;
    $orders_max_pages = 1;
    do {
        $wc_orders_result = wc_get_orders([
            'customer_id' => $uid,
            'limit' => $orders_per_page,
            'paged' => $orders_page,
            'orderby' => 'date',
            'order' => 'DESC',
            'paginate' => true,
        ]);
        $batch = [];
        if (is_object($wc_orders_result) && isset($wc_orders_result->orders) && is_array($wc_orders_result->orders)) {
            $batch = $wc_orders_result->orders;
            $orders_max_pages = max(1, (int) ($wc_orders_result->max_num_pages ?? 1));
        } elseif (is_array($wc_orders_result)) {
            $batch = $wc_orders_result;
            $orders_max_pages = 1;
        }
        foreach ($batch as $order_obj) {
            if (is_a($order_obj, 'WC_Order')) {
                $customer_orders[] = $order_obj;
            }
        }
        $orders_page++;
    } while ($orders_page <= $orders_max_pages);
}

if (function_exists('zerti_customer_paid_order_stats_from_orders')) {
    $paid_stats = zerti_customer_paid_order_stats_from_orders($customer_orders);
    $order_count = (int) ($paid_stats['count'] ?? 0);
    $money_spent = (float) ($paid_stats['total'] ?? 0.0);
}

$last_order = null;
if ($customer_orders !== []) {
    $last_order = $customer_orders[0];
} elseif (function_exists('wc_get_order')) {
    $fallback_last_order_id = (int) get_user_meta($uid, '_last_order', true);
    $maybe_order = $fallback_last_order_id > 0 ? wc_get_order($fallback_last_order_id) : false;
    if ($maybe_order && is_a($maybe_order, 'WC_Order')) {
        $last_order = $maybe_order;
    }
}

$last_order_customer_fields = [];
$last_order_customer_title = __('Customer information', 'zerti');
$last_order_customer_note = '';
if ($last_order && is_a($last_order, 'WC_Order')) {
    if (function_exists('zerti_wc_order_invoice_display_customer_fields')) {
        $last_order_customer_fields = zerti_wc_order_invoice_display_customer_fields($last_order);
    }
    if (function_exists('zerti_wc_order_display_customer_section_title')) {
        $last_order_customer_title = zerti_wc_order_display_customer_section_title($last_order);
    }
    $last_order_customer_note = trim((string) $last_order->get_customer_note());
}

$avatar_url = get_avatar_url($uid, ['size' => 96]);
?>
<div
    class="zerti-component zerti-component-customers zerti-customer-detail"
    data-zerti-customer-id="<?php echo esc_attr((string) $uid); ?>"
>
    <div class="zerti-customer-detail__main zerti-scrollbar-thin">
        <div class="zerti-customer-detail__actions mb-3" role="toolbar" aria-label="<?php esc_attr_e('Customer actions', 'zerti'); ?>">
            <a
                href="<?php echo esc_url(zerti_admin_route_url(['tab' => 'customers'])); ?>"
                class="btn btn-outline-secondary btn-sm zerti-customer-detail-back d-inline-flex align-items-center gap-1"
            >
                <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                <?php esc_html_e('Back to customers list', 'zerti'); ?>
            </a>
        </div>

        <article class="zerti-shop-invoice zerti-customer-detail__card" aria-label="<?php esc_attr_e('Customer card', 'zerti'); ?>">
            <header class="zerti-shop-invoice__header">
                <div class="zerti-shop-invoice__brand">
                    <?php if ($avatar_url) : ?>
                        <img
                            class="zerti-customer-detail__avatar"
                            src="<?php echo esc_url($avatar_url); ?>"
                            alt="<?php echo esc_attr($display_name); ?>"
                            width="64"
                            height="64"
                            decoding="async"
                        />
                    <?php endif; ?>
                    <div class="zerti-shop-invoice__brand-text">
                        <h2 class="zerti-shop-invoice__title mb-0"><?php echo esc_html($name_display); ?></h2>
                        <?php if ($username !== '' && $username !== $display_name) : ?>
                            <p class="zerti-shop-invoice__seller mb-0">
                                <span class="zerti-shop-invoice__seller-name" dir="ltr"><?php echo esc_html($username); ?></span>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>

                <dl class="zerti-shop-invoice__meta mb-0">
                    <div class="zerti-shop-invoice__meta-row">
                        <dt><?php esc_html_e('Customer ID', 'zerti'); ?></dt>
                        <dd dir="rtl"><?php echo esc_html($uid_label); ?></dd>
                    </div>
                    <?php if ($email !== '') : ?>
                        <div class="zerti-shop-invoice__meta-row">
                            <dt><?php esc_html_e('Email', 'zerti'); ?></dt>
                            <dd dir="ltr"><?php echo esc_html($email); ?></dd>
                        </div>
                    <?php endif; ?>
                    <?php if ($phone !== '') : ?>
                        <div class="zerti-shop-invoice__meta-row">
                            <dt><?php esc_html_e('Phone', 'zerti'); ?></dt>
                            <dd dir="ltr"><?php echo esc_html(zerti_to_persian_digits($phone)); ?></dd>
                        </div>
                    <?php endif; ?>
                    <div class="zerti-shop-invoice__meta-row">
                        <dt><?php esc_html_e('Registration date', 'zerti'); ?></dt>
                        <dd><?php echo esc_html($registered_label); ?></dd>
                    </div>
                    <div class="zerti-shop-invoice__meta-row">
                        <dt><?php esc_html_e('Role', 'zerti'); ?></dt>
                        <dd><?php echo esc_html($role_display); ?></dd>
                    </div>
                </dl>
            </header>

            <div class="zerti-shop-invoice__divider" role="presentation"></div>

            <section class="zerti-shop-invoice__items" aria-labelledby="zerti-customer-detail-stats-heading">
                <h3 id="zerti-customer-detail-stats-heading" class="zerti-shop-invoice__section-title">
                    <?php esc_html_e('Activity summary', 'zerti'); ?>
                </h3>
                <div class="zerti-customer-detail__stats">
                    <div class="zerti-customer-detail__stat">
                        <span class="zerti-customer-detail__stat-label"><?php esc_html_e('Order count', 'zerti'); ?></span>
                        <span class="zerti-customer-detail__stat-value"><?php echo esc_html(zerti_to_persian_digits((string) $order_count)); ?></span>
                    </div>
                    <div class="zerti-customer-detail__stat">
                        <span class="zerti-customer-detail__stat-label"><?php esc_html_e('Total purchases', 'zerti'); ?></span>
                        <span class="zerti-customer-detail__stat-value"><?php echo wp_kses_post(zerti_wc_price_html_persian($money_spent)); ?></span>
                    </div>
                </div>
            </section>

            <?php if ($last_order_customer_fields !== []) : ?>
                <section class="zerti-shop-invoice__party" aria-labelledby="zerti-customer-detail-party-heading">
                    <h3 id="zerti-customer-detail-party-heading" class="zerti-shop-invoice__section-title">
                        <?php echo esc_html($last_order_customer_title); ?>
                    </h3>
                    <div class="zerti-shop-invoice__party-body">
                        <?php zerti_wc_render_order_customer_field_rows($last_order_customer_fields); ?>
                    </div>
                </section>
            <?php endif; ?>

            <?php if ($last_order_customer_note !== '') : ?>
                <section class="zerti-shop-invoice__note" aria-labelledby="zerti-customer-detail-note-heading">
                    <h3 id="zerti-customer-detail-note-heading" class="zerti-shop-invoice__section-title">
                        <?php esc_html_e('Customer note', 'zerti'); ?>
                    </h3>
                    <p class="zerti-shop-invoice__note-text mb-0"><?php echo esc_html($last_order_customer_note); ?></p>
                </section>
            <?php endif; ?>

            <?php if ($customer_orders !== []) : ?>
                <section class="zerti-shop-invoice__items" aria-labelledby="zerti-customer-detail-orders-heading">
                    <h3 id="zerti-customer-detail-orders-heading" class="zerti-shop-invoice__section-title">
                        <?php
                        printf(
                            /* translators: %s: order count (Persian digits). */
                            esc_html__('Customer orders (%s)', 'zerti'),
                            esc_html(zerti_to_persian_digits((string) count($customer_orders)))
                        );
                        ?>
                    </h3>
                    <div class="table-responsive zerti-shop-order-items-wrap">
                        <table class="table table-sm align-middle mb-0 zerti-shop-order-items-table">
                            <thead>
                                <tr>
                                    <th scope="col" class="text-center"><?php esc_html_e('ID', 'zerti'); ?></th>
                                    <th scope="col" class="text-center"><?php esc_html_e('Date', 'zerti'); ?></th>
                                    <th scope="col" class="text-center"><?php esc_html_e('Status', 'zerti'); ?></th>
                                    <th scope="col" class="text-end"><?php esc_html_e('Total amount', 'zerti'); ?></th>
                                    <th scope="col" class="text-center"><?php esc_html_e('Details', 'zerti'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($customer_orders as $customer_order) : ?>
                                    <?php
                                    if (!is_a($customer_order, 'WC_Order')) {
                                        continue;
                                    }
                                    $r_id = (int) $customer_order->get_id();
                                    $r_id_label = zerti_to_persian_digits((string) $r_id);
                                    $r_created = $customer_order->get_date_created();
                                    $r_ts = ($r_created && is_a($r_created, 'WC_DateTime')) ? (int) $r_created->getTimestamp() : 0;
                                    $r_date = $r_ts > 0 ? zerti_format_datetime($r_ts) : '—';
                                    $r_status_slug = (string) $customer_order->get_status();
                                    $r_status_label = zerti_wc_order_status_label_fa($r_status_slug);
                                    $r_status_display = function_exists('zerti_localize_digits')
                                        ? zerti_localize_digits($r_status_label)
                                        : zerti_to_persian_digits($r_status_label);
                                    $r_status_class = 'bg-secondary';
                                    switch ($r_status_slug) {
                                        case 'completed':
                                        case 'processing':
                                            $r_status_class = 'bg-success';
                                            break;
                                        case 'pending':
                                        case 'on-hold':
                                        case 'draft':
                                        case 'checkout-draft':
                                            $r_status_class = 'bg-warning text-dark';
                                            break;
                                        case 'cancelled':
                                        case 'failed':
                                            $r_status_class = 'bg-danger';
                                            break;
                                        case 'refunded':
                                            $r_status_class = 'bg-info text-dark';
                                            break;
                                    }
                                    ?>
                                    <tr class="zerti-shop-order-items-row">
                                        <td class="text-center" dir="ltr">#<?php echo esc_html($r_id_label); ?></td>
                                        <td class="text-center"><?php echo esc_html($r_date); ?></td>
                                        <td class="text-center">
                                            <span class="badge <?php echo esc_attr($r_status_class); ?>" dir="rtl">
                                                <?php echo esc_html($r_status_display); ?>
                                            </span>
                                        </td>
                                        <td class="text-end"><?php echo wp_kses_post(zerti_wc_price_html_persian((float) $customer_order->get_total())); ?></td>
                                        <td class="text-center">
                                            <?php
                                            echo wp_kses_post(
                                                function_exists('zerti_shop_order_detail_link_html')
                                                    ? zerti_shop_order_detail_link_html($r_id)
                                                    : ''
                                            );
                                            ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            <?php endif; ?>
        </article>
    </div>
</div>
