<?php


use App\Models\BranchModel;
use App\Models\CentralizedUsers;
use App\Models\ClientModel;
use App\Models\InvoiceModel;
use App\Models\RightsModel;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use NumberToWords\NumberToWords;



if (!function_exists("storeFile")) {
    function storeFile($file, $path)
    {
        // $subdomain = 'billing';
        $host = request()->getHost();
        $subdomain = explode('.', $host)[0];

        $fileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $fileExtension = $file->getClientOriginalExtension();
        $uniqueFileName = $fileName . '_' . time() . '.' . $fileExtension;

        $filePath = $subdomain . '/' . $path . '/' . $uniqueFileName;

        if (Storage::disk('s3')->exists($filePath)) {
            return $filePath;
        }

        $filePath = $file->storeAs($subdomain . '/' . $path, $uniqueFileName, 's3');

        Storage::disk('s3')->setVisibility($filePath, 'public');

        return $filePath;
    }
}


if (!function_exists("getFileUrl")) {
    function getFileUrl($filePath)
    {
        $url = Storage::disk('s3')->url($filePath);
        return $url;
    }
}

function amountToWords($amount)
{
    $numberToWords = new NumberToWords();
    $numberTransformer = $numberToWords->getNumberTransformer('en'); // 'en' for English
    $integerPart = floor($amount);
    $decimalPart = round(($amount - $integerPart) * 100);

    $words = ucfirst($numberTransformer->toWords($integerPart)) . " rupees";
    if ($decimalPart > 0) {
        $words .= " and " . $numberTransformer->toWords($decimalPart) . " paise";
    }
    return $words;
}
if (!function_exists("userBranch")) {
    function userBranch()
    {
        $user = Auth::user();
        $branch_id = DB::table('branch_user')->where('user_id', $user->id)->pluck('branch_id')->toArray();
        $branch = BranchModel::whereIn('id', $branch_id)->get();
        return $branch;

    }
}

if (!function_exists('saveClient')) {

    function saveClient($request)
    {
        $user = User::where('phone', $request->client_num)->first();

        if (!empty($user)) {
            $client = ClientModel::where('user_id', $user->id)->first();
            return $client->id;
        } else {
            do {
                $randomEmail = Str::random(10) . '@billing.com';
            } while (
                User::where('email', $randomEmail)->exists() ||
                CentralizedUsers::where('email', $randomEmail)->exists()
            );
            $right = RightsModel::where('rights_type', 'client')->first();
            $clientRight = $right ? $right->id : null;

            $user = User::create([
                'name' => $request->client_name,
                'email' => $randomEmail,
                'phone' => $request->client_num,
                'password' => Hash::make('client@123'),
                'user_flg' => 'C',
                'active_status' => 'A',
                'branch_id' => session('branch_id'),
                'rights_id' => $clientRight,
            ]);

            $client = ClientModel::create([
                'user_id' => $user->id,
                'branch_id' => session('branch_id'),
                'active_status' => 'A',
            ]);

            $allBranchIds = DB::table('branch')->pluck('id');
            $allCompanyIds = DB::table('company')->pluck('id');

            $branchInsertData = [];
            $comapanyInsertData = [];

            foreach ($allBranchIds as $branchId) {
                $branchInsertData[] = [
                    'user_id' => $user->id,
                    'branch_id' => $branchId,
                ];
            }

            foreach ($allCompanyIds as $companyId) {
                $comapanyInsertData[] = [
                    'user_id' => $user->id,
                    'company_id' => $companyId,
                ];
            }

            DB::table('branch_user')->insert($branchInsertData);
            DB::table('company_user')->insert($comapanyInsertData);

            centralizedUsers($request->client_name, $user->email, $request->client_num);

            return $client->id;
        }
    }

    if (!function_exists('centralizedUsers')) {

        function centralizedUsers($name, $email, $number)
        {
            CentralizedUsers::create([
                'name' => $name,
                'email' => $email,
                'phone' => $number,
                'domain_name' => request()->getHost(),
            ]);
        }

    }
    if (!function_exists('centralizedUsersDelete')) {

        function centralizedUsersDelete($email)
        {
            CentralizedUsers::where('email', $email)->delete();
        }

    }
    if (!function_exists('getPrefixes')) {

        function getPrefixes($request, $client_id)
        {
            $client = ClientModel::find($client_id);
            $branch = $client ? BranchModel::find($client->branch_id) : null;

            if ($branch) {
                $prefix = ($request->gst == 'Y')
                    ? $branch->prefix
                    : ($branch->non_gst_prefix ?? ($branch->prefix . 'NG'));
            } else {
                $prefix = ($request->gst == 'Y') ? 'INV' : 'INVNG';
            }

            $lastInvoice = InvoiceModel::where('invoice_id', 'like', $prefix . '-%')
                ->orderBy('id', 'desc')
                ->first();

            if ($lastInvoice) {
                $lastInvoiceId = $lastInvoice->invoice_id;
                $parts = explode('-', $lastInvoiceId);
                $number = (int) end($parts);
                $newNumber = str_pad($number + 1, 3, '0', STR_PAD_LEFT);
                $invoice_id = $prefix . '-' . $newNumber;
            } else {
                $invoice_id = $prefix . '-001';
            }

            return $invoice_id;
        }
    }

}