<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use App\Models\User; 
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Exception\RequestException;

class AdminAuthController extends Controller
{
    public function showLoginForm()
    {
      return view('awa.auth.login'); 
    }

   
   
    public function login(Request $request)
    {
        $request->validate([
            'name'     => 'required|string',
            'email'    => 'required|email',
            'password' => 'required',
        ]);
    
        // 1) Try admin API
        try {
            $client = new Client([
                'base_uri' => config('services.admin_api.base_url'),
                'timeout'  => 5,
            ]);
    
            $response = $client->post('/login_admin', [
                'form_params' => [
                   'name'     => $request->name,
                    'email'    => $request->email,
                    'password' => $request->password,
                ],
            ]);
    
            $body = json_decode((string)$response->getBody(), true);
    
            if (! empty($body['token']) && ($body['status'] ?? 1) === 0) {
               
                Session::put('admin_token',    $body['token']);
                Session::put('admin_name',     $request->name);
                Session::put('admin_email',    $request->email);
                Session::put('admin_password', $request->password);
    
                User::updateOrCreate(
                    ['email' => $request->email],
                    [
                        'name'     => $request->name,
                        'password' => Hash::make($request->password),
                        'role'     => 'admin',
                    ]
                );
    
                return redirect()->route('admin.dashboard');
            }
            // if API returned status ≠ 0, fall through to user‐fallback
        }
        catch (RequestException $e) {
            // if it's a 401/403, that just means "not an admin"—swallow it
            if ($e->hasResponse()
                && in_array($e->getResponse()->getStatusCode(), [401,403], true)
            ) {
                // do nothing, let user‐fallback run
            } else {
               return back()
                    ->withInput($request->only('email'))
                    ->with('error', 'Login service unavailable, please try later.');
            }
        }
    
        // 2) Normal‐user fallback
        if (Auth::attempt([
               'name'    => $request->name,
                'email'    => $request->email,
                'password' => $request->password,
                'role'     => 'user',    // optional: lock out any admin records here
            ])) {
            $request->session()->regenerate();
            Session::put('user_name',  Auth::user()->name);
            Session::put('user_email', Auth::user()->email);
            return redirect()->route('admin.dashboard');
        }
    
        // 3) Neither admin nor user succeeded
        return back()
            ->withInput($request->only('email'))
            ->with('error', 'Invalid credentials, please try again.');
    }




  public function logout()
{
    if (Session::has('admin_token')) { 
  Session::forget(['admin_token','admin_email','admin_name','admin_password']);
    }

    if (Auth::check()) {
        Auth::logout();
       
        Session::forget([
            'user_name',
            'user_email',
           'user_password'
        ]);
    }



  return redirect()->route('login.form');

}



public function showProfileForm()
{
    return view('awa.pages.update-profile', [
        'name'       => Session::get('admin_name', ''),
        'email'      => Session::get('admin_email', ''),
        'avatar_url' => Session::get('admin_avatar_url', null),
    ]);
}



public function updateProfile(Request $request)
{
    $data = $request->validate([
        'name'        => 'required|string|max:255',
        'email'       => 'required|email',
        'password'    => 'nullable|string',
        'profile_pic' => 'nullable|file|image|max:2048',
    ]);

    $client = new Client([
        'base_uri' => config('services.admin_api.base_url'),
        'timeout'  => 5,
    ]);

    // 1) Build the multipart array
    $multipart = [
        ['name' => 'name',     'contents' => $data['name']],
        ['name' => 'email',    'contents' => $data['email']],
        ['name' => 'password', 'contents' => $data['password'] ?: Session::get('admin_password')],
    ];

    // 2) If a file was uploaded, attach it here
    if ($request->hasFile('profile_pic')) {
        $file     = $request->file('profile_pic');
        $multipart[] = [
            'name'     => 'profile_pic',
            'contents' => fopen($file->getRealPath(), 'r'),
            'filename' => $file->getClientOriginalName(),
        ];
    }

    try {
        // 3) Send everything in one request
        $res  = $client->post('/update_profile_admin', [
            'multipart' => $multipart,
        ]);
        $body = json_decode((string)$res->getBody(), true);

        if (($body['status'] ?? 1) === 0) {
            // update the name/email in session
            Session::put('admin_name',  $data['name']);
            Session::put('admin_email', $data['email']);

           

            // 4) now if you want to keep a local copy of the avatar:
                $localAvatarUrl = null;
                if ($request->hasFile('profile_pic')) {
                    $filename    = 'avatar_'.time().'.'.$file->getClientOriginalExtension();
                    $dest        = public_path('avatars');
                    if (!is_dir($dest)) mkdir($dest, 0755, true);
                    $file->move($dest, $filename);
                    $localAvatarUrl = asset("avatars/{$filename}");
                    Session::put('admin_avatar_url', $localAvatarUrl);
                }

                User::updateOrCreate(
                    ['email' => $data['email']],
                    [
                      'name'       => $data['name'],
                      'password'   => Hash::make($data['password'] ?: Session::get('admin_password')),
                      'role'       => 'admin',
                      'avatar_url' => $localAvatarUrl,  
                    ]
                );

            return redirect()
                ->route('admin.profile.edit')
                ->with('success','Profile updated successfully.');
        }

        return back()
            ->withErrors(['form' => $body['message'] ?? 'Update failed.'])
            ->withInput();

    } catch (\Exception $e) {
        return back()
            ->withErrors(['form' => 'Service unavailable.'])
            ->withInput();
    }
}


}
