<?php
namespace App\Http\Controllers;

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

class ChangePasswordController extends Controller
{
    protected $apiBaseUrl;

    public function __construct()
    {
        $this->apiBaseUrl = env('API_BASE_URL', 'http://your-backend-api-url');
    }

    public function showChangePasswordForm()
    {
        return view('change-password');
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'password' => 'required|min:8|confirmed',
        ]);

        $adminId = Session::get('admin_id');
        $apiToken = Session::get('api_token');

        if (!$adminId || !$apiToken) {
            return redirect()->route('login')->with('error', 'You must be logged in to change your password');
        }

        $response = Http::withToken($apiToken)
            ->get("{$this->apiBaseUrl}/api/admin/{$adminId}");

        if ($response->failed()) {
            return redirect()->back()->with('error', 'Unable to fetch admin data. Please try again later.');
        }

        $admin = $response->json();

        if (!$admin) {
            return redirect()->route('login')->with('error', 'Admin not found');
        }

        $updateResponse = Http::withToken($apiToken)
            ->put("{$this->apiBaseUrl}/api/admin/{$adminId}", [
                'password' => bcrypt($request->password),
                'is_passwordChanged' => 1,
            ]);

        if ($updateResponse->failed()) {
            return redirect()->back()->with('error', 'Failed to update password. Please try again.');
        }

        return redirect()->route('my-profile')->with('success', 'Password updated successfully');
    }

    // Method to fetch and display admin profile data
    public function showProfile()
    {
        $adminId = Session::get('admin_id');
        $apiToken = Session::get('api_token');

        if (!$adminId || !$apiToken) {
            return redirect()->route('login')->with('error', 'You must be logged in to view your profile');
        }

        $response = Http::withToken($apiToken)
            ->get("{$this->apiBaseUrl}/api/admin/{$adminId}");

        if ($response->failed()) {
            return redirect()->back()->with('error', 'Unable to fetch profile data. Please try again later.');
        }

        $admin = $response->json();

        if (!$admin) {
            return redirect()->route('login')->with('error', 'Admin not found');
        }

        return view('my-profile', ['admin' => $admin]);
    }
}