<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Admin\Transformer;

use BookiFlex\Core\Model\Customer\Customer;

defined( 'ABSPATH' ) || exit;

/**
 * Transforms Customer domain models to arrays for WP_List_Table display.
 *
 * This transformer handles:
 * - Converting domain objects to flat associative arrays
 * - Formatting dates and times for display
 * - Merging reservation and payment counts into rows
 * - Handling null safety for optional fields
 *
 * @package BookiFlex\Core\Admin\Transformer
 */
class CustomerTableListTransformer
{
    public const DATE_FORMAT = 'Y-m-d H:i:s';

    /**
     * Transform enriched service data to WP_List_Table format.
     *
     * Takes the enriched data structure from CustomerListService and converts
     * it to an array of associative arrays suitable for WP_List_Table rendering.
     *
     * @param array $data Service data with structure:
     *                    - customers: Customer[] - Domain models
     *                    - counts: array - Reservation and payment counts by customer ID
     * @return array[] Array of associative arrays for table rows
     */
    public function transform(array $data): array
    {
        $customers = $data['customers'] ?? [];
        $counts = $data['counts'] ?? [];

        if (empty($customers)) {
            return [];
        }

        $rows = [];

        foreach ($customers as $customer) {
            $rows[] = $this->transformCustomer($customer, $counts);
        }

        return $rows;
    }

    /**
     * Transform single customer with count data.
     *
     * @param Customer $customer Customer domain model
     * @param array $counts Count data indexed by customer ID
     * @return array Associative array for table row
     */
    private function transformCustomer(Customer $customer, array $counts): array
    {
        $customerId = $customer->getId();

        // Get count data or defaults
        $countData = $counts[$customerId] ?? [
            'reservations' => 0,
            'payments' => 0,
        ];

        return [
            // Basic customer data
            'id' => $customerId,
            'first_name' => $customer->getFirstName(),
            'last_name' => $customer->getLastName(),
            'email' => $customer->getEmail(),
            'phone' => $customer->getPhone() ?: '',

            // Aggregated counts
            'reservations' => $countData['reservations'],
            'payments' => $countData['payments'],

            // Timestamps (raw strings for backward compatibility)
            'created_at' => $customer->getCreatedAt()->format(self::DATE_FORMAT),
            'updated_at' => $customer->getUpdatedAt()?->format(self::DATE_FORMAT) ?? '',
        ];
    }
}