<?php

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Exceptions\Exception;




if (!function_exists('tableRowsColors')) {
    function tableRowsColors(int $id): string
    {
        return ($id % 2 === 1) ? 'bg-gray-0' : 'bg-gray-100';
    }
}


if (!function_exists('buildBaseDataTable')) {
    /**
     * @throws Exception
     */
    function buildBaseDataTable($query, array $customColumns = [], array $rawColumns = [])
    {
        $dataTable = DataTables::eloquent($query)
            ->addIndexColumn()
            ->setRowId(fn($row) => "row_{$row->id}")
            ->setRowClass(fn($row) => tableRowsColors($row->id))
            ->addColumn('checkbox', fn($row) => renderCheckboxColumn($row));

        foreach ($customColumns as $name => $callback) {
            $dataTable->addColumn($name, $callback);
        }

        return $dataTable->rawColumns(array_merge(['checkbox'], $rawColumns));
    }
}

if (!function_exists('applySearch')) {
    function applySearch($query, array $columns = [])
    {
        $search = request('search');

        if ($search) {
            $query->where(function ($q) use ($columns, $search) {
                foreach ($columns as $col) {
                    $row     = $col['row'];
                    $pattern = ($col['type'] ?? 1) == 1 ? "%{$search}%" : "{$search}%";

                    if (str_contains($row, '.')) {
                        [$relation, $column] = explode('.', $row, 2);

                        $q->orWhereHas($relation, function ($rel) use ($column, $pattern) {
                            $rel->where($column, 'like', $pattern);
                        });
                    } else {
                        $q->orWhere($row, 'like', $pattern);
                    }
                }
            });
        }

        return $query;
    }
}

if (!function_exists('CustomerInfo')) {
    function CustomerInfo($row): string
    {
        $avatar = !empty($row->avatar) && !empty($row->avatar_path)
            ? Storage::disk('attachments')->url($row->avatar_path)
            : asset('assets/images/blank.svg');

        return <<<HTML
            <div class="d-flex align-items-center gap-2">
                <img src="{$avatar}" alt="avatar-{$row->id}" class="rounded-circle avatar-sm">
                <div class="d-flex flex-column">
                    <span class="text-primary">
                        {$row->name}
                        <span class="badge badge-soft-primary font-size-10 m-1">{$row->code}</span>
                    </span>
                    <span>{$row->email}</span>
                </div>
            </div>
        HTML;
    }
}

if (!function_exists('statusBadge')) {
    function statusBadge($status, string $configKey): string
    {
        $statuses = config($configKey);

        $statusData = $statuses[$status] ?? null;

        if (!$statusData) {
            return '';
        }

        $label = getLocalizedName($statusData);
        $color = $statusData['color'] ?? 'secondary';

        return "<span class='badge badge-soft-{$color}'>{$label}</span>";
    }
}

if (!function_exists('customerStatus')) {
    function customerStatus($row): string
    {
        return statusBadge($row->status, 'data-select.customer-status');
    }
}

if (!function_exists('subscriptionStatus')) {
    function subscriptionStatus($row): string
    {
        return statusBadge($row->status, 'data-select.subscriptions-status');
    }
}
