<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Hash;
use App\Models\Admin;

class AuthController extends Controller
{
    public function showLogin()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        $admin = Admin::where('email', $credentials['email'])->first();

        if ($admin && Hash::check($credentials['password'], $admin->password)) {
            Session::put('admin_logged_in', true);
            Session::put('admin_id', $admin->id);
            return Redirect::route('admin.dashboard');
        }

        return back()->withErrors(['email' => 'The credentials do not match our records.']);
    }

    public function logout(Request $request)
    {
        Session::forget('admin_logged_in');
        Session::forget('admin_id');
        return redirect()->route('admin.login');
    }

    public function showChangePassword()
    {
        return view('admin.change-password');
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

        $admin = Admin::find(Session::get('admin_id'));
        
        if (!$admin) {
             // Fallback for admins logged in before this change
             $admin = Admin::first();
             if ($admin) Session::put('admin_id', $admin->id);
        }

        if (!$admin || !Hash::check($request->current_password, $admin->password)) {
            return back()->withErrors(['current_password' => 'Current password is incorrect.']);
        }

        $admin->password = Hash::make($request->new_password);
        $admin->save();

        return redirect()->route('admin.dashboard')->with('success', 'Password changed successfully!');
    }
}
