<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class AuthController extends Controller
{
    protected $apiBaseUrl = 'http://192.168.100.6:8081/api';

    /**
     * Show the login form
     */
    public function showLoginForm()
    {
        return view('login');
    }

    /**
     * Handle login form submission by calling the API
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        try {
            $response = Http::post(config('services.backend_api.url') . '/api/cms/login_password', [
                'username' => $request->username,
                'password' => $request->password,
            ]);

            $json = $response->json();

            Log::info('Login API Response: ', $json);

            if ($response->successful()) {
                if ($json['code'] == 200) {
                    $userData = [
                        'admin' => $json['data']['admin'] ?? null,
                        'access_token' => $json['data']['token'] ?? null,
                        'admin_uuid' => $json['data']['admin']['uuid'] ?? null,
                    ];
                    Session::put('user', $userData);
                    Session::save();

                    Log::info('Session data after login: ', Session::get('user'));

                    // Redirect to my-profile if access_token is present
                    if (isset($userData['access_token']) && !empty($userData['access_token'])) {
                        Log::info('Access token present, redirecting to my-profile from login');
                        return redirect()->route('my-profile');
                    }

                    $isPasswordChanged = $json['data']['admin']['is_passwordChanged'] ?? 0;
                    Log::info('Login: is_passwordChanged from API = ' . $isPasswordChanged);

                    if ($isPasswordChanged == 1) {
                        Log::info('Redirecting to my-profile from login');
                        return redirect()->route('my-profile');
                    } else {
                        Log::info('Redirecting to change-password from login');
                        return redirect()->route('change-password')->with('info', 'You must change your password before accessing your profile.');
                    }
                } else {
                    return back()->withErrors(['username' => $json['message'] ?? 'Login failed.']);
                }
            } else {
                return back()->withErrors(['username' => $json['message'] ?? 'Login request failed.']);
            }
        } catch (\Exception $e) {
            Log::error('Login error: ' . $e->getMessage());
            return back()->withErrors(['username' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    /**
     * Show the my-profile page
     */
    public function showMyProfile()
    {
        $user = Session::get('user');

        if (!$user || !isset($user['access_token'])) {
            Log::info('No user session or access token, redirecting to login from my-profile');
            return redirect()->route('login')->with('error', 'Please log in to view your profile.');
        }

        if (!isset($user['admin']) || !is_array($user['admin'])) {
            Log::error('Invalid admin data in session: ', $user);
            return redirect()->route('login')->with('error', 'Invalid user data. Please log in again.');
        }

        Log::info('Session data in my-profile: ', $user);
        Log::info('Rendering my-profile page');
        return view('pages.my-profile', compact('user'));
    }

    /**
     * Show the change password form
     */
    public function showChangePasswordForm()
    {
        if (!session()->has('user.admin_uuid')) {
            Log::info('No admin_uuid in session, redirecting to login from change-password form');
            return redirect()->route('login')->withErrors(['error' => 'Unauthorized access']);
        }

        Log::info('Rendering change-password form');
        return view('change-password');
    }

    /**
     * Handle change password form submission by calling the API
     */
    public function changePassword(Request $request)
    {
        $request->validate([
            'admin_uuid' => 'required|string',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $url = "{$this->apiBaseUrl}/cms/login_changePassword";
        $csrfToken = $request->session()->token();

        try {
            $response = Http::withHeaders([
                'X-CSRF-TOKEN' => $csrfToken,
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . session('user.access_token'),
            ])->post($url, [
                'admin_uuid' => $request->input('admin_uuid'),
                'password' => $request->input('password'),
            ]);

            $data = $response->json();

            Log::info('Change Password API Response: ', $data);

            if ($response->successful() && isset($data['code']) && $data['code'] === 200) {
                $user = Session::get('user');

                // Update access token from API response
                if (isset($data['token'])) {
                    $user['access_token'] = $data['token'];
                } elseif (isset($data['data']['access_token'])) {
                    $user['access_token'] = $data['data']['access_token'];
                }

                // Update admin data with the latest from API
                if (isset($data['admin'])) {
                    $user['admin'] = $data['admin'];
                }

                Session::put('user', $user);
                Session::save();

                Log::info('Updated Session after password change: ', Session::get('user'));
                Log::info('Redirecting to my-profile from changePassword');

                // Immediately redirect to my-profile
                return redirect()->route('my-profile')->with('success', $data['message'] ?? 'Password changed successfully');
            }

            Log::info('Change password failed, redirecting back');
            return redirect()->back()->withErrors(['error' => $data['message'] ?? 'Failed to change password']);
        } catch (\Exception $e) {
            Log::error('Change Password Exception: ' . $e->getMessage());
            return redirect()->back()->withErrors(['error' => 'Password change request failed: ' . $e->getMessage()]);
        }
    }

    /**
     * Handle logout by calling the API
     */
    public function logout(Request $request)
    {
        $url = "{$this->apiBaseUrl}/logout_cms";
        $csrfToken = $request->session()->token();

        try {
            Http::withHeaders([
                'X-CSRF-TOKEN' => $csrfToken,
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . session('user.access_token'),
            ])->post($url);

            session()->flush();
            Log::info('Logged out, redirecting to login');
            return redirect()->route('login')->with('success', 'Logged out successfully');
        } catch (\Exception $e) {
            Log::error('Logout Exception: ' . $e->getMessage());
            session()->flush();
            return redirect()->route('login')->with('success', 'Logged out successfully');
        }
    }
}