<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Libraries\Validation;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class AuthenticationController extends Controller
{
    public function index()
    {
        if (Auth::check()) {
            return redirect('admin/projects');
        }
        return view('admin.authentication.login',['page_title' => 'Wellcome to Login Page']);
    }

    public function login(Request $request)
    {
    	try {
    		$payload = $request->all();
    		$result = Validation::validatePayload($request->all(), ['username' => 'required','password' => 'required']);

    		if($result['status']){
    			$payload['role'] = 'admin';
    			if (Auth::attempt($payload)) {
    				return response()->json(['status' => true]);
    			}
    			return response()->json(['status' => false,'message' => 'Invalid credentials.']);
    		}
    		return response()->json($result);
    	} catch (\Exception $e) {
    		Log::error('Admin login error: ' . $e->getMessage());
    		return response()->json(['status' => false, 'message' => 'Login failed. Please try again.']);
    	}
    }

    public function logout()
    {
    	Auth::logout();
    	return redirect('admin/login');
    }
}
