<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Services\ApiService;

class LoginController extends Controller
{
    /**
     * API Service
     *
     * @var ApiService
     */
    protected $apiService;

    /**
     * Constructor
     *
     * @param ApiService $apiService
     */
    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }

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

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        try {
            // Call API for authentication without using the default authorization
            $response = $this->apiService->http()->post($this->apiService->url('api/admin/login'), [
                'email' => $credentials['email'],
                'password' => $credentials['password'],
            ]);
            
            $data = $response->json();
            
            // Log the response for debugging
            Log::info('API Login Response', [
                'status' => $response->status(),
                'body' => $data
            ]);
            
            if ($response->successful() && isset($data['success']) && $data['success']) {
                // Store user information and tokens in session
                $request->session()->put('api_token', $data['data']['access_token']);
                $request->session()->put('token_type', $data['data']['token_type']);
                $request->session()->put('user', $data['data']['user']);
                
                // Return JSON response if requested
                if ($request->expectsJson()) {
                    return response()->json($data);
                }
                
                // Redirect to dashboard
                return redirect()->route('admin.dashboard');
            }
            
            // Return JSON error if requested
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $data['message'] ?? 'Authentication failed'
                ], 401);
            }
            
            // Default error message
            return back()->withErrors([
                'email' => $data['message'] ?? 'The provided credentials do not match our records.',
            ]);
            
        } catch (\Exception $e) {
            Log::error('Login Error', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            // Return JSON error if requested
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'An error occurred during login. Please try again.'
                ], 500);
            }
            
            return back()->withErrors([
                'email' => 'An error occurred during login. Please try again.'
            ]);
        }
    }

    public function logout(Request $request)
    {
        $request->session()->forget(['api_token', 'token_type', 'user']);
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect()->route('admin.login');
    }
} 