<?php

namespace PortalPeople\delivery\components;

use Yii;
use backend\models\ActionLog;

/**
 * Delivery Services Shared Components and functions
 * 
 */

class DeliveryService
{
    /**
     * Write a delivery action log entry without duplicating provider logging
     * and cart/null handling.
     *
     * @param mixed $cart
     */
    public static function logAction(
        $cart,
        string $type,
        string $message,
        string $category = 'delivery',
        ?string $sourceClass = null
    ): void {
        if (!is_object($cart) || empty($cart->id)) {
            Yii::warning($message, $category);
            return;
        }

        ActionLog::create([
            'class' => $sourceClass ?: static::class,
            'action' => 'create',
            'relatedid' => $cart->id,
            'type' => $type,
            'message' => $message . (!empty($cart->orderref) ? " for cart #{$cart->orderref}" : ''),
        ]);
    }

    /**
     * Store the consignment PDF in the cart's file storage
     *
     * @param Cart $cart The cart object
     * @param string $pdf The PDF content to store
     */
    public static function storeConsignmentPdf($cart, $pdf, $haulier)
    {
        // Assuming the cart has a method to store files, e.g., storeFile($filename, $content)
        $filename = "documents/consignments/{$cart->account_code}/{$haulier}_{$cart->orderref}.pdf";
        $filepath = Yii::getAlias('@' . $filename);
        $directory = dirname($filepath);
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true);
        }
        file_put_contents($filepath, $pdf);
        return $filename;
    }
}