<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\DataTables\UsersDataTable;

class UserController extends Controller
{
    public function index()
    {
        // id column is displayed by default
        $idColumn = [['key' => 'id', 'label' => '#', 'visible' => true]];

        // Default columns
        $defaultColumns = collect((new User())->getFillable())->map(function ($field) {
            return [
                'key' => $field,
                'label' => ucfirst(str_replace('_', ' ', $field)),
                'visible' => true
            ];
        })->toArray();

        // Add additional or override specific columns
        $customColumns = [
            ['key' => 'created_at', 'label' => 'Joined Date', 'visible' => true],
            ['key' => 'updated_at', 'label' => 'Last Updated', 'visible' => false], // Optional hidden by default
        ];

        // Bonus: Customize Column Visibility Programmatically
        // If you want to set custom visibility rules based on user roles or permissions, add conditional logic inside your controller like this:
        // $customColumns = [
        //     ['key' => 'created_at', 'label' => 'Joined Date', 'visible' => auth()->user()->isAdmin()],
        // ];

        // Merge default columns with custom columns
        $userColumns = array_merge($idColumn, $defaultColumns, $customColumns);

        return view('users.index', compact('userColumns'));
    }

    public function data(Request $request)
    {
        $query = User::query();

        // Check if search is present and not empty
        if ($request->has('search') && trim($request->query('search')) !== '') {
            $search = $request->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $sort = $request->query('sort', 'id');
        $direction = $request->query('direction', 'asc');
        $query->orderBy($sort, $direction);

        $users = $query->paginate(4);

        return response()->json([
            'data'         => $users->items(),
            'current_page' => $users->currentPage(),
            'last_page'    => $users->lastPage(),
            'total'        => $users->total(),
        ]);
    }

    public function export(Request $request)
    {
        $users = User::all();
        $xmlContent = view('users.export', ['users' => $users])->render();

        return response($xmlContent, 200)
            ->header('Content-Type', 'application/xml')
            ->header('Content-Disposition', 'attachment; filename="users.xml"');
    }

    public function destroy(User $user)
    {
        $user->delete();
        return response()->noContent();
    }

    public function destroyMultiple(Request $request)
    {
        $ids = $request->input('ids', []);
        User::destroy($ids);
        return response()->noContent();
    }

    public function show(Request $request): View
    {
        $user = $request->user();
        return view('backend.profile.show', compact('user'));
    }
}
