<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

use App\Models\User;


class AuthController extends Controller
{
    public function showLoginForm() {
        // If the user is already logged in, redirect them to the dashboard
        if (session()->has('user_id')) {
            return redirect()->route('dashboard');
        }
    
        return view('login');
    }

    public function login(Request $request)
    {
        // var_dump($request);
        // Validate the incoming data
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // Capture the credentials from the form
        $username = $request->username;
        $password = $request->password;

        // Basic Authentication credentials for the external API
        $apiUser = 'geeth';
        $apiPass = 'abc123';

        // Build the URL dynamically with the username and password as URL parameters
        $url = "http://94.156.189.111:8080/XCore/API/um/access/{$username}/{$password}";

        // Send the GET request with Basic Authentication and URL parameters
        $response = Http::withBasicAuth($apiUser, $apiPass)
                        ->get($url);


        // Check if the response is valid and successful
        if ($response->successful()) {
            // Save the data from the response to the session
            $data = $response->json();

            if(empty($data)){
                return back()->withErrors(['error' => 'Invalid credentials..!']);
            }

            /*
            Session::put('person', $data['person']);
            Session::put('domain', $data['domain']);
            Session::put('name', $data['name']);
            Session::put('employee', $data['employee']);
            Session::put('login', $data['login']);
            Session::put('rolls', $data['rolls']);
            Session::put('customer', $data['customer']);

            // Redirect to the dashboard or home page after successful login
            return redirect()->route('dashboard');
        }

        // Handle error, show login with message
        return back()->withErrors(['error' => 'Invalid credentials']);
    }*/
        // Get client details
        $clientIp = $request->ip();
        $userAgent = $request->userAgent();
        $machineName = gethostbyaddr($clientIp); // Optional - frontend can pass it too
        $now = now();

        // Try to find existing user
        $user = User::where('login', $data['login'])->first();

        if ($user) {
            $user->update([
                'person'         => $data['person'],
                'domain'         => $data['domain'],
                'name'           => $data['name'],
                'employee'       => $data['employee'],
                'rolls'          => $data['rolls'],
                'customer'       => $data['customer'],
                'last_login_at'  => $user->login_at,
                'login_at'       => $now,
                'failed_attempts'=> 0,
                'ip_address'     => $clientIp,
                'user_agent'     => $userAgent,
                'machine_name'   => $machineName,
            ]);
        } else {
            $user = User::create([
                'login'          => $data['login'],
                'name'           => $data['name'], // also fills default 'name' column
                'email'          => $data['login'].'@example.com', // fake if backend doesn't return email
                'password'       => Hash::make($password), // random password
                'person'         => $data['person'],
                'domain'         => $data['domain'],
                'employee'       => $data['employee'],
                'rolls'          => $data['rolls'],
                'customer'       => $data['customer'],
                'login_at'       => $now,
                'ip_address'     => $clientIp,
                'user_agent'     => $userAgent,
                'machine_name'   => $machineName,
            ]);
        }

        // Login the user using Laravel Auth
        Auth::login($user);

        // Save some data to session (if needed)
        Session::put('user_id', $user->id);
        Session::put('login', $user->login);

        // Redirect to dashboard
        return redirect()->route('dashboard');
    }

    // If login failed, increment failed_attempts
    $user = User::where('login', $request->input('username'))->first();
    if ($user) {
        $user->increment('failed_attempts');
    }

    return back()->withErrors(['error' => 'Invalid credentials']);
}

    public function logout()
    {
        // Clear session data when logging out
        Session::flush();
        
        return redirect()->route('login');
    }
}