<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\PromoCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Password;
use App\Models\UserSession;
use Carbon\Carbon;

class UserController extends Controller
{
    public function showRegistrationForm()
    {
        return view('signup');
    }

    public function register(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Password::defaults()],
            'promo_code' => ['required', 'string', 'max:255'],
            'date_of_birth' => ['required', 'date'],
            'phone_number' => ['required', 'string', 'max:20'],
        ]);

        // Check if promo code exists
        $promoCode = PromoCode::where('code', $request->promo_code)->first();
        if (!$promoCode) {
            return back()->withErrors([
                'promo_code' => 'Invalid promo code. Please enter a valid promo code.'
            ])->withInput();
        }

        try {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'promo_code' => $request->promo_code,
                'date_of_birth' => $request->date_of_birth,
                'phone_number' => $request->phone_number,
                'currency' => 'USD',
                'balance' => 0,
                'leverage' => 100,
                'credit' => 0,
                'margin' => 0,
                'free_margin' => 0,
                'margin_level' => 0,
            ]);

            // Update the login field with 10000 + user_id
            $user->login = 10000 + $user->id;
            $user->save();

            auth()->login($user);

            return redirect('/')->with('success', 'Registration successful!');
        } catch (\Exception $e) {
            \Log::error('Registration error: ' . $e->getMessage());
            return back()->withErrors([
                'general' => 'An error occurred during registration. Please try again.'
            ])->withInput();
        }
    }

    public function showLoginForm()
    {
        return view('login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        try {
            if (Auth::attempt($credentials, $request->remember)) {
                $user = Auth::user();
                
                // Check if user has admin or manager role
                if (!$user->hasRole('admin') && !$user->hasRole('manager')) {
                    // Log out the user if they don't have the required role
                    Auth::logout();
                    $request->session()->invalidate();
                    $request->session()->regenerateToken();
                    
                    return back()->withErrors([
                        'email' => 'Access denied.',
                    ])->onlyInput('email');
                }
                
                $request->session()->regenerate();
                
                // Record session with UTC timezone in a try-catch block
                try {
                    UserSession::create([
                        'user_id' => Auth::id(),
                        'login_at' => Carbon::now('UTC'),
                        'ip_address' => $request->ip(),
                        'user_agent' => $request->header('User-Agent'),
                    ]);
                } catch (\Exception $e) {
                    // Log the error but don't prevent login
                    \Log::error('Failed to record user session: ' . $e->getMessage());
                }
                
                // Redirect to admin dashboard
                return redirect()->route('admin.dashboard')->with('success', 'Login successful!');
            }
        } catch (\Exception $e) {
            \Log::error('Login error: ' . $e->getMessage());
            return back()->withErrors([
                'email' => 'An error occurred during login. Please try again.',
            ])->onlyInput('email');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        if (Auth::check()) {
            $session = UserSession::where('user_id', Auth::id())
                ->whereNull('logout_at')
                ->orderByDesc('login_at')
                ->first();
            if ($session) {
                $session->logout_at = Carbon::now('UTC');
                $session->save();
            }
        }
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/')->with('success', 'Logged out successfully!');
    }
} 