<?php

namespace App\Services;

use App\Models\Tenant\User;
use App\Models\Tenant\WorkOrder;
use App\Tenancy\TenantManager;

/**
 * Resolves the internal margin percentage for a work order line.
 *
 * Terminology: this is "marja internă" — an internal profit margin the shop
 * takes on top of the mechanic's labor rate. It is NOT VAT/TVA and MUST NOT
 * be exposed on any customer-facing surface (PDF, tracking, receipts, API).
 *
 * Fallback chain:
 *   1. WorkOrder.override_margin_pct — per-Fișă override (special contracts)
 *   2. User.internal_margin_pct — per-mechanic setting (main location)
 *   3. Company.settings.default_internal_margin_pct — tenant-wide default
 *   4. 0.0 — no margin
 *
 * Semantics:
 *   client_price = whatever you charge (auto-computed OR manually entered)
 *   salary_base  = client_price × (1 - margin_pct / 100)
 *
 * The mechanic's payroll % applies to salary_base, never to client_price.
 */
class MarginResolver
{
    public function resolve(?WorkOrder $wo = null, ?User $mechanic = null): float
    {
        if ($wo && $wo->override_margin_pct !== null) {
            return (float) $wo->override_margin_pct;
        }
        if ($mechanic && $mechanic->internal_margin_pct !== null) {
            return (float) $mechanic->internal_margin_pct;
        }
        $tenant = app(TenantManager::class)->current();
        if ($tenant) {
            $default = data_get($tenant->settings, 'default_internal_margin_pct');
            if ($default !== null) return (float) $default;
        }
        return 0.0;
    }

    /**
     * Compute the salary base from a client-facing amount.
     * salary_base = client_price × (1 - margin_pct/100)
     */
    public function computeSalaryBase(float $clientPrice, float $marginPct): float
    {
        $factor = max(0.0, 1.0 - $marginPct / 100.0);
        return round($clientPrice * $factor, 2);
    }
}
