<?php
/*
* Copyright (c) 2022.
* Aidyn Sapargaliyev
* Nur-Sultan (Astana), Kazakhstan
* ТОО Дизайн лаборатория А7
* https://a7.kz
*/

/**
 * @var \A7kz\Platform\Modules\Platform\Core\Services\Application\CrudApplication $app
 */

use A7kz\Platform\Modules\Platform\Core\Services\Data\DataTypes;
use Illuminate\Support\Carbon;

$show = false;
$actions = $app->getActions();
if (isset($actions->show) && \A7kz\Platform\Modules\Platform\Acl\Facades\Acl::isCanRun($app->getName(), 'show')) {
    $show = true;
}
?>
<style>
    .rowStyleStatic td {}
</style>
<x-component name="Js.Before" :params="['app'=>$app]" :module="$module"/>
{!! $app->show_message() !!}
<div class="global-actions">
    <div class="left-content">
        @if(!is_null($app->filter))
            <span class="btn btn-primary filter-trigger">{{__("Фильтр")}}</span>
        @endif
        <h5 class="global-title px-4">{{__($app->getUiTitle("grid"))}}</h5>
    </div>
    <div class="right-content">
        <x-component name="App.components.HeadActions" :params="['app'=>$app]" :module="$module"/>
    </div>
</div>
<div>
<div class="filter-container-parent">
    {!! $app->filter() !!}
