<?php

namespace App\Modules\Admin\Controllers;

use CodeIgniter\Controller; // ← Important: Don't inherit frontend logic

class AuthController extends Controller
{
    public function login()
    {
        if (session()->has('admin_id')) {
            return redirect()->to('/admin/dashboard');
        }
        return view('App\Modules\Admin\Views\auth\login');
    }

    public function authenticate()
    {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $adminModel = model('App\Modules\Admin\Models\AdminModel'); // Use model() helper

        $admin = $adminModel->where('email', $email)->first();

        if ($admin && password_verify($password, $admin['password_hash'])) {
            session()->set([
                'admin_id' => $admin['id'],
                'admin_email' => $admin['email']
            ]);
            return redirect()->to('/admin/dashboard')->with('success', 'Logged in successfully.');
        }

        return redirect()->back()->with('error', 'Invalid email or password.');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/admin/login')->with('info', 'Logged out.');
    }
}