<?php
// classes/PermissionManager.php
// This class handles all logic related to checking and requesting user permissions for data sources.

class PermissionManager
{
    private $pdo;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * Checks if a specific person has a specific permission for a data source.
     * @param int $personId The ID of the person.
     * @param int $dataSourceId The ID of the data source.
     * @param string $permissionType The type of permission to check ('Read' or 'Download').
     * @return bool True if the permission exists, false otherwise.
     */
    public function hasPermission($personId, $dataSourceId, $permissionType)
    {
        try {
            // Using a prepared statement to prevent SQL injection
            $sql = "SELECT COUNT(*) FROM dspsds_person_permissions 
                    WHERE fk_dspsdspp_person_id = :personId 
                    AND fk_dspsdspp_dspsds_id = :dataSourceId
                    AND dspsdspp_permission = :permissionType";
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':personId', $personId, PDO::PARAM_INT);
            $stmt->bindParam(':dataSourceId', $dataSourceId, PDO::PARAM_INT);
            $stmt->bindParam(':permissionType', $permissionType, PDO::PARAM_STR);
            
            $stmt->execute();
            
            return $stmt->fetchColumn() > 0;

        } catch (PDOException $e) {
            // Log the error but don't expose it to the user
            error_log("Database error in hasPermission: " . $e->getMessage());
            return false;
        }
    }
}
