<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\SecurityLogModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Email\Email;

class Auth extends BaseController
{
    protected $userModel;
    protected $securityLogModel;
    protected $email;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->securityLogModel = new SecurityLogModel();
        $this->email = \Config\Services::email();
    }

    /**
     * Display the login form
     *
     * @return string
     */
    public function login()
    {
        // If user is already logged in, redirect to dashboard
        if (session()->get('user_id')) {
            return redirect()->to('/dashboard');
        }

        return view('login');
    }

    /**
     * Process the login form
     *
     * @return ResponseInterface
     */
    public function attemptLogin()
    {
        // Check rate limiting
        if ($this->isRateLimited()) {
            // Log the rate limiting event
            $this->securityLogModel->logEvent(null, 'login_rate_limit', 'Login attempt blocked due to rate limiting from IP: ' . $this->request->getIPAddress(), 'medium');
            
            session()->setFlashdata('error', 'Too many login attempts. Please try again later.');
            return redirect()->back()->withInput();
        }

        // Validate input
        $rules = [
            'username' => [
                'rules' => 'required|min_length[3]|max_length[50]',
                'errors' => [
                    'required' => 'Username is required',
                    'min_length' => 'Username must be at least 3 characters long',
                    'max_length' => 'Username cannot exceed 50 characters',
                ]
            ],
            'password' => [
                'rules' => 'required|min_length[8]',
                'errors' => [
                    'required' => 'Password is required',
                    'min_length' => 'Password must be at least 8 characters long',
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            return view('login', [
                'validation' => $this->validator,
            ]);
        }

        // Get input data
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        // Find user by username
        $user = $this->userModel->findByUsername($username);
        
        // Debug: Log user info (remove this in production)
        log_message('debug', 'Login attempt for username: ' . $username);
        if ($user) {
            log_message('debug', 'User found: ' . print_r($user, true));
            log_message('debug', 'Password verify result: ' . (password_verify($password, $user['password']) ? 'true' : 'false'));
        } else {
            log_message('debug', 'User not found');
        }

        // Check if user exists and password is correct
        if ($user && password_verify($password, $user['password'])) {
            // Reset failed login attempts
            session()->remove('failed_login_attempts');
            session()->remove('last_failed_attempt');
            
            // Update last login time
            $this->userModel->updateLastLogin($user['id']);
            
            // Store user data in session
            $sessionData = [
                'user_id'  => $user['id'],
                'username' => $user['username'],
                'role'     => $user['role'],
                'isLoggedIn' => true,
                'last_login' => $user['last_login'] // Store previous login time in session
            ];

            session()->set($sessionData);
            
            // Regenerate session ID for security
            session()->regenerate();
            
            // Log successful login
            $this->securityLogModel->logEvent($user['id'], 'login_success', 'User successfully logged in', 'low');
            
            // Redirect to dashboard
            return redirect()->to('/dashboard');
        } else {
            // Record failed login attempt
            $this->recordFailedAttempt();
            
            // Log failed login attempt
            $userId = $user['id'] ?? null;
            $this->securityLogModel->logEvent($userId, 'login_failed', 'Failed login attempt for username: ' . $username, 'medium');
            
            // Set error message
            session()->setFlashdata('error', 'Invalid username or password.');
            
            return redirect()->back()->withInput();
        }
    }

    /**
     * Check if user is rate limited
     *
     * @return bool
     */
    private function isRateLimited()
    {
        $maxAttempts = 5;
        $timeWindow = 900; // 15 minutes in seconds
        
        $attempts = session()->get('failed_login_attempts') ?? 0;
        $lastAttempt = session()->get('last_failed_attempt');
        
        // If no previous attempts, not rate limited
        if ($attempts === 0) {
            return false;
        }
        
        // If time window has passed, reset attempts
        if ($lastAttempt && (time() - strtotime($lastAttempt)) > $timeWindow) {
            session()->remove('failed_login_attempts');
            session()->remove('last_failed_attempt');
            return false;
        }
        
        // If max attempts reached, rate limited
        return $attempts >= $maxAttempts;
    }
    
    /**
     * Record failed login attempt
     *
     * @return void
     */
    private function recordFailedAttempt()
    {
        $attempts = session()->get('failed_login_attempts') ?? 0;
        $attempts++;
        
        session()->set('failed_login_attempts', $attempts);
        session()->set('last_failed_attempt', date('Y-m-d H:i:s'));
    }

    /**
     * Logout the user
     *
     * @return ResponseInterface
     */
    public function logout()
    {
        // Get user info before destroying session for email notification
        $userId = session()->get('user_id');
        $user = null;
        if ($userId) {
            $user = $this->userModel->find($userId);
        }
        
        // Log the logout event
        if ($userId) {
            $this->securityLogModel->logEvent($userId, 'logout', 'User logged out successfully', 'low');
        }
        
        // Destroy session
        session()->destroy();
        
        // Send logout notification email if user was logged in
        if ($user) {
            $this->sendLogoutNotification($user);
        }
        
        // Redirect to login page
        return redirect()->to('/login');
    }
    
    /**
     * Send logout notification email
     *
     * @param array $user
     * @return void
     */
    private function sendLogoutNotification($user)
    {
        if (!empty($user['email'])) {
            $this->email->setTo($user['email']);
            $this->email->setSubject('Account Logout Notification - Labourdnhdd CMS');
            $this->email->setMessage($this->getLogoutEmailTemplate($user));
            $this->email->send();
        }
    }
    
    /**
     * Get logout email template
     *
     * @param array $user
     * @return string
     */
    private function getLogoutEmailTemplate($user)
    {
        $template = '
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #5EC9F8 0%, #3A82D4 50%, #214D8C 100%); color: white; padding: 20px; text-align: center; }
                .content { background: #f9f9f9; padding: 30px; border: 1px solid #ddd; }
                .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
                .logo { max-width: 150px; margin: 0 auto 20px; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <img src="cid:labourdnhdd_logo" alt="Labourdnhdd Logo" class="logo">
                    <h1>Labourdnhdd - CMS</h1>
                    <p>Companies Management System</p>
                </div>
                <div class="content">
                    <h2>Account Logout Notification</h2>
                    <p>Hello ' . htmlspecialchars($user['username']) . ',</p>
                    <p>This is a notification to inform you that your Labourdnhdd Companies Management System account was successfully logged out at ' . date('Y-m-d H:i:s') . '.</p>
                    <p>If you did not initiate this logout, please <a href="' . base_url('/forgot-password') . '">reset your password</a> immediately.</p>
                    <p>Thank you,<br>The Labourdnhdd Team</p>
                </div>
                <div class="footer">
                    <p>This is an automated message. Please do not reply to this email.</p>
                    <p>&copy; ' . date('Y') . ' Labourdnhdd - Companies Management System. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>';

        return $template;
    }
}