<?php

namespace App\Http\Controllers;

use App\Models\UserDevice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class UserDeviceController extends Controller
{
    protected $module, $data = [];

    public function __construct()
    {
        $this->module = new UserDevice();
        $this->data['module_name'] = 'User Devices';
        $this->data['view_directory'] = 'pages.device';
        $this->data['parent_named_route'] = 'devices';
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {

            $data = $this->module::with('user')
            ->select([
                'user_devices.*',
                DB::raw("users.name AS full_name")
            ])
            ->leftJoin('users', 'user_devices.user_id', '=', 'users.id');

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('sno', function ($row) {
                    static $index = 0; // Static variable to keep track of the index
                    $page = request()->get('start', 0); // Get the start parameter
                    $index++;
                    return $page + $index;
                })
                ->addColumn('is_notify', function ($row) {
                    return $row->is_notify
                        ? '<i style="color:green;" class="menu-icon tf-icons bx bx-check"></i> Allowed'
                        : '<i style="color:red;" class="menu-icon tf-icons bx bx-x"></i> Blocked';
                })
                ->rawColumns(['is_notify'])

                ->filterColumn('full_name', function ($query, $keyword) {
                    $query->whereRaw("users.name like ?", ["%{$keyword}%"]);
                })
                ->make(true);
        }

        $this->data['page'] = 'List';

        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }
}
