<?php

namespace App\Traits\Basics\Yajra\Plans;


use App\Helpers\PermissionHelper;
use App\Models\Plan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

use Yajra\DataTables\Exceptions\Exception as YajraDataTableException;
use Yajra\DataTables\Facades\DataTables;

use Symfony\Component\HttpFoundation\JsonResponse;
use Exception;
use Log;

trait PlansTable
{

    /**
     * @throws Exception
     * @throws YajraDataTableException
     */
    public function yajra(Request $request): JsonResponse
    {
        $query = Plan::query();

        // البحث النصي
        $search = $request->input('search');
        if (!empty($search) && is_string($search)) {
            $searchTerm = '%' . trim($search) . '%';
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name_ar', 'like', $searchTerm)
                    ->orWhere('name_en', 'like', $searchTerm)
                    ->orWhere('price', 'like', $searchTerm)
                    ->orWhereHas('register', function ($q) use ($searchTerm) {
                        $q->where('name', 'like', $searchTerm);
                    });
            });
        }

        // فلتر النوع
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // فلتر الحالة
        if ($request->filled('status')) {
            $status = filter_var($request->status, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
            $query->where('is_active', $status);
        }

        // فلتر السعر
        if ($request->filled('price_min')) {
            $query->where('price', '>=', $request->price_min);
        }
        if ($request->filled('price_max')) {
            $query->where('price', '<=', $request->price_max);
        }

        return DataTables::eloquent($query)
            ->addIndexColumn()
            ->setRowId(fn($row) => "row-{$row->id}")
            ->addColumn('checkbox', fn($row) => renderCheckboxColumn($row))
            ->addColumn('name', fn($row) => $row->name)
            ->addColumn('type', fn($row) => getLocalizedName(config('data-select.plans-types')[$row->type]))
            ->addColumn('formatted_price', fn($row) => $row->formatted_price)
            ->addColumn('status', fn($row) => renderToggleSwitch($row, PermissionHelper::can('plans.edit'), 'is_active'))
            ->addColumn('actions', fn($row) => $this->actions($row))
            ->rawColumns(['checkbox', 'name', 'type', 'formatted_price', 'status', 'actions'])
            ->make(true);
    }

    /** ==============* Helpers *============== */
    protected function actions($row): string
    {
        $actions = [
            'edit' => [
                'name' => __('Edit'),
                'route' => route('plans.edit', encrypt($row->id)),
            ],
            'destroy' => [
                'name' => __('Remove'),
                'route' => route('plans.destroy', $row->id),
            ],
        ];

        $edit = '';
        $destroy = '';

        if (PermissionHelper::can('plans.edit')) {
            $edit = <<<HTML
                <a href="{$actions['edit']['route']}" class="dropdown-item">{$actions['edit']['name']}</a>
            HTML;
        }

        if (PermissionHelper::can('plans.delete')) {
            $destroy = <<<HTML
                <a class="dropdown-item text-danger button-delete" data-id="{$row->id}" data-name="{$row->name}">{$actions['destroy']['name']}</a>
            HTML;
        }

        return View::make('components.dropdown-menu', [
            'slot' => <<<HTML
                {$edit}{$destroy}
            HTML,
        ])->render();
    }

}
