<?php

namespace App\Controllers;

class AuthController {
    private $pdo;
    private $config;
    
    public function __construct($pdo, $config) {
        $this->pdo = $pdo;
        $this->config = $config;
    }
    
    public function login() {
        if (is_logged_in()) {
            $user = current_user();
            redirect(base_url(role_home_url($user)));
        }
        
        $error = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                $error = 'Invalid request. Please try again.';
            } else {
                $email = trim($_POST['email'] ?? '');
                $password = $_POST['password'] ?? '';
                
                $stmt = $this->pdo->prepare("SELECT u.*, r.name as role_name, r.slug as role_slug FROM users u JOIN roles r ON u.role_id = r.id WHERE u.email = ? AND u.is_active = 1");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && password_verify($password, $user['password_hash'])) {
                    if ($user['is_locked'] && $user['locked_until'] && new \DateTime() < new \DateTime($user['locked_until'])) {
                        $error = 'Account is temporarily locked. Please try again later.';
                    } else {
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['role_slug'] = $user['role_slug'];
                        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                        
                        $this->pdo->prepare("UPDATE users SET last_login_at = NOW(), last_login_ip = ?, failed_login_attempts = 0 WHERE id = ?")
                            ->execute([$_SERVER['REMOTE_ADDR'] ?? '', $user['id']]);
                        
                        log_activity($user['id'], 'login', 'User logged in', ['email' => $email]);
                        log_audit($user['id'], 'login', 'user', $user['id']);
                        
                        redirect(base_url(role_home_url($user)));
                    }
                } else {
                    if ($user) {
                        $attempts = $user['failed_login_attempts'] + 1;
                        $lockUntil = null;
                        if ($attempts >= 5) {
                            $lockUntil = date('Y-m-d H:i:s', time() + 900);
                        }
                        $this->pdo->prepare("UPDATE users SET failed_login_attempts = ?, locked_until = ? WHERE id = ?")
                            ->execute([$attempts, $lockUntil, $user['id']]);
                    }
                    $error = 'Invalid email or password.';
                }
            }
        }
        
        $theme = get_setting('default_theme', 'orbit-dark');
        include __DIR__ . '/../Views/layouts/public.php';
        include __DIR__ . '/../Views/auth/login.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function logout() {
        if (is_logged_in()) {
            log_activity($_SESSION['user_id'], 'logout', 'User logged out');
        }
        session_destroy();
        redirect(base_url('login'));
    }
    
    public function forgotPassword() {
        $error = '';
        $success = '';
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = trim($_POST['email'] ?? '');
            $stmt = $this->pdo->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();
            
            if ($user) {
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', time() + 3600);
                $this->pdo->prepare("UPDATE users SET password_reset_token = ?, password_reset_expires = ? WHERE id = ?")
                    ->execute([$token, $expires, $user['id']]);
                
                $resetLink = base_url('reset-password?token=' . $token);
                $body = '<p>Click the link below to reset your password:</p><p><a href="' . $resetLink . '">Reset Password</a></p><p>This link expires in 1 hour.</p>';
                send_email($user['email'], 'Reset Your CIX Orbit Academy Password', $body);
                $success = 'Password reset link sent to your email.';
            } else {
                $success = 'If an account with that email exists, a reset link has been sent.';
            }
        }
        
        $theme = get_setting('default_theme', 'orbit-dark');
        include __DIR__ . '/../Views/layouts/public.php';
        include __DIR__ . '/../Views/auth/forgot_password.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function resetPassword() {
        $token = $_GET['token'] ?? '';
        $error = '';
        $success = '';
        
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE password_reset_token = ? AND password_reset_expires > NOW()");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            $error = 'Invalid or expired reset token.';
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $password = $_POST['password'] ?? '';
            $confirm = $_POST['confirm_password'] ?? '';
            
            if (strlen($password) < 8) {
                $error = 'Password must be at least 8 characters.';
            } elseif ($password !== $confirm) {
                $error = 'Passwords do not match.';
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $this->pdo->prepare("UPDATE users SET password_hash = ?, password_reset_token = NULL, password_reset_expires = NULL WHERE id = ?")
                    ->execute([$hash, $user['id']]);
                $success = 'Password reset successfully. You can now login.';
            }
        }
        
        $theme = get_setting('default_theme', 'orbit-dark');
        include __DIR__ . '/../Views/layouts/public.php';
        include __DIR__ . '/../Views/auth/reset_password.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
}
