<?php

namespace PortalPeople\invoicing\services;

use backend\models\Cartsbe;
use PortalPeople\invoicing\models\Invoicesbe;
use Yii;
use yii\helpers\Json;

/**
 * Invoice Factory Service
 *
 * Maps cart data to invoice snapshot payload for immutable storage.
 */
class InvoiceFactory
{
    /**
     * Create invoice data snapshot from cart
     *
     * @param Cartsbe $cart
     * @return array
     */
    public function createInvoiceDataFromCart(Cartsbe $cart): array
    {
        return [
            'source_cart_id' => $cart->id,
            'source_centrearrddate' => $cart->centrearrddate,
            'generated_at' => date('Y-m-d H:i:s'),
            'generation_key' => $this->generateUniqueKey($cart),
            
            // Invoice number (can be customized by your numbering scheme)
            'invoice_number' => $this->generateInvoiceNumber($cart),
            
            // Copy key cart fields as immutable snapshot
            'cartid' => $cart->id,
            'email' => $cart->email,
            'name' => $cart->name,
            'namefirstname' => $cart->namefirstname,
            'namelastname' => $cart->namelastname,
            'telephone' => $cart->telephone,
            'fulladdress' => $cart->fulladdress,
            'postcode' => $cart->postcode,
            'centername' => $cart->centername,
            'centrearrddate' => $cart->centrearrddate,
            'centredepdate' => $cart->centredepdate,
            
            // Financial snapshot
            'subtotal' => $cart->subtotal,
            'total' => $cart->total,
            'tax' => $cart->tax,
            'shipping' => $cart->shipping,
            'amountpaid' => $cart->amountpaid,
            
            // Order metadata
            'ordernumber' => $cart->ordernumber,
            'orderref' => $cart->orderref,
            'status' => $cart->status,
            'billingstatus' => $cart->billingstatus,
            'paymentmethod' => $cart->paymentmethod,
            
            // Complete snapshot as JSON for audit trail
            'source_snapshot_json' => Json::encode([
                'cart_id' => $cart->id,
                'cart_attributes' => $cart->getAttributes(),
                'snapshot_timestamp' => time(),
                'generated_by' => Yii::$app->user->identity?->id ?? 'console',
            ]),
        ];
    }

    /**
     * Generate unique key for idempotency
     *
     * @param Cartsbe $cart
     * @return string
     */
    public function generateUniqueKey(Cartsbe $cart): string
    {
        $arrivalDate = date('Y-m-d', is_numeric($cart->centrearrddate) 
            ? $cart->centrearrddate 
            : strtotime($cart->centrearrddate));
        
        return sprintf('CART_%d_ARRDATE_%s', $cart->id, $arrivalDate);
    }

    /**
     * Generate invoice number (override with your custom numbering logic)
     *
     * @param Cartsbe $cart
     * @return string
     */
    public function generateInvoiceNumber(Cartsbe $cart): string
    {
        // Example: INV-20260311-12345
        $date = date('Ymd');
        $cartId = str_pad($cart->id, 5, '0', STR_PAD_LEFT);
        return "INV-{$date}-{$cartId}";
    }
}
