// ========== STATISTIKA ZA ODREĐENOG AGENTA (admin) ========== if (path === '/api/agent-stats' && method === 'GET') { const auth = verifyToken(request.headers.get('Authorization')); if (!auth || auth.role !== 'admin') { return new Response(JSON.stringify({ error: 'Nemate dozvolu' }), { status: 403, headers }); } try { const agentId = url.searchParams.get('agent_id'); const month = url.searchParams.get('month') || `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`; if (!agentId) { return new Response(JSON.stringify({ error: 'agent_id je obavezan' }), { status: 400, headers }); } const { results } = await env.DB.prepare( `SELECT COUNT(*) as count, COALESCE(SUM(final_price), 0) as total_value FROM sales WHERE agent_id = ? AND month_year = ? AND (status = 'dostavljeno' OR status = 'placeno_karticno')` ).bind(agentId, month).all(); const count = results[0]?.count || 0; const totalValue = results[0]?.total_value || 0; let percent = 0; if (count >= 1 && count <= 9) percent = 25; else if (count >= 10 && count <= 19) percent = 30; else if (count >= 20) percent = 35; let bonus = 0; if (count >= 40 && count <= 49) bonus = 500; else if (count >= 50) bonus = 1000; const commission = (totalValue * percent / 100) + bonus; return new Response(JSON.stringify({ sales_count: count, total_value: totalValue, commission_percent: percent, bonus: bonus, total_commission: commission }), { headers }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, headers }); } }