<?php

namespace App\Controllers\Auth;

use App\Controllers\BaseController;
use App\Models\AdminModel;

/**
 * LoginController — handles admin authentication.
 */
class LoginController extends BaseController
{
    private AdminModel $adminModel;

    public function __construct()
    {
        $this->adminModel = new AdminModel();
    }

    // ----------------------------------------------------------------
    // GET /login
    // ----------------------------------------------------------------
    public function index(): string
    {
        if (session()->get('admin_logged_in')) {
            return redirect()->to(site_url('admin/dashboard'))->send() ?: '';
        }
        return view('auth/login', ['title' => lang('Admin.login_title')]);
    }

    // ----------------------------------------------------------------
    // POST /login
    // ----------------------------------------------------------------
    public function attempt()
    {
        // Validate
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required|min_length[6]',
        ];
        if (! $this->validate($rules)) {
            return redirect()->back()
                             ->withInput()
                             ->with('errors', $this->validator->getErrors());
        }

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

        $admin = $this->adminModel->findByEmail($email);

        if (! $admin || ! password_verify($password, $admin['password'])) {
            return redirect()->back()
                             ->withInput()
                             ->with('error', lang('Admin.invalid_credentials'));
        }

        // Start session
        session()->set([
            'admin_logged_in' => true,
            'admin_id'        => $admin['id'],
            'admin_name'      => $admin['name'],
            'admin_email'     => $admin['email'],
            'admin_role'      => $admin['role'],
        ]);

        $this->adminModel->touchLogin($admin['id']);

        // Log activity
        model('App\Models\ActivityLogModel')->log('login', 'auth', $admin['id'], 'Admin login');

        return redirect()->to(site_url('admin/dashboard'));
    }

    // ----------------------------------------------------------------
    // GET /logout
    // ----------------------------------------------------------------
    public function logout()
    {
        model('App\Models\ActivityLogModel')->log('logout', 'auth');
        session()->destroy();
        return redirect()->to(site_url('login'));
    }

    // ----------------------------------------------------------------
    // GET /forgot-password
    // ----------------------------------------------------------------
    public function forgot(): string
    {
        return view('auth/forgot_password');
    }

    // ----------------------------------------------------------------
    // POST /forgot-password
    // ----------------------------------------------------------------
    public function sendReset()
    {
        $email = $this->request->getPost('email', FILTER_SANITIZE_EMAIL);
        $admin = $this->adminModel->where('email', $email)->first();

        if ($admin) {
            $token   = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
            $this->adminModel->setResetToken($admin['id'], $token, $expires);

            // In production: send email with reset link
            // For now: store in flash for dev testing
            $this->flashSuccess(lang('Admin.reset_link_sent') . ' (dev token: ' . $token . ')');
        } else {
            // Same message to prevent email enumeration
            $this->flashSuccess(lang('Admin.reset_link_sent'));
        }

        return redirect()->to(site_url('login'));
    }

    // ----------------------------------------------------------------
    // GET /reset-password/:token
    // ----------------------------------------------------------------
    public function resetForm(string $token): string
    {
        $admin = $this->adminModel->findByResetToken($token);
        if (! $admin) {
            $this->flashError(lang('Admin.invalid_reset_token'));
            return redirect()->to(site_url('login'))->send() ?: '';
        }
        return view('auth/reset_password', ['token' => $token]);
    }

    // ----------------------------------------------------------------
    // POST /reset-password
    // ----------------------------------------------------------------
    public function resetPassword()
    {
        $token    = $this->request->getPost('token');
        $password = $this->request->getPost('password');
        $confirm  = $this->request->getPost('confirm_password');

        if ($password !== $confirm || strlen($password) < 8) {
            $this->flashError(lang('Admin.password_mismatch'));
            return redirect()->back()->withInput();
        }

        $admin = $this->adminModel->findByResetToken($token);
        if (! $admin) {
            $this->flashError(lang('Admin.invalid_reset_token'));
            return redirect()->to(site_url('login'));
        }

        $this->adminModel->update($admin['id'], [
            'password' => password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]),
        ]);
        $this->adminModel->clearResetToken($admin['id']);

        $this->flashSuccess(lang('Admin.password_reset_success'));
        return redirect()->to(site_url('login'));
    }
}
