<?php

namespace modules\selfserve\traits;
require_once WD . '/modules/selfserve/helpers/selfserve_lane_status.php';
require_once WD . '/modules/selfserve/classes/selfserve_lane.php';

use classes\selfserve;
use Exception;
use modules\selfserve\classes\selfserve_lane;
use modules\selfserve\helpers\selfserve_lane_status;
use objects\order_items_o;
use objects\orders_o;

trait selfserve_lane_invoice_t
{
    /**
     * The product ID for minute-based billing
     * @var int|null $minute_billing_product_id
     */
    public ?int $minute_billing_product_id = null;
    /**
     * Get the minute billing product ID
     * @return int|null The product ID for minute-based billing, or null if not set
     */
    public function getMinuteBillingProductId(): ?int
    {
        $minute_billing_product_id = selfserve::getInstance()
            ->config
            ->minute_product
            ->getVariableValue();
        if (!empty($minute_billing_product_id)) {
            $this->minute_billing_product_id = $minute_billing_product_id;
        }
        return $this->minute_billing_product_id;
    }

    /**
     * Invoice for minute-based billing
     * @return bool True on success, false on failure
     * @throws Exception if lane ID is not set, lane is not occupied, customer number or license plate is not set, or product ID is not set
     */
    public function invoice(): bool
    {
        if (empty($this->id)) throw new \Exception("Lane ID is not set.");
        if ($this->getLaneStatus() !== selfserve_lane_status::OCCUPIED) throw new \Exception("Lane ID {$this->id} is not occupied; cannot invoice.");
        if (empty($this->getCustomerNumber())) throw new \Exception("Customer number is not set for lane ID {$this->id}.");
        if (empty($this->getLicensePlate())) throw new \Exception("License plate is not set for lane ID {$this->id}.");
        if (empty($product_id = $this->getMinuteBillingProductId())) throw new \Exception("Minute billing product ID is not set.");
        // Calculate minutes used
        $minutes = $this->getElapsedWashTime() / 60; // Convert seconds to minutes
        $minutes = (int)ceil($minutes); // Round up to nearest whole minute
        if ($minutes <= 0) throw new \Exception("No minutes to bill for lane ID {$this->id}.");
        $amount = $minutes; // Assuming 1 unit per minute, adjust as needed
        // Create invoice order
        $order = (new orders_o())->add(
            $this->getCustomerNumber(),
            2285, // System User ID
            '',
            '',
            (int)$this->department_lane->department->value(),
            (string)$this->getLicensePlate()
        );
        $order->lane->set($this->id);
        // Add product to order
        $order_items = new order_items_o();
        $order_items->addItemToOrder(
            $order->id,
            $product_id,
            2285, // System User ID
            $amount,
        );
        return true;
    }
}