<?php

use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

if (!function_exists('getDocTypeLabel')) {
    function getDocTypeLabel($type)
    {
        $docTypeLabels = [
            // sales
            'invoicesale'       => 'Facture de vente',
            'returnsale'        => 'Avoir de vente',
            'estimate'          => 'Devis',
            'deliverynote'      => 'Bon de livraison',
            // purchases
            'pricerequest'      => 'Demande de prix',
            'purchaseorder'     => 'Bon de commande',
            'receiptnote'       => 'Bon de réception',
            'invoicepurchase'   => 'Facture d’achat',
            'returnpurchase'    => 'Avoir d’achat',
            // stock movements
            'exitnote'          => 'Bon de sortie',
            'entrynote'         => 'Bon d’entrée',
            'transfernote'      => 'Bon de transfert',
            'adjustmentnote'    => 'Bon d’ajustement',
            // production
            'orderprod'         => 'Ordre de production',
            'generateprod'      => 'Bon de production',
        ];

        return $docTypeLabels[$type] ?? Str::title(str_replace('_', ' ', $type));
    }
}

if (!function_exists('cleanStorageUrl')) {
    function cleanStorageUrl($url)
    {
        // if it's already storage/... path
        if (strpos($url, 'storage/') !== false) {
            return public_path(str_replace(url('/'), '', $url));
        }

        // fallback: return URL as is
        return $url;
    }
}

if (!function_exists('copyImageToPublic')) {
    function copyImageToPublic(string $sourcePath)
    {
        // Check if the source file exists
        if (!File::exists($sourcePath)) {
            throw new \Exception("Source file does not exist: {$sourcePath}");
        }

        // Destination path in public folder
        $destinationPath = public_path('logo.png');

        // If logo.png exists, delete it first
        if (File::exists($destinationPath)) {
            File::delete($destinationPath);
        }

        // Copy the source file to destination
        File::copy($sourcePath, $destinationPath);

        return $destinationPath;
    }
}

if (!function_exists('getMethodOfPayment')) {

    function getMethodOfPayment($method)
    {
        $methods = [
           'cash' => 'Espèces',
            'credit_card' => 'Carte de crédit',
            'bank_transfer' => 'Virement bancaire',
            'cheque' => 'Chèque',
            'mobile_payment' => 'Paiement mobile',
            'paypal' => 'PayPal',
            'cryptocurrency' => 'Cryptomonnaie',
            'gift_card' => 'Carte cadeau',
            'direct_debit' => 'Prélèvement automatique',
            'wire_transfer' => 'Virement',
            'money_order' => 'Mandat',
            'payment_plan' => 'Plan de paiement',
            'other' => 'Autre'
        ];

        return $methods[$method] ?? Str::title(str_replace('_', ' ', $method));
    }
}

if (!function_exists('getModeShipping')) {

    function getModeShipping($method)
    {
        $methods = [
            'incluse' => 'Inclus',
            'exclude' => 'Exclus'
        ];

        return $methods[$method] ?? Str::title(str_replace('_', ' ', $method));
    }
}

//nethod return boolean  if operation has pricing or not by base as list of docType

if (!function_exists('hasPricing')) {

    function hasPricing($operation)
    {
        $docTypes = ['purchaseorder', 'estimate', 'invoicesale','invoicepurchase'];
        return in_array($operation, $docTypes);
    }
}

//item is separator
if (!function_exists('isSeparator')) {

    function isSeparator($item)
    {
        return $item['isSeparator'];
    }
}

if (!function_exists('safeSubtract')) {
    function safeSubtract($a, $b)
    {
        // Validate both values are numeric
        if (!is_numeric($a) || !is_numeric($b)) {
            return 0; // or throw an exception if you prefer
        }

        // Convert and subtract safely to avoid floating point precision issues
        return number_format((float)$a - (float)$b, 2, '.', '');

    }
}

//convert number to number with 2 decimal places and replace . with ,
if (!function_exists('formatNumber')) {

    function formatNumber($number)
    {
        return number_format($number, 2, ',', ' ');
    }
}

//operation is legal purchaseorder   , estimate , invoicesale


if (!function_exists('isLegalOperation')) {

    function isLegalOperation($operation)
    {
        $docTypes = ['purchaseorder', 'estimate', 'invoicesale'];
        return in_array($operation, $docTypes);
    }
}

//operations intern
// entrynote ,exitenote,transfernote,adjustmentnote
//'receiptnote','deliverynote',

if (!function_exists('isInternOperation')) {

    function isInternOperation($operation)
    {
        $docTypes = ['receiptnote','deliverynote','entrynote', 'exitenote', 'transfernote', 'adjustmentnote'];
        return in_array($operation, $docTypes);
    }
}

//calculate purcentage from number


if (!function_exists('calculatePercentage')) {
    //discountValue / this.subtotal * 100
    function calculatePercentage($number, $percentage)
    {
        return  $percentage / $number * 100;
    }
}


//set env value
if(!function_exists('setEnvValue')){
    function setEnvValue($key, $value)
{
    $path = base_path('.env');

    if (file_exists($path)) {
        // read current .env
        $env = file_get_contents($path);

        // replace if key exists
        if (strpos($env, $key) !== false) {
            $env = preg_replace(
                "/^{$key}=.*$/m",
                "{$key}={$value}",
                $env
            );
        } else {
            // else append new key
            $env .= "\n{$key}={$value}";
        }

        file_put_contents($path, $env);
    }
}

}
