<?php
// helpers/auth.php

require_once __DIR__ . '/response.php';
require_once __DIR__ . '/request.php';
require_once __DIR__ . '/../vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

define('JWT_SECRET', 'gqMMHpK0t49m429j4C.dQ/gO/2uXsHPHazBwIudnd.xD3O1Vi.');

function requireAuth() {
    $token = getBearerToken();
    
    if (!$token) {
        sendError('Authentication required. Please login.', 401);
    }
    
    try {
        $decoded = JWT::decode($token, new Key(JWT_SECRET, 'HS256'));
        
        return [
            'id' => $decoded->user_id,
            'email' => $decoded->email,
            'role_id' => $decoded->role_id,
            'role' => $decoded->role
        ];
        
    } catch (Firebase\JWT\ExpiredException $e) {
        sendError('Token expired. Please login again.', 401);
    } catch (Firebase\JWT\SignatureInvalidException $e) {
        sendError('Invalid token signature.', 401);
    } catch (Exception $e) {
        sendError('Invalid token. Please login again.', 401);
    }
}

function requireAdmin() {
    $user = requireAuth();
    
    if ($user['role_id'] != 1) {
        sendError('Admin access required', 403);
    }
    
    return $user;
}

function hasPermission($user, $permissionName) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM role_permissions rp
            JOIN permissions p ON p.id = rp.permission_id
            WHERE rp.role_id = :role_id AND p.name = :permission
        ");
        $stmt->execute([
            ':role_id' => $user['role_id'],
            ':permission' => $permissionName
        ]);
        
        return $stmt->fetchColumn() > 0;
        
    } catch (PDOException $e) {
        // If error, deny permission
        return false;
    }
}

function requirePermission($permissionName) {
    $user = requireAuth();
    
    if (!hasPermission($user, $permissionName)) {
        sendError('You do not have permission to perform this action', 403);
    }
    
    return $user;
}
?>