<?php
require_once __DIR__ . '/../../helpers/response.php';
require_once __DIR__ . '/../../helpers/security.php';
require_once __DIR__ . '/../../helpers/auth.php';
require_once __DIR__ . '/../Models/Vendor.php';

class VendorAuthMiddleware {
    public static function authenticate() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? '';

        if (empty($authHeader) || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            sendError('Unauthorized', [], 401);
        }

        $token = $matches[1];
        $payload = verifyJWT($token);

        if (!$payload) {
            sendError('Invalid or expired token', [], 401);
        }

        if (!isset($payload['type']) || $payload['type'] !== 'vendor') {
            sendError('Forbidden: Vendor access required', [], 403);
        }

        return $payload;
    }

    public static function enforceApproved($payload) {
        $vendorId = $payload['id'];
        $vendor = (new Vendor())->find($vendorId);
        
        if (!$vendor) {
            sendError('Vendor not found', [], 404);
        }
        
        if ($vendor['status'] !== 'approved') {
            sendError('Account is not active or approved. Current status: ' . $vendor['status'], ['status' => $vendor['status']], 403);
        }
        return $vendor;
    }

    public static function enforceDocumentAccess($payload) {
        $vendorId = $payload['id'];
        $vendor = (new Vendor())->find($vendorId);
        
        if (!$vendor) {
            sendError('Vendor not found', [], 404);
        }
        
        if (in_array($vendor['status'], ['suspended', 'rejected'])) {
            sendError('Account is ' . $vendor['status'] . '. Access denied.', ['status' => $vendor['status']], 403);
        }
        return $vendor;
    }
}
