<?php
class Auth {
    private $db;

    public function __construct($db) {
        $this->db = $db;
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    }

    // ✅ LOGIN
    public function login($email, $password) {
        $query = "SELECT id, name, email, password, role, is_active 
                  FROM users 
                  WHERE email = :email AND is_active = 1";
        $user = $this->db->fetch($query, [':email' => $email]);

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['user_role'] = $user['role'];

            $this->logAction($user['id'], 'login', 'User logged in successfully');
            return true;
        }
        return false;
    }

    // ✅ REGISTER
    public function register($name, $email, $password) {
        if (!$this->isEmailAvailable($email)) {
            return false;
        }

        $hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        $role = ($email === 'admin123@gmail.com') ? 'admin' : 'user';

        $data = [
            'name' => $name,
            'email' => $email,
            'password' => $hashed_password,
            'role' => $role,
            'is_active' => 0,  // Inactive until email is verified
            'created_at' => date('Y-m-d H:i:s')
        ];

        $user_id = $this->db->insert('users', $data);

        if ($user_id) {
            // Create wallet with 100 coins welcome bonus
            $this->db->insert('wallets', ['user_id' => $user_id, 'balance' => 100.00]);
            $this->db->insert('permissions', ['user_id' => $user_id]);
            $this->logAction($user_id, 'register', 'User registered with 100 coins welcome bonus - waiting for email verification');
            return true;
        }

        return false;
    }

    // ✅ LOGOUT
    public function logout() {
        if (isset($_SESSION['user_id'])) {
            $this->logAction($_SESSION['user_id'], 'logout', 'User logged out');
        }
        session_destroy();
        header('Location: /extract/login.php');
        exit();
    }

    // ✅ CHECK LOGIN
    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }

    // ✅ CHECK ADMIN
    public function isAdmin() {
        return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
    }

    // ✅ GET CURRENT USER
    public function getCurrentUser() {
        if ($this->isLoggedIn()) {
            return [
                'id' => $_SESSION['user_id'],
                'name' => $_SESSION['user_name'],
                'email' => $_SESSION['user_email'],
                'role' => $_SESSION['user_role']
            ];
        }
        return null;
    }

    // ✅ CHECK EMAIL
    private function isEmailAvailable($email) {
        $query = 'SELECT id FROM users WHERE email = ?';
        $result = $this->db->fetch($query, [$email]);
        return !$result;
    }

    // ✅ LOG ACTION
    private function logAction($user_id, $action, $details) {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $this->db->insert('audit_logs', [
            'user_id' => $user_id,
            'action' => $action,
            'details' => $details,
            'ip_address' => $ip,
            'user_agent' => $user_agent,
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }

    // ✅ REDIRECT BASED ON ROLE
    public function redirectBasedOnRole() {
        if (!$this->isLoggedIn()) {
            header('Location: /extract/login.php');
            exit();
        }

        if ($this->isAdmin()) {
            header('Location: /extract/admin/dashboard.php');
        } else {
            header('Location: /extract/user/dashboard.php');
        }
        exit();
    }
}
?>