</div>
<div class="table-container @if($app->data->isSubCrud() ?? false)subcrud-table @endif">
    <table class="table table-hover">
        <thead>
        <tr>
            @foreach($app->cols as $col)
                <th>
                    <a href="@if($col->name == $app->data->getSortField())
                    @if($app->data->getSortOrder() == 'asc')
                    {{$app->getPath().'?sort=desc-'.$col->name.'&page='.$app->data->getPage()}}
                    @else
                    {{$app->getPath().'?sort=asc-'.$col->name.'&page='.$app->data->getPage()}}
                    @endif
                    @else
                    {{$app->getPath().'?sort=asc-'.$col->name.'&page='.$app->data->getPage()}}
                    @endif">
                        {{__($col->caption)}}
                        @if($col->name == $app->data->getSortField())
                            @if($app->data->getSortOrder() == 'asc')
                                <i class="bi bi-arrow-up"></i>
                            @else
                                <i class="bi bi-arrow-down"></i>
                            @endif
                        @endif
                    </a>
                </th>
            @endforeach
            @if(!$app->isReadonly())
                @if(isset($app->action['row']))
                    <th></th>
                @endif
            @endif
        </tr>
        </thead>
        <tbody>

        @foreach($app->rows as $row)
            @php
                $href = !isset($targetLink) ?
                    $app->getPath()."/show?pk=".$row->{$app->data->getPk()} :
                    lurl("app/".$targetLink->application."/show?pk=".$row->{$app->data->getPk()});
            @endphp

            <tr @if(\A7kz\Platform\Modules\Platform\Acl\Facades\Acl::isCanRun($app->getName(), 'show')) style="cursor: pointer;"
                class="grid-table-row" data-href="{{$href}}" @endif>
                @foreach($app->cols as $col)
                    <td @if(isset($row->style)) style="{{$row->style}}" @endif>
                        @if($app->data->fields[$col->name]->getType() == DataTypes::Boolean)
                            @if($row->{$col->name})
                                <i class="yes bi bi-check-circle-fill"></i>
                            @elseif(isset($app->data->fields[$col->name]->nullable) && is_null($row->{$col->name}))
                                <i class="wait bi bi-hourglass-split"></i>
                            @else
                                <i class="no bi bi-x-circle-fill"></i>
                            @endif
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Date)
                            {!! $row->{$col->name}?\Illuminate\Support\Carbon::parse($row->{$col->name})->format('d.m.Y'):'' !!}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::DateTime)
                            {!! $row->{$col->name}?\Illuminate\Support\Carbon::parse($row->{$col->name})->format('d.m.Y H:i:s'):'' !!}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Month)
                            {!! $row->{$col->name}?\A7kz\Platform\Models\Month::get($row->{$col->name}):'' !!}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Wysiwyg)
                            {!! $row->{$col->name} !!}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Foreign)
                            @php
                                $str = '';
                                if (isset($row->{$col->name . "_list_class_val"})) {
                                    $str = $row->{$col->name . "_list_class_val"};
                                } elseif (!empty($row->{$col->name})) {
                                    $templateKey = isset($app->data->fields[$col->name]->grid_template)
                                        ? 'grid_template'
                                        : (isset($app->data->fields[$col->name]->template) ? 'template' : null);

                                    if ($templateKey) {
                                        $str = $app->data->fields[$col->name]->{$templateKey};
                                        $str = str_replace('{lk}', app()->getLocale(), $str);

                                        foreach ($app->data->fields[$col->name]->display as $item) {
                                            $str = str_replace("{" . $item . "}", $row->{$col->name . "_" . $item}, $str);
                                        }

                                        $str = preg_replace_callback('/\{(.*?)\}/', function ($matches) use ($row) {
                                            return $row->{$matches[1]} ?? '';
                                        }, $str);
                                    } else {
                                        $str = '';
                                        foreach ($app->data->fields[$col->name]->display as $item) {
                                            $str .= $row->{$col->name . "_" . $item} . " ";
                                        }
                                    }
                                }
                            @endphp
                            {{ $str }}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Json)
                            {{var_dump(json_decode($row->{$col->name},true))}}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::Combined)
                            {{ data_get(json_decode($row->{$app->data->fields[$col->name]->getDbFieldName()},true), $app->data->fields[$col->name]->getFieldName()) }}
                        @elseif($app->data->fields[$col->name]->getType() == DataTypes::ExpirationStatus)
                            @php
                                $currentDate = Carbon::now();
                                $expirationDate = $row->{$col->name} != '' ? Carbon::parse($row->{$col->name}) : null;
                                $creationDate = $app->data->fields[$col->name]->started_at_field
                                    ? Carbon::parse($row->{$app->data->fields[$col->name]->started_at_field} ?? null)
                                    : null;

                                $isActive = match (true) {
                                    is_null($expirationDate) && is_null($creationDate) => true,
                                    is_null($creationDate) => $currentDate->lt($expirationDate),
                                    is_null($expirationDate) => $currentDate->gte($creationDate),
                                    default => ($currentDate->lt($expirationDate) and $currentDate->gte($creationDate)),
                                };

                                $status = $isActive ? 'active' : 'inactive';

                                $text = $app->data->fields[$col->name]->text[$status] ??
                                    ($isActive ? __('Активно') : __('Неактивно'));

                                $icon = $isActive
                                    ? '<i class="yes bi bi-check-circle-fill"></i>'
                                    : '<i class="no bi bi-x-circle-fill"></i>';

                                echo "$icon <span class='status-label'>$text</span>";
                            @endphp
                        @else
                            @php
                                $truncateLength = $col->truncate_length ?? mb_strlen($row->{ $col->name });
                                if (mb_strlen($row->{ $col->name }) > $truncateLength) {
                                    $row->{ $col->name } = mb_substr($row->{ $col->name }, 0, $truncateLength) . '...';
                                }
                            @endphp
                            @if($col->link ?? false)
                                <a href="{{ lurl(sprintf($col->link, ...array_map(fn($repl) => $row->{$repl}, $col->replace))) }}">
                                    {{ $row->{ $col->name } }}
                                </a>
                            @else
                                {{ $row->{ $col->name } }}
                            @endif
                        @endif
                    </td>
                @endforeach
                @if(!$app->isReadonly())
                    @if(isset($app->action['row']))
                        <td class="td-actions"
                            @if(isset($app->action['row']))  style="width: {{count($app->action['row'])*40}}px" @endif>
                            @foreach($app->action['row'] as $action=>$actionProperties)
                                @if(!is_null($actionProperties))
                                    <x-component name="Buttons.GridActionButton"
                                                 :params="[
                                            'app' => $app,
                                            'row' => $row,
                                            'action' => $action,
                                            'actionProps' => $actionProperties,
                                            'label' => $actionProperties->label,
                                            'btn' => $actionProperties->btn ?? null,
                                            'icon' => $actionProperties->icon ?? null
                                        ]"
                                    />
                                @endif
                            @endforeach
                        </td>
                    @endif
                @endif
            </tr>
        @endforeach
        </tbody>
        <tfoot>
        @if($app->rows->total() > $app->data->limit)
            <tr>
                <td class="td-pagination" colspan="{{count($app->cols)+1}}">
                    {{$app->rows->links()}}
                </td>
            </tr>
        @endif
        </tfoot>
    </table>
</div>
<x-component name="Js.After" :params="['app'=>$app]" :module="$module"/>
<x-component name="Additional.ImportAction" :params="['app'=>$app]" :module="$module"/>

@if(isset($app->getConfig()?->ui?->grid?->inject_component))
    @foreach($app->getCOnfig()->ui->grid->inject_component as $inject_component)
        <x-component :name="$inject_component" :module="$module" :params="['app'=>$app]"/>
    @endforeach
@endif

@if(isset($app->getConfig()?->ui?->grid?->inject_component))
    @if(!empty($app->getConfig()->ui->grid->on_render_emit_functions))
        <x-component name="Js.OnRenderEmitFunctions" :module="$module"
                     :params="['app' => $app, 'emitFunctions' => $app->getConfig()->ui->grid->on_render_emit_functions]"
        />
    @endif
@endif

<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".grid-table-row").forEach((el) => {
            el.addEventListener("click", (event) => {
                if (event.target.classList.contains("btn") || event.target.parentNode.classList.contains("btn")) {
                    return;
                }
                else {
                    window.open(el.dataset.href, '_self');
                }
            });
        });
    });
</script>
