<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Services\ApiService;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController 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 {
            // Login ke API terlebih dahulu
            // Format URL yang benar adalah https://api.tailors.stuffly.my.id/api/admin/login
            $response = $this->apiService->post('admin/login', [
                'email' => $credentials['email'],
                'password' => $credentials['password'],
            ]);

            \Log::info('API Login Response', [
                'status' => $response->status(),
                'body' => $response->json()
            ]);

            if ($response->successful()) {
                $data = $response->json();
                
                if ($data['success'] && isset($data['data']['access_token'])) {
                    // Simpan token dan token type di session
                    session([
                        'api_token' => $data['data']['access_token'],
                        'token_type' => $data['data']['token_type'],
                        'user_data' => $data['data']['user']
                    ]);

                    // Coba cari user di database, atau login dengan user yang sudah ada
                    // tanpa membuat user baru (karena kolom sudah ditambahkan di migrasi)
                    $user = User::where('email', $credentials['email'])->first();
                    
                    if ($user) {
                        // Update data user jika ada
                        $apiUser = $data['data']['user'];
                        $user->update([
                            'name' => $apiUser['name'],
                            'role' => $apiUser['role'] ?? null,
                            'phone_number' => $apiUser['phone_number'] ?? null,
                            'address' => $apiUser['address'] ?? null,
                        ]);
                    } else {
                        // Buat user baru jika belum ada
                        $apiUser = $data['data']['user'];
                        $user = User::create([
                            'name' => $apiUser['name'],
                            'email' => $apiUser['email'],
                            'password' => Hash::make($credentials['password']),
                            'role' => $apiUser['role'] ?? null,
                            'phone_number' => $apiUser['phone_number'] ?? null,
                            'address' => $apiUser['address'] ?? null,
                        ]);
                    }
                    
                    // Login ke aplikasi web dengan user yang ada
                    Auth::login($user);
                        $request->session()->regenerate();
                    
                    // Redirect ke dashboard
                        return redirect()->intended(route('admin.dashboard'));
                }
            }

            // Jika gagal, tampilkan pesan error dari API
            $errorMessage = 'Email atau password salah.';
            if ($response->json() && isset($response->json()['message'])) {
                $errorMessage = $response->json()['message'];
            }

            return back()->withErrors([
                'email' => $errorMessage,
            ])->onlyInput('email');

        } catch (\Exception $e) {
            \Log::error('Login Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return back()->withErrors([
                'email' => 'Terjadi kesalahan saat menghubungi server. Silakan coba lagi: ' . $e->getMessage(),
            ])->onlyInput('email');
        }
    }

    public function logout(Request $request)
    {
        try {
            // Logout dari API
            $this->apiService->post('admin/logout');
        } catch (\Exception $e) {
            \Log::error('API Logout Error:', ['message' => $e->getMessage()]);
        }

        // Hapus token dari session
        session()->forget(['api_token', 'token_type', 'user_data']);
        
        // Logout dari aplikasi web
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect()->route('admin.login');
    }
} 