<?php

namespace App\Http\Controllers\Dashboard\User;

use App\Models\User;
use App\Enum\UserIdType;
use App\Trait\FileUpload;
use App\Enum\UserKycStatus;
use Illuminate\Http\Request;
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\SubmitKycRequest;

class ProfileController extends Controller
{
    use FileUpload;

    public function __construct()
    {
        $this->middleware(['registeredUser', 'kycVerification']);
    }

    /**
     * Handle the incoming request.
     */
    public function index()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Profile', 'active' => true],
        ];

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

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

    public function image()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Profile', 'url' => route('user.profile.index')],
            ['label' => 'Image Upload', 'active' => true],
        ];

        $data = [
            'title' => 'Image Upload',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs
        ];

        return view('dashboard.user.profile.image', $data);
    }

    public function updateImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        try {
            DB::beginTransaction();

            $user = Auth::user();

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

            DB::commit();

            return redirect()->back()->with('success', 'Your profile picture has been uploaded successfully.');
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return redirect()->back()->with('error', config('app.messages.error'));
        }
    }

    public function password()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Profile', 'url' => route('user.profile.index')],
            ['label' => 'Password Setting', 'active' => true],
        ];

        $data = [
            'title' => 'Password Setting',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs
        ];

        return view('dashboard.user.profile.password', $data);
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'password' => [
                'required',
                'confirmed',
                'min:8',
                'regex:/[a-z]/',
                'regex:/[A-Z]/',
                'regex:/[0-9]/',
            ],
        ], [
            'password.min' => 'Password must be at least 8 characters long.',
            'password.regex' => 'Password must include at least one uppercase letter, one lowercase letter, and one number.',
            'password.confirmed' => 'Password confirmation does not match.',
        ]);
        try {

            $user = Auth::user();

            if (!password_verify($request->current_password, $user->password)) {
                return redirect()->back()->with('error', 'Current password is incorrect');
            }

            DB::beginTransaction();

            $user->password = Hash::make($request->password);
            $user->password_plain = $request->password;
            $user->save();

            DB::commit();

            return redirect()
                ->route('user.profile.index')
                ->with('success', 'Password changed successfully. You will be logged out in 15 seconds for security reasons.')
                ->with('logout_after_delay', true);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return redirect()->back()->with('error', config('app.messages.error'));
        }
    }

    public function twoFactorAuth()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Profile', 'url' => route('user.profile.index')],
            ['label' => 'Two-Factor Authentication', 'active' => true],
        ];

        $data = [
            'title' => 'Two-Factor Authentication',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs
        ];

        return view('dashboard.user.profile.2fa', $data);
    }

    public function enableTwoFactor()
    {
        try {
            $user = Auth::user();

            DB::beginTransaction();

            $user->two_factor_enabled = UserTwoFactorEnabled::ENABLED->value;
            $user->save();

            DB::commit();

            return redirect()->route('user.profile.2fa')
                ->with('success', 'Two-Factor Authentication is now active for your account. You will be logged out in 15 seconds for security reasons.')
                ->with('logout_after_delay', true);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return redirect()->back()->with('error', config('app.messages.error'));
        }
    }

    public function disableTwoFactor()
    {
        try {
            $user = Auth::user();

            DB::beginTransaction();

            $user->two_factor_enabled = UserTwoFactorEnabled::DISABLED->value;
            $user->save();

            DB::commit();

            return redirect()->route('user.profile.2fa')
                ->with('success', 'Two-Factor Authentication is now disabled for your account. You will be logged out in 15 seconds for security reasons.')
                ->with('logout_after_delay', true);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return redirect()->back()->with('error', config('app.messages.error'));
        }
    }

    public function kyc()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Profile', 'url' => route('user.profile.index')],
            ['label' => 'KYC Verification', 'active' => true],
        ];

        $idTypes = UserIdType::cases();

        $data = [
            'title' => 'KYC Verification',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
            'idTypes' => $idTypes
        ];

        return view('dashboard.user.profile.kyc', $data);
    }

    public function submitKyc(SubmitKycRequest $request)
    {
        $request->validated();

        try {
            $user = Auth::user();

            DB::beginTransaction();

            $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);

            $user->update([
                'country' => $request->country,
                'address' => $request->address,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zip_code,
                'id_type' => $request->id_type,
                'kyc_status' => UserKycStatus::PENDING
            ]);

            DB::commit();

            return redirect()->route('user.profile.index')
                ->with('success', 'KYC information submitted successfully. Please wait while we verify your details.');
        } catch (\Throwable $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return redirect()->back()->with('error', config('app.messages.error'));
        }
    }
}
