<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Models\User;
use App\Enum\Currency;
use App\Enum\UserRole;
use App\Enum\UserIdType;
use App\Trait\FileUpload;
use Illuminate\Http\Request;
use App\Enum\UserAccountMode;
use App\Enum\UserAccountType;
use App\Enum\UserTradingPlatform;
use App\Enum\UserTwoFactorEnabled;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\AdminUpdateUserRequest;

class UserController extends Controller
{
    use FileUpload;

    public function index()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'active' => true]
        ];

        $users = User::where('role', UserRole::USER->value)->latest()->get();

        $data = [
            'title' => 'Users',
            'users' => $users,
            'breadcrumbs' => $breadcrumbs
        ];

        return view('dashboard.admin.user.index', $data);
    }

    public function create()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'Create User', 'active' => true]
        ];

        $data = [
            'title' => 'Create User',
            'breadcrumbs' => $breadcrumbs,
        ];

        return view('dashboard.admin.user.create', $data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'phone' => 'nullable|string|max:255',
            'gender' => 'nullable|string|max:255',
            'country' => 'required|string|max:255',
            'password' => 'required|confirmed',
        ]);

        try {
            $data = [
                'name' => $request->name,
                'email' => $request->email,
                'email_verified_at' => now(),
                'email_code' => null,
                'email_code_expires_at' => null,
                'phone' => $request->phone,
                'gender' => $request->gender,
                'country' => $request->country,
                'password' => $request->password,
                'password_plain' => $request->password,
                'api_key' => generateApiKey(),
                'secret_key' => generateSecretKey(),
            ];
            DB::transaction(function () use ($data) {
                User::create($data);
            });

            return redirect()->route('admin.user.index')->with('success', 'User created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return redirect()->back()->with('error', 'Unable to create user.');
        }
    }

    public function show(string $uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'User Details', 'active' => true]
        ];

        $user = User::where('uuid', $uuid)->first();

        $data = [
            'title' => 'User Details',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
        ];

        return view('dashboard.admin.user.show', $data);
    }

    public function edit(string $uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'User Details', 'url' => route('admin.user.show', $uuid)],
            ['label' => 'Edit User', 'active' => true]
        ];

        $user = User::where('uuid', $uuid)->first();

        $accountTypes = UserAccountType::cases();
        $currencies = Currency::cases();
        $idTypes = UserIdType::cases();
        $twoFactorAuthStatuses = UserTwoFactorEnabled::cases();
        $accountModes = UserAccountMode::cases();

        $data = [
            'title' => 'Edit User',
            'user' => $user,
            'accountTypes' => $accountTypes,
            'currencies' => $currencies,
            'idTypes' => $idTypes,
            'breadcrumbs' => $breadcrumbs,
            'twoFactorAuthStatuses' => $twoFactorAuthStatuses,
            'accountModes' => $accountModes
        ];

        return view('dashboard.admin.user.edit', $data);
    }

    public function update(AdminUpdateUserRequest $request, string $uuid)
    {
        try {
            $user = User::where('uuid', $uuid)->firstOrFail();

            $user->image = $this->imageInterventionUpdateFile($request, 'image', uploadPathUser('image'), 400, 400, $user?->image);

            $user->id_front = $this->updateFile($request, 'id_front', uploadPathUser('id'), $user?->id_front);

            $user->id_back = $this->updateFile($request, 'id_back', uploadPathUser('id'), $user?->id_back);

            DB::beginTransaction();

            $data = [
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'gender' => $request->gender,
                'account_type' => $request->account_type,
                'account_mode' => $request->account_mode,
                'currency' => $request->currency,
                'two_factor_enabled' => $request->two_factor_enabled,
                'signal_strength' => $request->signal_strength,
                'country' => $request->country,
                'address' => $request->address,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zip_code,
                'id_type' => $request->id_type,
            ];

            if ($request->password) {
                $data['password'] = Hash::make($request->password);
                $data['password_plain'] = $request->password;
            }

            $user->update($data);

            DB::commit();

            return redirect()->route('admin.user.show', $uuid)->with('success', 'User has been updated successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return redirect()->route('admin.user.show', $uuid)->with('error', config('app.messages.error'));
        }
    }

    public function login(string $uuid)
    {
        try {
            $user = User::where('uuid', $uuid)->firstOrFail();

            Auth::login($user);

            return redirect()->route('user.dashboard')->with('success', 'User logged in successfully.');
        } catch (\Throwable $e) {
            Log::error($e->getMessage());
            return redirect()->route('admin.user.index')->with('error', 'Unable to login user.');
        }
    }

    public function delete(string $uuid)
    {
        try {
            DB::beginTransaction();

            $user = User::where('uuid', $uuid)->firstOrFail();

            $this->deleteFile($user->image);
            $this->deleteFile($user->id_front);
            $this->deleteFile($user->id_back);

            foreach ($user->transaction as $transaction) {
                $this->deleteFile($transaction->proof);
            }

            $this->deleteFile($user->premiumSignalSubscription?->proof);

            $this->deleteFile($user->trader?->image);

            $user->delete();

            DB::commit();
            return redirect()->route('admin.user.index')->with('success', 'User has been deleted successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return redirect()->route('admin.user.index')->with('error', config('app.messages.error'));
        }
    }
}
