<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Libraries\LoginAttempt;

class AuthController extends BaseController
{
    protected $userModel;
    protected $loginAttempt;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->loginAttempt = new LoginAttempt();
    }

    /**
     * Display login form
     */
    public function login()
    {
        // If already logged in, redirect to dashboard
        if (session()->get('isLoggedIn')) {
            return redirect()->to('/admin');
        }

        $data = [
            'title' => 'Admin Login',
        ];

        return view('admin/login', $data);
    }

    /**
     * Process login
     */
    public function attemptLogin()
    {
        // Check if locked out
        if ($this->loginAttempt->isLocked()) {
            $remaining = $this->loginAttempt->getFormattedRemainingTime();
            return redirect()->back()
                ->with('error', "Terlalu banyak percobaan login. Coba lagi dalam {$remaining}.");
        }

        // Validate input
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required|min_length[6]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Email dan password harus diisi dengan benar.');
        }

        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        // Find user
        $user = $this->userModel->findByEmail($email);

        if (!$user || !$this->userModel->verifyPassword($password, $user['password_hash'])) {
            // Record failed attempt
            $this->loginAttempt->recordFailedAttempt();
            
            $remaining = $this->loginAttempt->getRemainingAttempts();
            $message = "Email atau password salah.";
            
            if ($remaining > 0) {
                $message .= " Sisa percobaan: {$remaining}";
            }

            return redirect()->back()
                ->withInput()
                ->with('error', $message);
        }

        // Successful login - reset attempts
        $this->loginAttempt->reset();

        // Regenerate session ID for security
        session()->regenerate();

        // Set session data
        session()->set([
            'user_id'       => $user['id'],
            'user_name'     => $user['name'],
            'user_email'    => $user['email'],
            'user_role'     => $user['role'],
            'isLoggedIn'    => true,
            'last_activity' => time(),
        ]);

        // Update last login
        $this->userModel->updateLastLogin($user['id']);

        // Redirect to intended URL or dashboard
        $redirectUrl = session()->get('redirect_url') ?? '/admin';
        session()->remove('redirect_url');

        return redirect()->to($redirectUrl)
            ->with('success', 'Selamat datang, ' . $user['name'] . '!');
    }

    /**
     * Logout
     */
    public function logout()
    {
        session()->destroy();
        return redirect()->to('/admin/login')
            ->with('success', 'Anda telah berhasil logout.');
    }
}
