<?php

class UserType
{
    private $pdo;
    
    public function __construct()
    {
        $this->pdo = $GLOBALS['pdo'];
    }
    
    public function create($data)
    {
        $sql = "INSERT INTO user_types (name, description, permissions, color, is_active, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
        $stmt = $this->pdo->prepare($sql);
        $result = $stmt->execute([
            $data['name'],
            $data['description'] ?? '',
            json_encode($data['permissions'] ?? []),
            $data['color'] ?? '#007bff',
            $data['is_active'] ?? 1
        ]);
        if ($result) {
            $id = $this->pdo->lastInsertId();
            $this->logAudit('create','user_type',$id,[
                'name'=>$data['name'],
                'permissions'=>$data['permissions'] ?? []
            ]);
        }
        return $result;
    }
    
    public function findById($id)
    {
        $sql = "SELECT * FROM user_types WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$id]);
        
        $userType = $stmt->fetch();
        if ($userType) {
            if (!empty($userType['permissions'])) {
                $decoded = json_decode($userType['permissions'], true);
                $userType['permissions'] = $decoded ?: [];
            } else {
                $userType['permissions'] = [];
            }
        }
        
        return $userType;
    }
    
    public function findByName($name)
    {
        $sql = "SELECT * FROM user_types WHERE name = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$name]);
        
        $userType = $stmt->fetch();
        if ($userType) {
            if (!empty($userType['permissions'])) {
                $decoded = json_decode($userType['permissions'], true);
                $userType['permissions'] = $decoded ?: [];
            } else {
                $userType['permissions'] = [];
            }
        }
        
        return $userType;
    }
    
    public function getAll($activeOnly = false)
    {
        $sql = "SELECT * FROM user_types";
        if ($activeOnly) {
            $sql .= " WHERE is_active = 1";
        }
        $sql .= " ORDER BY name ASC";
        
        $stmt = $this->pdo->query($sql);
        $userTypes = $stmt->fetchAll();
        
        // Decode permissions for each user type
        foreach ($userTypes as &$userType) {
            if (!empty($userType['permissions'])) {
                $decoded = json_decode($userType['permissions'], true);
                $userType['permissions'] = $decoded ?: [];
            } else {
                $userType['permissions'] = [];
            }
        }
        
        return $userTypes;
    }
    
    public function update($id, $data)
    {
        $before = $this->findById($id);
        $sql = "UPDATE user_types SET name = ?, description = ?, permissions = ?, color = ?, is_active = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        $result = $stmt->execute([
            $data['name'],
            $data['description'] ?? '',
            json_encode($data['permissions'] ?? []),
            $data['color'] ?? '#007bff',
            $data['is_active'] ?? 1,
            $id
        ]);
        if ($result) {
            $after = $this->findById($id);
            $this->logAudit('update','user_type',$id,[
                'before'=>$before ? ['name'=>$before['name'],'permissions'=>$before['permissions']] : null,
                'after'=>['name'=>$after['name'],'permissions'=>$after['permissions']]
            ]);
        }
        return $result;
    }
    
    public function delete($id)
    {
        // Check if any users are using this type
        $sql = "SELECT COUNT(*) FROM users WHERE user_type_id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$id]);
        
        if ($stmt->fetchColumn() > 0) {
            return false; // Cannot delete user type that's in use
        }
        
        $sql = "DELETE FROM user_types WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        $before = $this->findById($id);
        $result = $stmt->execute([$id]);
        if ($result) {
            $this->logAudit('delete','user_type',$id,[
                'before'=>$before ? ['name'=>$before['name']] : null
            ]);
        }
        return $result;
    }
    
    public function getAvailablePermissions()
    {
        return [
            'users' => [
                'view' => 'View Users',
                'create' => 'Create Users',
                'edit' => 'Edit Users',
                'delete' => 'Delete Users'
            ],
            'user_types' => [
                'view' => 'View User Types',
                'create' => 'Create User Types',
                'edit' => 'Edit User Types',
                'delete' => 'Delete User Types'
            ],
            'dashboard' => [
                'view' => 'View Dashboard',
                'admin' => 'Admin Dashboard Access'
            ],
            'system' => [
                'settings' => 'System Settings',
                'logs' => 'View System Logs',
                'backup' => 'Backup System'
            ]
        ];
    }
    
    public function hasPermission($userTypeId, $permission)
    {
        $userType = $this->findById($userTypeId);
        if (!$userType || !$userType['permissions']) {
            return false;
        }
        
        $parts = explode('.', $permission);
        $permissions = $userType['permissions'];
        
        foreach ($parts as $part) {
            if (!isset($permissions[$part])) {
                return false;
            }
            $permissions = $permissions[$part];
        }
        
        return $permissions === true;
    }

    private function logAudit($action,$entityType,$entityId,$details=[]) {
        if (!isset($GLOBALS['pdo'])) return; // safety
        require_once __DIR__ . '/AuditLog.php';
        try {
            $logger = new AuditLog();
            $actorId = $_SESSION['user_id'] ?? null;
            $logger->record($actorId,$action,$entityType,$entityId,$details);
        } catch (Exception $e) {
            // swallow
        }
    }
}
