<?php
require_once 'includes/database.php';

class Auth {
    private $db;
    
    public function __construct() {
        global $db;
        $this->db = $db;
    }
    
    public function login($username, $password) {
        $username = $this->db->escape($username);
        
        $sql = "SELECT * FROM users WHERE username = '$username' AND status = 1";
        $result = $this->db->query($sql);
        
        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            
            if (password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['logged_in'] = true;
                
                // Update last login
                $update_sql = "UPDATE users SET updated_at = NOW() WHERE id = " . $user['id'];
                $this->db->query($update_sql);
                
                return true;
            }
        }
        
        return false;
    }
    
    public function logout() {
        session_destroy();
        header('Location: ../auth/login.php');
        exit();
    }
    
    public function isLoggedIn() {
        return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
    }
    
    public function requireLogin() {
        if (!$this->isLoggedIn()) {
            header('Location: ../auth/login.php');
            exit();
        }
    }
    
    public function requireRole($allowedRoles) {
        $this->requireLogin();
        
        if (!in_array($_SESSION['role'], (array)$allowedRoles)) {
            header('Location: ../dashboard.php');
            exit();
        }
    }
    
    public function getCurrentUser() {
        if ($this->isLoggedIn()) {
            return [
                'id' => $_SESSION['user_id'],
                'username' => $_SESSION['username'],
                'role' => $_SESSION['role'],
                'full_name' => $_SESSION['full_name']
            ];
        }
        return null;
    }
}

$auth = new Auth();
?>