<?php

namespace modules\selfserve\traits;

require_once WD . '/modules/selfserve/helpers/selfserve_lane_log_action.php';
require_once WD . '/objects/module_action_logs_o.php';

use modules\selfserve\helpers\selfserve_lane_log_action;
use objects\module_action_logs_o;

trait selfserve_lane_log_t
{
    /**
     * Log a lane action
     * @param selfserve_lane_log_action $action The action to log
     * @param int $status_code The status code of the action (default 200)
     * @param array $extra_data Additional data to include in the log
     * @return void
     */
    public function logLaneAction(selfserve_lane_log_action $action, int $status_code = 200, array $extra_data = []): void
    {
        try {
            $data = array_merge([
                'lane_id' => $this->id,
                'status' => $this->getLaneStatus()->name,
                'mode' => $this->getLaneMode()->name,
                'state' => $this->getLaneState()->name,
            ], $extra_data);

            if (method_exists($this, 'getCustomerNumber')) {
                $data['customer_number'] = $this->getCustomerNumber();
            }
            if (method_exists($this, 'getLicensePlate')) {
                $data['license_plate'] = $this->getLicensePlate();
            }

            (new module_action_logs_o())->add(
                'selfserve',
                $action->name,
                $status_code,
                $data
            );
        } catch (\Exception $e) {
            // Silently fail to not interrupt the main flow, or we could log it to a fallback error log
            error_log("Failed to log lane action: " . $e->getMessage());
        }
    }
}
